opencode-rag-plugin 2.9.3 → 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 +99 -1
- package/dist/core/config.js +148 -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/plugin.d.ts +14 -9
- package/dist/plugin.js +50 -28
- package/dist/safety/shell-guard.d.ts +157 -0
- package/dist/safety/shell-guard.js +412 -0
- package/dist/v2/v2-adapter.d.ts +49 -3
- package/dist/v2/v2-adapter.js +63 -7
- package/package.json +1 -1
|
@@ -0,0 +1,412 @@
|
|
|
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 { statSync } from "node:fs";
|
|
23
|
+
import path from "node:path";
|
|
24
|
+
import { DEFAULT_CONFIG, loadWorkspaceConfig, resolveConfigPaths, resolveLogConfig } from "../core/config.js";
|
|
25
|
+
import { appendDebugLog } from "../core/fileLogger.js";
|
|
26
|
+
import { createDecisionProvider } from "../decision/factory.js";
|
|
27
|
+
/** Tool names whose command text is vetted (V2 `shell`, V1-style `bash`). */
|
|
28
|
+
export const SHELL_GUARD_TOOL_NAMES = ["shell", "bash"];
|
|
29
|
+
/** Fallback decision config when neither shellGuard nor decision provide one. */
|
|
30
|
+
const FALLBACK_DECISION = {
|
|
31
|
+
enabled: false,
|
|
32
|
+
provider: "ollama",
|
|
33
|
+
baseUrl: "http://127.0.0.1:11434/api",
|
|
34
|
+
model: "tev1:4b",
|
|
35
|
+
timeoutMs: 120000,
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Questions asked of the decision model for every command.
|
|
39
|
+
*
|
|
40
|
+
* Two `noul` questions drive the pass/fail decision (either one reaching the
|
|
41
|
+
* threshold flags the command); the `choice` question only labels the risk so
|
|
42
|
+
* the confirmation prompt explains *why* it was flagged.
|
|
43
|
+
*/
|
|
44
|
+
export const SHELL_GUARD_QUESTIONS = [
|
|
45
|
+
{
|
|
46
|
+
id: "destructive",
|
|
47
|
+
type: "noul",
|
|
48
|
+
instructions: "Could this shell command delete, overwrite, move, or irreversibly modify files, databases, or system state beyond a normal edit, build, or test operation?",
|
|
49
|
+
criteria: {
|
|
50
|
+
true: "Deletes/overwrites data or irreversibly changes files or system state",
|
|
51
|
+
false: "Normal, reversible, or read-only operation",
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
id: "malicious",
|
|
56
|
+
type: "noul",
|
|
57
|
+
instructions: "Does this shell command show malicious intent — exfiltrating data, disabling security controls, privilege escalation, obfuscated payloads, or unexpected remote writes?",
|
|
58
|
+
criteria: {
|
|
59
|
+
true: "Exfiltration, security tampering, privilege escalation, or hidden payloads",
|
|
60
|
+
false: "Ordinary development or administration command",
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
id: "category",
|
|
65
|
+
type: "choice",
|
|
66
|
+
instructions: "Which category best describes the risk of this command?",
|
|
67
|
+
criteria: {
|
|
68
|
+
none: "No destructive or malicious behavior",
|
|
69
|
+
delete_files: "Deletes or overwrites files or directories",
|
|
70
|
+
format_disk: "Formats a disk, partition, or block device",
|
|
71
|
+
process_kill: "Kills processes or restarts services",
|
|
72
|
+
network: "Sends data to or pulls code from a remote host",
|
|
73
|
+
config_tamper: "Changes system or security configuration",
|
|
74
|
+
privilege: "Elevates privileges",
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
];
|
|
78
|
+
/** Case-insensitive test for a shell-execution tool name. */
|
|
79
|
+
export function isShellToolName(name) {
|
|
80
|
+
if (!name)
|
|
81
|
+
return false;
|
|
82
|
+
return SHELL_GUARD_TOOL_NAMES.includes(name.toLowerCase());
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Truncate an oversized command for the decision model.
|
|
86
|
+
*
|
|
87
|
+
* The model's effective context is small (~2k tokens), so keep the head and
|
|
88
|
+
* the tail — destructive payloads usually appear at one end — and mark the
|
|
89
|
+
* omission explicitly.
|
|
90
|
+
*/
|
|
91
|
+
export function buildShellGuardState(command, maxChars = 8000) {
|
|
92
|
+
const trimmed = command.trim();
|
|
93
|
+
if (maxChars <= 0 || trimmed.length <= maxChars)
|
|
94
|
+
return trimmed;
|
|
95
|
+
const marker = "\n…[truncated by shell guard]…\n";
|
|
96
|
+
const headLen = Math.floor(maxChars * 0.6);
|
|
97
|
+
const tailLen = Math.max(0, maxChars - headLen - marker.length);
|
|
98
|
+
return `${trimmed.slice(0, headLen)}${marker}${tailLen > 0 ? trimmed.slice(-tailLen) : ""}`;
|
|
99
|
+
}
|
|
100
|
+
/** Clamp a probability into [0, 1]; non-numeric answers degrade to 0. */
|
|
101
|
+
function clampProbability(value) {
|
|
102
|
+
if (typeof value !== "number" || Number.isNaN(value))
|
|
103
|
+
return 0;
|
|
104
|
+
return Math.min(1, Math.max(0, value));
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Convert raw decision answers into a guard verdict.
|
|
108
|
+
*
|
|
109
|
+
* Exported for tests; production callers use {@link ShellGuard.evaluate}.
|
|
110
|
+
*/
|
|
111
|
+
export function verdictFromDecisionResult(result, opts) {
|
|
112
|
+
let destructive = 0;
|
|
113
|
+
let malicious = 0;
|
|
114
|
+
let category = "none";
|
|
115
|
+
for (const answer of result.answers) {
|
|
116
|
+
if (answer.id === "destructive")
|
|
117
|
+
destructive = clampProbability(answer.noul);
|
|
118
|
+
else if (answer.id === "malicious")
|
|
119
|
+
malicious = clampProbability(answer.noul);
|
|
120
|
+
else if (answer.id === "category" && typeof answer.choice === "string" && answer.choice.length > 0) {
|
|
121
|
+
category = answer.choice;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const flagged = destructive >= opts.threshold || malicious >= opts.threshold;
|
|
125
|
+
const verdict = {
|
|
126
|
+
flagged,
|
|
127
|
+
destructive,
|
|
128
|
+
malicious,
|
|
129
|
+
category,
|
|
130
|
+
reason: "",
|
|
131
|
+
provider: opts.provider,
|
|
132
|
+
model: opts.model,
|
|
133
|
+
latencyMs: opts.latencyMs,
|
|
134
|
+
cached: opts.cached ?? false,
|
|
135
|
+
};
|
|
136
|
+
// The reason is only consumed when a command is escalated; clean verdicts
|
|
137
|
+
// stay message-free so a caller cannot accidentally prompt for them.
|
|
138
|
+
if (flagged)
|
|
139
|
+
verdict.reason = formatShellGuardReason(verdict);
|
|
140
|
+
return verdict;
|
|
141
|
+
}
|
|
142
|
+
/** Build the message shown in the permission prompt. */
|
|
143
|
+
export function formatShellGuardReason(verdict) {
|
|
144
|
+
if (verdict.error) {
|
|
145
|
+
return (`ShellGuard could not classify this command (${verdict.error}) — ` +
|
|
146
|
+
`confirmation required by shellGuard.onError = "ask".`);
|
|
147
|
+
}
|
|
148
|
+
const category = verdict.category && verdict.category !== "none" ? ` (category: ${verdict.category})` : "";
|
|
149
|
+
return (`ShellGuard flagged this command with ${verdict.provider}/${verdict.model}: ` +
|
|
150
|
+
`destructive p=${verdict.destructive.toFixed(2)}, malicious p=${verdict.malicious.toFixed(2)}${category}. ` +
|
|
151
|
+
`Confirm before running.`);
|
|
152
|
+
}
|
|
153
|
+
/** Short, log-safe error description. */
|
|
154
|
+
function describeError(error) {
|
|
155
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
156
|
+
return message.length > 160 ? `${message.slice(0, 157)}…` : message;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Classify shell commands and cache verdicts.
|
|
160
|
+
*
|
|
161
|
+
* One instance lives for the lifetime of the plugin registration. Provider
|
|
162
|
+
* instances are re-created only when the endpoint/model signature changes, so
|
|
163
|
+
* a config edit (e.g. switching tev1 → Clef-Flash) takes effect without a
|
|
164
|
+
* restart.
|
|
165
|
+
*/
|
|
166
|
+
export class ShellGuard {
|
|
167
|
+
deps;
|
|
168
|
+
cache = new Map();
|
|
169
|
+
now;
|
|
170
|
+
createProvider;
|
|
171
|
+
providerState;
|
|
172
|
+
constructor(deps = {}) {
|
|
173
|
+
this.deps = deps;
|
|
174
|
+
this.now = deps.now ?? Date.now;
|
|
175
|
+
this.createProvider = deps.createProvider ?? createDecisionProvider;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Classify one command.
|
|
179
|
+
*
|
|
180
|
+
* Returns a non-flagged verdict when the guard is disabled or when the
|
|
181
|
+
* classifier fails under `onError: "allow"` (fail-open). Never throws.
|
|
182
|
+
*/
|
|
183
|
+
async evaluate(command, abort) {
|
|
184
|
+
const cfg = this.deps.getConfig?.();
|
|
185
|
+
if (!cfg) {
|
|
186
|
+
return {
|
|
187
|
+
flagged: false,
|
|
188
|
+
destructive: 0,
|
|
189
|
+
malicious: 0,
|
|
190
|
+
category: "none",
|
|
191
|
+
reason: "",
|
|
192
|
+
provider: "",
|
|
193
|
+
model: "",
|
|
194
|
+
latencyMs: 0,
|
|
195
|
+
cached: false,
|
|
196
|
+
skipped: true,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
const { guard, decision, logging } = cfg;
|
|
200
|
+
const signature = `${decision.provider}|${decision.baseUrl}|${decision.model}`;
|
|
201
|
+
const cacheKey = `${signature}\u0000${command}`;
|
|
202
|
+
const cacheTtlMs = guard.cacheTtlMs ?? 0;
|
|
203
|
+
if (cacheTtlMs > 0) {
|
|
204
|
+
const hit = this.cache.get(cacheKey);
|
|
205
|
+
if (hit) {
|
|
206
|
+
if (this.now() - hit.ts < hit.ttlMs) {
|
|
207
|
+
return this.verdictFromOutcome(hit.outcome, guard, decision, true);
|
|
208
|
+
}
|
|
209
|
+
this.cache.delete(cacheKey);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const provider = this.getProvider(signature, decision);
|
|
213
|
+
const started = this.now();
|
|
214
|
+
const state = buildShellGuardState(command, decision.maxStateChars ?? 8000);
|
|
215
|
+
let timedOut = false;
|
|
216
|
+
const controller = new AbortController();
|
|
217
|
+
const onAbort = () => controller.abort();
|
|
218
|
+
abort?.addEventListener("abort", onAbort);
|
|
219
|
+
const timeoutMs = Math.max(50, guard.timeoutMs ?? 10000);
|
|
220
|
+
const timer = setTimeout(() => {
|
|
221
|
+
timedOut = true;
|
|
222
|
+
controller.abort();
|
|
223
|
+
}, timeoutMs);
|
|
224
|
+
try {
|
|
225
|
+
const result = await provider.decide({ state, questions: [...SHELL_GUARD_QUESTIONS] }, controller.signal);
|
|
226
|
+
const latencyMs = this.now() - started;
|
|
227
|
+
const verdict = verdictFromDecisionResult(result, {
|
|
228
|
+
threshold: guard.threshold,
|
|
229
|
+
provider: decision.provider,
|
|
230
|
+
model: decision.model,
|
|
231
|
+
latencyMs,
|
|
232
|
+
});
|
|
233
|
+
this.log(logging, verdict, command, undefined);
|
|
234
|
+
this.store(cacheKey, {
|
|
235
|
+
destructive: verdict.destructive,
|
|
236
|
+
malicious: verdict.malicious,
|
|
237
|
+
category: verdict.category,
|
|
238
|
+
latencyMs,
|
|
239
|
+
}, cacheTtlMs, guard.maxCacheEntries ?? 256);
|
|
240
|
+
return verdict;
|
|
241
|
+
}
|
|
242
|
+
catch (error) {
|
|
243
|
+
const failure = timedOut ? `timeout after ${timeoutMs}ms` : describeError(error);
|
|
244
|
+
const latencyMs = this.now() - started;
|
|
245
|
+
const verdict = this.verdictFromOutcome({ destructive: 0, malicious: 0, category: "none", latencyMs, error: failure }, guard, decision, false);
|
|
246
|
+
this.log(logging, verdict, command, error);
|
|
247
|
+
// Cache failures briefly so a dead endpoint is not re-probed before
|
|
248
|
+
// every command — but never longer than the normal verdict TTL.
|
|
249
|
+
this.store(cacheKey, { destructive: 0, malicious: 0, category: "none", latencyMs, error: failure }, Math.min(cacheTtlMs, 30_000), guard.maxCacheEntries ?? 256);
|
|
250
|
+
return verdict;
|
|
251
|
+
}
|
|
252
|
+
finally {
|
|
253
|
+
clearTimeout(timer);
|
|
254
|
+
abort?.removeEventListener("abort", onAbort);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/** Reset cached verdicts (tests / config reload). */
|
|
258
|
+
clearCache() {
|
|
259
|
+
this.cache.clear();
|
|
260
|
+
}
|
|
261
|
+
getProvider(signature, decision) {
|
|
262
|
+
if (this.providerState?.signature === signature)
|
|
263
|
+
return this.providerState.provider;
|
|
264
|
+
const provider = this.createProvider(decision);
|
|
265
|
+
this.providerState = { signature, provider };
|
|
266
|
+
return provider;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Build a verdict from a (possibly cached) classifier outcome using the
|
|
270
|
+
* CURRENT threshold and `onError` policy — editing either in
|
|
271
|
+
* `opencode-rag.json` takes effect on the next command even while cached
|
|
272
|
+
* probabilities are still valid.
|
|
273
|
+
*/
|
|
274
|
+
verdictFromOutcome(outcome, guard, decision, cached) {
|
|
275
|
+
const base = {
|
|
276
|
+
destructive: outcome.destructive,
|
|
277
|
+
malicious: outcome.malicious,
|
|
278
|
+
category: outcome.category,
|
|
279
|
+
reason: "",
|
|
280
|
+
provider: decision.provider,
|
|
281
|
+
model: decision.model,
|
|
282
|
+
latencyMs: outcome.latencyMs,
|
|
283
|
+
cached,
|
|
284
|
+
};
|
|
285
|
+
if (outcome.error) {
|
|
286
|
+
const verdict = {
|
|
287
|
+
...base,
|
|
288
|
+
destructive: 0,
|
|
289
|
+
malicious: 0,
|
|
290
|
+
category: "none",
|
|
291
|
+
flagged: (guard.onError ?? "allow") === "ask",
|
|
292
|
+
error: outcome.error,
|
|
293
|
+
};
|
|
294
|
+
// Fail-open verdicts stay message-free — the "confirmation required"
|
|
295
|
+
// text describes the ask policy and would be a lie under allow.
|
|
296
|
+
if (verdict.flagged)
|
|
297
|
+
verdict.reason = formatShellGuardReason(verdict);
|
|
298
|
+
return verdict;
|
|
299
|
+
}
|
|
300
|
+
const flagged = outcome.destructive >= guard.threshold || outcome.malicious >= guard.threshold;
|
|
301
|
+
const verdict = { ...base, flagged };
|
|
302
|
+
// The reason is only consumed when a command is escalated; clean verdicts
|
|
303
|
+
// stay message-free so a caller cannot accidentally prompt for them.
|
|
304
|
+
if (flagged)
|
|
305
|
+
verdict.reason = formatShellGuardReason(verdict);
|
|
306
|
+
return verdict;
|
|
307
|
+
}
|
|
308
|
+
store(key, outcome, ttlMs, maxEntries) {
|
|
309
|
+
if (ttlMs <= 0 || maxEntries <= 0)
|
|
310
|
+
return;
|
|
311
|
+
if (this.cache.size >= maxEntries) {
|
|
312
|
+
// Map preserves insertion order — evict the oldest entry.
|
|
313
|
+
const oldest = this.cache.keys().next();
|
|
314
|
+
if (!oldest.done)
|
|
315
|
+
this.cache.delete(oldest.value);
|
|
316
|
+
}
|
|
317
|
+
this.cache.set(key, { outcome, ts: this.now(), ttlMs });
|
|
318
|
+
}
|
|
319
|
+
log(logging, verdict, command, error) {
|
|
320
|
+
const preview = command.length > 160 ? `${command.slice(0, 157)}…` : command;
|
|
321
|
+
if (verdict.error) {
|
|
322
|
+
appendDebugLog(logging.logFilePath, {
|
|
323
|
+
scope: "shell.guard",
|
|
324
|
+
message: `classifier failed (${verdict.error}) — onError=${verdict.flagged ? "ask" : "allow"} for "${preview}"`,
|
|
325
|
+
error,
|
|
326
|
+
severity: "warn",
|
|
327
|
+
}, logging.level);
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
appendDebugLog(logging.logFilePath, {
|
|
331
|
+
scope: "shell.guard",
|
|
332
|
+
message: `${verdict.flagged ? "FLAG" : "allow"} destructive=${verdict.destructive.toFixed(2)} ` +
|
|
333
|
+
`malicious=${verdict.malicious.toFixed(2)} category=${verdict.category} ` +
|
|
334
|
+
`model=${verdict.provider}/${verdict.model} latency=${verdict.latencyMs}ms for "${preview}"`,
|
|
335
|
+
severity: verdict.flagged ? "info" : "debug",
|
|
336
|
+
}, logging.level);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Resolve the guard's live config from a loaded `RagConfig`.
|
|
341
|
+
*
|
|
342
|
+
* Returns `undefined` when the guard is disabled — callers use that as the
|
|
343
|
+
* single gate. `decision.enabled` deliberately does NOT gate the guard: the
|
|
344
|
+
* guard has its own switch and may run against a backend the `make_decision`
|
|
345
|
+
* tool does not expose.
|
|
346
|
+
*
|
|
347
|
+
* @param cfg - Fully merged workspace configuration.
|
|
348
|
+
* @param directory - Workspace root; when given, the log file path is
|
|
349
|
+
* resolved against it (the plugin's process cwd is not necessarily the
|
|
350
|
+
* workspace).
|
|
351
|
+
*/
|
|
352
|
+
export function resolveShellGuardRuntimeConfig(cfg, directory) {
|
|
353
|
+
const guard = cfg.shellGuard;
|
|
354
|
+
if (guard?.enabled !== true)
|
|
355
|
+
return undefined;
|
|
356
|
+
const base = cfg.decision ?? DEFAULT_CONFIG.decision ?? FALLBACK_DECISION;
|
|
357
|
+
const decision = {
|
|
358
|
+
...base,
|
|
359
|
+
enabled: true,
|
|
360
|
+
provider: guard.provider?.trim() || base.provider,
|
|
361
|
+
baseUrl: guard.baseUrl?.trim() || base.baseUrl,
|
|
362
|
+
model: guard.model?.trim() || base.model,
|
|
363
|
+
};
|
|
364
|
+
const log = resolveLogConfig(cfg);
|
|
365
|
+
return {
|
|
366
|
+
guard,
|
|
367
|
+
decision,
|
|
368
|
+
logging: directory
|
|
369
|
+
? { ...log, logFilePath: path.resolve(directory, log.logFilePath) }
|
|
370
|
+
: log,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Build a config reader that re-reads the global + workspace config when
|
|
375
|
+
* either changes.
|
|
376
|
+
*
|
|
377
|
+
* A shell command is classified at most a few seconds apart, so the stat
|
|
378
|
+
* check is cheap; re-reading makes an edit (global enabled flag, threshold,
|
|
379
|
+
* model) take effect without restarting OpenCode.
|
|
380
|
+
*/
|
|
381
|
+
export function createShellGuardConfigReader(directory) {
|
|
382
|
+
let cached;
|
|
383
|
+
return () => {
|
|
384
|
+
try {
|
|
385
|
+
const paths = resolveConfigPaths(directory);
|
|
386
|
+
if (!paths.global && !paths.workspace)
|
|
387
|
+
return undefined;
|
|
388
|
+
const stamp = [paths.global, paths.workspace]
|
|
389
|
+
.filter((p) => p !== undefined)
|
|
390
|
+
.map((p) => {
|
|
391
|
+
const stat = statSync(p);
|
|
392
|
+
return `${p}:${stat.mtimeMs}:${stat.size}`;
|
|
393
|
+
})
|
|
394
|
+
.join("|");
|
|
395
|
+
if (cached && cached.stamp === stamp)
|
|
396
|
+
return cached.value;
|
|
397
|
+
const value = resolveShellGuardRuntimeConfig(loadWorkspaceConfig(directory, false), directory);
|
|
398
|
+
cached = { stamp, value };
|
|
399
|
+
return value;
|
|
400
|
+
}
|
|
401
|
+
catch {
|
|
402
|
+
// Malformed config: keep the last good value rather than disabling the
|
|
403
|
+
// guard mid-session.
|
|
404
|
+
return cached?.value;
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
/** Convenience factory used by the V2 adapter. */
|
|
409
|
+
export function createShellGuardForDirectory(directory) {
|
|
410
|
+
return new ShellGuard({ getConfig: createShellGuardConfigReader(directory) });
|
|
411
|
+
}
|
|
412
|
+
//# sourceMappingURL=shell-guard.js.map
|
package/dist/v2/v2-adapter.d.ts
CHANGED
|
@@ -16,9 +16,12 @@
|
|
|
16
16
|
* | `tool.execute.after` | `ctx.tool.hook("execute.after", ...)` |
|
|
17
17
|
* | `event` | `ctx.event.subscribe({ signal })` |
|
|
18
18
|
*
|
|
19
|
-
* Additional V2-only
|
|
20
|
-
* are granted to the built-in `explore` agent via
|
|
21
|
-
* (config `openCode.exploreAgentTools`, default on)
|
|
19
|
+
* Additional V2-only registrations (no V1 equivalent):
|
|
20
|
+
* - the read-only RAG tools are granted to the built-in `explore` agent via
|
|
21
|
+
* `ctx.agent.transform` (config `openCode.exploreAgentTools`, default on);
|
|
22
|
+
* - the optional shell guard classifies shell commands and escalates flagged
|
|
23
|
+
* ones to the confirmation prompt via `ctx.permission.hook("evaluate", …)`
|
|
24
|
+
* (config `shellGuard`, default off).
|
|
22
25
|
*
|
|
23
26
|
* The V2 prompt hook exposes the user's text as a mutable `event.prompt.text`
|
|
24
27
|
* instead of V1's parts-mutation contract; the adapter shims a V1-shaped
|
|
@@ -30,6 +33,7 @@
|
|
|
30
33
|
* queries and session-end extraction fall back gracefully.
|
|
31
34
|
* - The read-tool override keeps its V1 execute contract (args + sessionID).
|
|
32
35
|
*/
|
|
36
|
+
import { type ShellGuard } from "../safety/shell-guard.js";
|
|
33
37
|
type V2Registration = {
|
|
34
38
|
dispose(): Promise<void>;
|
|
35
39
|
};
|
|
@@ -67,6 +71,31 @@ type V2AgentDomain = {
|
|
|
67
71
|
transform(callback: (editor: V2AgentEditor) => void): Promise<V2Registration>;
|
|
68
72
|
reload(): Promise<void>;
|
|
69
73
|
};
|
|
74
|
+
/**
|
|
75
|
+
* Permission evaluation event (OpenCode V2 `ctx.permission.hook("evaluate")`).
|
|
76
|
+
*
|
|
77
|
+
* Runs after configured rules are evaluated and before the action runs or a
|
|
78
|
+
* prompt is published — for `allow` and `ask` decisions (`deny` is final).
|
|
79
|
+
* Mutating `effect`/`message` is the documented way to escalate an allowed
|
|
80
|
+
* action to a confirmation prompt.
|
|
81
|
+
*/
|
|
82
|
+
export type V2PermissionEvaluation = {
|
|
83
|
+
readonly sessionID: string;
|
|
84
|
+
readonly agent?: string;
|
|
85
|
+
readonly action: string;
|
|
86
|
+
readonly resources: readonly string[];
|
|
87
|
+
readonly metadata?: Record<string, unknown>;
|
|
88
|
+
readonly source?: {
|
|
89
|
+
type: "tool";
|
|
90
|
+
messageID: string;
|
|
91
|
+
id: string;
|
|
92
|
+
};
|
|
93
|
+
effect: "allow" | "ask" | "deny";
|
|
94
|
+
message?: string;
|
|
95
|
+
};
|
|
96
|
+
type V2PermissionDomain = {
|
|
97
|
+
hook(name: "evaluate", callback: (event: V2PermissionEvaluation) => Promise<void> | void): Promise<V2Registration>;
|
|
98
|
+
};
|
|
70
99
|
/** Structural subset of the OpenCode V2 plugin context. */
|
|
71
100
|
export type V2Context = {
|
|
72
101
|
location: {
|
|
@@ -77,6 +106,8 @@ export type V2Context = {
|
|
|
77
106
|
session: V2SessionDomain;
|
|
78
107
|
event: V2EventDomain;
|
|
79
108
|
agent?: V2AgentDomain;
|
|
109
|
+
/** Permission surface — present in OpenCode V2 hosts; absent on older builds. */
|
|
110
|
+
permission?: V2PermissionDomain;
|
|
80
111
|
};
|
|
81
112
|
/** A registered V2 tool definition (structural subset of Tool.Info). */
|
|
82
113
|
type V2Tool = {
|
|
@@ -184,6 +215,21 @@ export declare function zodShapeToJsonSchema(shape: Record<string, unknown>): Re
|
|
|
184
215
|
* and left untouched. No-op when the agent is absent. Exported for tests.
|
|
185
216
|
*/
|
|
186
217
|
export declare function grantExploreToolPermissions(editor: V2AgentEditor): void;
|
|
218
|
+
/**
|
|
219
|
+
* Install the optional shell-command safety guard on the V2 permission
|
|
220
|
+
* `evaluate` hook.
|
|
221
|
+
*
|
|
222
|
+
* The hook runs after rules resolve and before the shell action executes, for
|
|
223
|
+
* both `allow` and `ask` decisions (`deny` is final). A command the decision
|
|
224
|
+
* model flags is escalated to the host's confirmation prompt; a clean command
|
|
225
|
+
* keeps the resolved effect and runs normally. Any failure inside the hook is
|
|
226
|
+
* swallowed so a broken classifier can never block a permission check.
|
|
227
|
+
*
|
|
228
|
+
* Returns `undefined` when the host exposes no permission hook (older V2
|
|
229
|
+
* builds) — the guard then stays inert instead of failing plugin setup.
|
|
230
|
+
* Exported for tests.
|
|
231
|
+
*/
|
|
232
|
+
export declare function installShellGuard(ctx: Pick<V2Context, "permission">, guard: ShellGuard): Promise<V2Registration | undefined>;
|
|
187
233
|
/**
|
|
188
234
|
* Run the V1 `ragPlugin` factory for the V2 context's location and register
|
|
189
235
|
* all returned hooks as V2 transforms/hooks. Returns a cleanup function that
|
package/dist/v2/v2-adapter.js
CHANGED
|
@@ -16,9 +16,12 @@
|
|
|
16
16
|
* | `tool.execute.after` | `ctx.tool.hook("execute.after", ...)` |
|
|
17
17
|
* | `event` | `ctx.event.subscribe({ signal })` |
|
|
18
18
|
*
|
|
19
|
-
* Additional V2-only
|
|
20
|
-
* are granted to the built-in `explore` agent via
|
|
21
|
-
* (config `openCode.exploreAgentTools`, default on)
|
|
19
|
+
* Additional V2-only registrations (no V1 equivalent):
|
|
20
|
+
* - the read-only RAG tools are granted to the built-in `explore` agent via
|
|
21
|
+
* `ctx.agent.transform` (config `openCode.exploreAgentTools`, default on);
|
|
22
|
+
* - the optional shell guard classifies shell commands and escalates flagged
|
|
23
|
+
* ones to the confirmation prompt via `ctx.permission.hook("evaluate", …)`
|
|
24
|
+
* (config `shellGuard`, default off).
|
|
22
25
|
*
|
|
23
26
|
* The V2 prompt hook exposes the user's text as a mutable `event.prompt.text`
|
|
24
27
|
* instead of V1's parts-mutation contract; the adapter shims a V1-shaped
|
|
@@ -30,8 +33,9 @@
|
|
|
30
33
|
* queries and session-end extraction fall back gracefully.
|
|
31
34
|
* - The read-tool override keeps its V1 execute contract (args + sessionID).
|
|
32
35
|
*/
|
|
33
|
-
import {
|
|
36
|
+
import { loadWorkspaceConfig, resolveConfigPaths } from "../core/config.js";
|
|
34
37
|
import { ragPlugin, RAG_TOOL_NAMES } from "../plugin.js";
|
|
38
|
+
import { createShellGuardForDirectory, formatShellGuardReason, isShellToolName, } from "../safety/shell-guard.js";
|
|
35
39
|
/**
|
|
36
40
|
* Join the text parts of a tool result's `content`.
|
|
37
41
|
*
|
|
@@ -220,6 +224,42 @@ export function grantExploreToolPermissions(editor) {
|
|
|
220
224
|
}
|
|
221
225
|
});
|
|
222
226
|
}
|
|
227
|
+
/**
|
|
228
|
+
* Install the optional shell-command safety guard on the V2 permission
|
|
229
|
+
* `evaluate` hook.
|
|
230
|
+
*
|
|
231
|
+
* The hook runs after rules resolve and before the shell action executes, for
|
|
232
|
+
* both `allow` and `ask` decisions (`deny` is final). A command the decision
|
|
233
|
+
* model flags is escalated to the host's confirmation prompt; a clean command
|
|
234
|
+
* keeps the resolved effect and runs normally. Any failure inside the hook is
|
|
235
|
+
* swallowed so a broken classifier can never block a permission check.
|
|
236
|
+
*
|
|
237
|
+
* Returns `undefined` when the host exposes no permission hook (older V2
|
|
238
|
+
* builds) — the guard then stays inert instead of failing plugin setup.
|
|
239
|
+
* Exported for tests.
|
|
240
|
+
*/
|
|
241
|
+
export async function installShellGuard(ctx, guard) {
|
|
242
|
+
const permission = ctx.permission;
|
|
243
|
+
if (!permission?.hook)
|
|
244
|
+
return undefined;
|
|
245
|
+
return permission.hook("evaluate", async (event) => {
|
|
246
|
+
try {
|
|
247
|
+
if (!isShellToolName(event.action))
|
|
248
|
+
return;
|
|
249
|
+
const command = Array.isArray(event.resources) ? event.resources.join("\n").trim() : "";
|
|
250
|
+
if (command.length === 0)
|
|
251
|
+
return;
|
|
252
|
+
const verdict = await guard.evaluate(command);
|
|
253
|
+
if (!verdict.flagged)
|
|
254
|
+
return;
|
|
255
|
+
event.effect = "ask";
|
|
256
|
+
event.message = verdict.reason || formatShellGuardReason(verdict);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
// Never break a permission check — leave the resolved effect untouched.
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
}
|
|
223
263
|
/**
|
|
224
264
|
* Run the V1 `ragPlugin` factory for the V2 context's location and register
|
|
225
265
|
* all returned hooks as V2 transforms/hooks. Returns a cleanup function that
|
|
@@ -240,9 +280,9 @@ export async function registerRagPluginV2(ctx) {
|
|
|
240
280
|
// `openCode.exploreAgentTools: false` in opencode-rag.json.
|
|
241
281
|
let exploreToolsEnabled = true;
|
|
242
282
|
try {
|
|
243
|
-
const
|
|
244
|
-
if (
|
|
245
|
-
exploreToolsEnabled =
|
|
283
|
+
const paths = resolveConfigPaths(ctx.location.directory);
|
|
284
|
+
if (paths.global || paths.workspace) {
|
|
285
|
+
exploreToolsEnabled = loadWorkspaceConfig(ctx.location.directory, false).openCode.exploreAgentTools !== false;
|
|
246
286
|
}
|
|
247
287
|
}
|
|
248
288
|
catch {
|
|
@@ -259,6 +299,22 @@ export async function registerRagPluginV2(ctx) {
|
|
|
259
299
|
});
|
|
260
300
|
registrations.push(registration);
|
|
261
301
|
}
|
|
302
|
+
// ── shell guard (V2-only permission evaluate hook) ───────────────────────
|
|
303
|
+
// Optional: classify every shell command with the local decision model and
|
|
304
|
+
// escalate flagged commands to OpenCode's confirmation prompt. The guard
|
|
305
|
+
// re-reads opencode-rag.json, so shellGuard.enabled/threshold/model edits
|
|
306
|
+
// take effect without a restart. Inert when the host has no permission
|
|
307
|
+
// surface or when `shellGuard.enabled` is false.
|
|
308
|
+
if (ctx.permission) {
|
|
309
|
+
try {
|
|
310
|
+
const registration = await installShellGuard(ctx, createShellGuardForDirectory(ctx.location.directory));
|
|
311
|
+
if (registration)
|
|
312
|
+
registrations.push(registration);
|
|
313
|
+
}
|
|
314
|
+
catch {
|
|
315
|
+
// Non-critical — the rest of the plugin must keep working
|
|
316
|
+
}
|
|
317
|
+
}
|
|
262
318
|
// Explore agent tool grant: hand the read-only RAG tools to the built-in
|
|
263
319
|
// search agent. The grant appends allow rules after the shipped deny-all
|
|
264
320
|
// policy (last matching rule wins) and respects explicit user rules.
|