Repository navigation
Expand file tree
/
Copy pathcommand.js
More file actions
890 lines (851 loc) · 50.9 KB
/
Copy pathcommand.js
File metadata and controls
890 lines (851 loc) · 50.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
import { execFile } from "node:child_process"
import { createHash, randomBytes } from "node:crypto"
import { mkdirSync, writeFileSync } from "node:fs"
import { mkdir, readdir, readFile, rename, stat, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import path from "node:path"
import { groupMisses } from "./learn.js"
import { sanitizeCategory } from "./patterns.js"
import { describePolicy, modeFor, policyMtime, ruleFor, stricter } from "./companypolicy.js"
import { escapeRegex, expandPath, hasWindowsInterop, isWsl, stripBom } from "./util.js"
import { deleteCredential, writeCredential } from "./wincred.js"
/**
* `gh▒▒▒▒▒`: first characters only, fixed-width mask. Values under 16 chars
* (typical passwords) are fully masked. Command output becomes part of the
* conversation on the next turn, so it must never carry more than this.
*/
export function mask(value, visible = 2) {
const v = String(value ?? "")
if (v.length < 16 || visible <= 0) return "▒▒▒▒▒"
return `${v.slice(0, Math.min(visible, 4))}▒▒▒▒▒`
}
export function readClipboard() {
const [cmd, args] =
process.platform === "win32" || (isWsl() && !process.env.WAYLAND_DISPLAY && !process.env.DISPLAY)
? ["powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "[Console]::OutputEncoding=[Text.Encoding]::UTF8; Get-Clipboard -Raw"]]
: process.platform === "darwin"
? ["pbpaste", []]
: process.env.WAYLAND_DISPLAY
? ["wl-paste", ["--no-newline"]]
: ["xclip", ["-o", "-selection", "clipboard"]]
return new Promise((resolve) => {
execFile(cmd, args, { timeout: 10_000, windowsHide: true }, (error, stdout) =>
resolve(error ? { error: String(error.message).split("\n")[0] } : { value: String(stdout ?? "").replace(/\r?\n$/, "") }),
)
})
}
/**
* A shell command that prints `text` and deletes it afterwards (`!vibeguard`: OpenCode shows shell output as is,
* without a model call). The text goes through a private temp file, so no quoting of its content is needed.
*/
export function shellPrint(text, shell) {
const outDir = path.join(tmpdir(), "vibeguard")
mkdirSync(outDir, { recursive: true, mode: 0o700 })
const file = path.join(outDir, `out-${randomBytes(6).toString("hex")}.txt`)
writeFileSync(file, text, { mode: 0o600 })
const sh = String(shell ?? "")
return /powershell|pwsh/i.test(sh)
? `[Console]::OutputEncoding=[Text.Encoding]::UTF8; Get-Content -Raw -Encoding UTF8 -LiteralPath '${file}'; Remove-Item -LiteralPath '${file}'`
: /cmd(?:\.exe)?$/i.test(sh)
? `type "${file}" & del "${file}"`
: `cat '${file}'; rm -f '${file}'`
}
function quoteValue(v) {
if (!/[\s#"'`]/.test(v)) return v
if (!v.includes('"')) return `"${v}"`
if (!v.includes("'")) return `'${v}'`
return `\`${v}\``
}
async function atomicWrite(file, text) {
await mkdir(path.dirname(file), { recursive: true })
const tmp = `${file}.tmp-${process.pid}`
await writeFile(tmp, text, "utf8")
await rename(tmp, file)
}
async function readText(file) {
try {
return stripBom(await readFile(file, "utf8"))
} catch (error) {
if (error?.code === "ENOENT") return ""
throw error
}
}
const lineFor = (name) => new RegExp(`^\\s*(?:export\\s+)?${name}(?:\\[\\w+\\])?\\s*[=:]`, "i")
export async function addToSecretsFile(file, name, value) {
const text = await readText(file)
const lines = text.split(/\r?\n/).filter((l, i, a) => !(i === a.length - 1 && l === ""))
const re = lineFor(name)
const next = lines.filter((l) => !re.test(l))
const replaced = next.length !== lines.length
next.push(`${name}=${quoteValue(value)}`)
await atomicWrite(file, `${next.join("\n")}\n`)
return { replaced }
}
export async function removeFromSecretsFile(file, name) {
const text = await readText(file)
const lines = text.split(/\r?\n/)
const re = lineFor(name)
const next = lines.filter((l) => !re.test(l))
if (next.length === lines.length) return { removed: false }
await atomicWrite(file, next.join("\n"))
return { removed: true }
}
const HELP = (n) => `**/${n}** – VibeGuard secret protection
- \`/${n}\` or \`/${n} status\` – Status, sources, masked known secrets
- \`/${n} add NAME\` – Add a secret **from the clipboard** (nothing typed into the chat)
- \`/${n} add NAME=value\` – Add a secret typed inline (redacted before any request)
- \`/${n} add NAME --wincred\` – Store in Windows Credential Manager (\`vibeguard:NAME\`) instead of the file
- \`/${n} remove NAME\` – Remove from the secrets file / Credential Manager
- \`/${n} reload\` – Re-read all sources (incl. password managers)
- \`/${n} check [--hibp]\` – Strength of each secret, collisions with project files, optional breach check
- \`/${n} why __VG_…__\` – Why a value was replaced: detector or rule, the text in front of it, how often, whether it is remembered – never the value
- \`/${n} allow <value or placeholder>\` – **No secret in this session** – no longer replaced by any detector (rules, local LLM, sensitive files, remembered values). \`allow remove …\` undoes it. Alias: \`forget\`
- \`/${n} allow-global <value or placeholder>\` – **No secret anywhere** – applies at once in every session and project (fingerprint only). \`allow-global list\`, \`allow-global remove …\`
- \`/${n} forget __VG_…__\` – False positive: the value behind this placeholder is no longer remembered or replaced by the LLM / sensitive-file check in this session (slash command only)
- \`/${n} alert test\` – Send a test alarm through all channels (desktop notification, e-mail)
- \`/${n} compact\` – Start a compaction of this session now (also \`!${n} compact\`)
- \`/${n} learn [clear]\` – Contexts in which the local LLM found credentials the rules missed (grouped, never values) – basis for new rules
- \`/${n} session\` – What was replaced in **this session** (masked) and statistics
- \`/${n} off\` – **This session only:** send everything unfiltered (no placeholders, no payload guard, no file protection). Routing rules stay
- \`/${n} off all\` – Like \`off\`, and routing rules (restricted sources) are lifted for this session too
- \`/${n} route off [30m|2h|session]\` – **Only** lift the routing rules for this session (default 1 h); secrets stay replaced. \`/${n} route on\` restores them
- \`/${n} urls [allow|ask|deny] [30m|2h|session]\` – Real values inside **URL fields** of tool inputs: change the policy for this session (default 1 h; config \`restore.url_fields\`). \`/${n} urls reset\` restores the configured policy
- \`/${n} on\` – Protection back on for this session (also after every restart)
- \`/${n} fingerprints prune\` – Remove fingerprints of common text (in several sessions without data from the source) and of tool documentation
- \`/${n} taint [clear]\` – Restricted data sources this session has seen
- \`/${n} policy\` – Company policy: which settings it sets, how binding they are (default, floor, enforce) and which of your own settings it overrides
- \`/${n} test\` – Run the self-test`
const STRENGTH = { strong: "strong", medium: "medium", weak: "⚠️ weak" }
const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", "out", ".next", ".venv", "venv", "__pycache__", "target", "bin", "obj"])
async function listProjectFiles(directory) {
const viaGit = await new Promise((resolve) => {
execFile("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: directory, windowsHide: true, maxBuffer: 32 * 1024 * 1024, timeout: 15_000 }, (error, stdout) =>
resolve(error ? null : String(stdout).split("\0").filter(Boolean).map((f) => path.join(directory, f))),
)
})
if (viaGit) return viaGit.slice(0, 5000)
const out = []
const walk = async (dir, depth) => {
if (depth > 6 || out.length >= 5000) return
let items
try {
items = await readdir(dir, { withFileTypes: true })
} catch {
return
}
for (const it of items) {
if (out.length >= 5000) return
if (it.isDirectory()) {
if (!SKIP_DIRS.has(it.name) && !it.name.startsWith(".")) await walk(path.join(dir, it.name), depth + 1)
} else if (it.isFile()) out.push(path.join(dir, it.name))
}
}
await walk(directory, 0)
return out
}
/** Occurrences of values in project text files. Returns counts only. */
export async function scanProject(directory, values) {
const result = new Map()
const files = await listProjectFiles(directory)
for (const file of files) {
let text
try {
const s = await stat(file)
if (s.size > 512 * 1024) continue
const buf = await readFile(file)
if (buf.includes(0)) continue
text = buf.toString("utf8")
} catch {
continue
}
for (const v of values) {
let n = 0
for (let i = text.indexOf(v); i !== -1; i = text.indexOf(v, i + v.length)) n++
if (!n) continue
const r = result.get(v) ?? { files: 0, hits: 0 }
r.files++
r.hits += n
result.set(v, r)
}
}
return result
}
/** Have I Been Pwned "Pwned Passwords" range API (k-anonymity). */
export async function hibpCounts(values, fetchImpl = globalThis.fetch) {
const out = new Map()
const byPrefix = new Map()
for (const v of new Set(values)) {
const h = createHash("sha1").update(v, "utf8").digest("hex").toUpperCase()
const p = h.slice(0, 5)
if (!byPrefix.has(p)) byPrefix.set(p, [])
byPrefix.get(p).push([v, h.slice(5)])
}
for (const [prefix, list] of [...byPrefix].slice(0, 200)) {
try {
const res = await fetchImpl(`https://api.pwnedpasswords.com/range/${prefix}`, {
headers: { "Add-Padding": "true", "User-Agent": "opencode-vibeguard" },
signal: AbortSignal.timeout(10_000),
})
if (!res.ok) continue
const counts = new Map()
for (const line of (await res.text()).split(/\r?\n/)) {
const [suffix, count] = line.trim().split(":")
if (suffix) counts.set(suffix.toUpperCase(), Number(count) || 0)
}
for (const [v, suffix] of list) out.set(v, counts.get(suffix) ?? 0)
} catch {
// offline: leave unknown
}
}
return out
}
/** "30m" | "2h" | "1.5d" | "session" (0 = until restart) -> ms; null = unreadable, undefined = out of range. Default 1 h. */
export function liftDuration(spec) {
const s = String(spec ?? "1h").toLowerCase()
if (s === "session") return 0
const m = s.match(/^(\d+(?:\.\d+)?)\s*(m|min|h|d)?$/)
if (!m) return null
const ms = Number(m[1]) * ({ h: 3_600_000, d: 86_400_000 }[m[2]] ?? 60_000)
return ms > 0 && ms <= 7 * 86_400_000 ? ms : undefined
}
/**
* Handler for the `/vibeguard` command. Returns markdown for a synthetic message.
* Never echoes secret values.
*/
export function createCommandHandler(deps) {
const { config, directory, getState, rebuild, selfTest, audit, sessions } = deps
const name = config.command?.name ?? "vibeguard"
const visible = Number.isFinite(config.command?.mask_chars) ? config.command.mask_chars : 2
const secretsFile = () => expandPath((config.secrets?.files ?? [])[0] ?? "~/.config/opencode/vibeguard.secrets", directory)
const status = async (sessionID) => {
const st = getState()
if (sessionID && deps.routing) taintCache.set(sessionID, await deps.routing.getTaint(sessionID))
const lines = []
const health = st.selftest?.ok
? st.selftest.warnings
? `✅ passed with ${st.selftest.warnings} warning(s) – run \`/${name} test\``
: "✅ passed"
: st.selftest
? `❌ FAILED – requests are blocked while fail_closed is on; run \`/${name} test\``
: "not run"
lines.push(`**VibeGuard status**`, "")
const off = sessionID ? deps.filter?.get(sessionID) : null
if (off) lines.push(`⚠️ **OFF for this session** since ${off.since}${off.scope === "all" ? " (including routing rules)" : ""} – \`/${name} on\` turns it back on.`, "")
const lifted = sessionID ? deps.filter?.route?.get(sessionID) : null
if (lifted) lines.push(`⚠️ **Routing lifted for this session** ${lifted.until ? `until ${new Date(lifted.until).toLocaleTimeString()}` : "until restart"} (secrets stay replaced) – \`/${name} route on\` restores it.`, "")
lines.push(`- Config: \`${config.loadedFrom}\``)
const pol = config.policy?.doc
if (pol) lines.push(`- Company policy: ${pol.policy.id ? `\`${pol.policy.id}\` ` : ""}v${pol.policy.version}${config.policy.signed ? " · signed" : config.policy.keys ? "" : " · unsigned"}${config.policy.changed.length ? ` · ${config.policy.changed.length} own setting(s) overridden` : ""}${policyMtime() > (config.policy.mtime ?? 0) ? " · ⚠️ newer policy waiting – restart OpenCode" : ""} (\`/${name} policy\`)`)
lines.push(`- Self-test: ${health}${st.pipeline ? ` · live pipeline: ${st.pipeline}` : ""}`)
lines.push(`- Known values: ${st.known?.named ?? 0} named (+${(st.known?.entries.length ?? 0) - (st.known?.named ?? 0)} encoded variants)`)
lines.push(`- Detection rules: ${st.patterns?.regex.length ?? 0} · protected paths: ${st.protectedCount ?? 0} · sessions: ${sessions()}`)
lines.push(`- Payload guard: ${config.guard?.http ?? "redact"} · stream restore: ${config.restore?.response !== false ? "on" : "off"} · fail_closed: ${config.fail_closed}`)
const llmSt = deps.llmStatus?.()
if (llmSt) {
const st2 = llmSt.status
lines.push(
`- Local LLM scan: \`${llmSt.model}\` on \`${llmSt.endpoint}\` · ${
!st2 || st2.available
? "✅ reachable"
: `⚠️ **unreachable since ${new Date(st2.downSince).toLocaleTimeString()}** (${st2.lastError}) – requests go out with rules and remembered values; ${st2.uncheckedQueued} unchecked piece(s) wait for a re-check`
}`,
)
}
lines.push(`- Audit log: ${audit.enabled ? `\`${audit.path}\`` : "off"}`)
const counts = st.known?.counts ?? {}
lines.push(`- Sources: ${Object.entries(counts).filter(([k]) => k !== "total").map(([k, v]) => `${k}=${v}`).join(", ") || "none"}`)
for (const f of st.known?.failed ?? []) lines.push(`- ⚠️ unreadable: \`${f.file}\` (${f.message})`)
lines.push(...routingStatus(sessionID))
const named = (st.known?.entries ?? []).slice(0, st.known?.named ?? 0)
const weak = named.filter((e) => e.strength === "weak")
if (weak.length) {
lines.push("", `⚠️ **${weak.length} weak secret(s)** – only replaced in a credential context (\`${name} check\` for details). Change these passwords:`)
lines.push(weak.slice(0, 20).map((e) => `\`${e.category}\``).join(", "))
}
if (named.length) {
lines.push("", "**Known secrets** (name · masked value · strength · match · source)")
for (const e of named.slice(0, 60)) {
lines.push(`- ${e.category} · \`${mask(e.value, visible)}\` · ${STRENGTH[e.strength] ?? "?"} · ${e.mode ?? "exact"} · ${e.source}`)
}
if (named.length > 60) lines.push(`- … ${named.length - 60} more`)
}
return lines.join("\n")
}
const routingStatus = (sessionID) => {
const r = deps.routing?.info
if (!r || (!r.endpoints.length && !r.sources.length)) return []
const out = ["", "**Routing**"]
for (const e of r.endpoints) {
out.push(`- Endpoint \`${e.name}\`${e.trusted ? " (trusted: no substitution)" : ""}${e.hasBaseUrls ? "" : " ⚠️ no base_urls – provider ID is trusted"}`)
}
for (const s of r.sources) out.push(`- Source \`${s.name}\` → ${s.allow ? [...s.allow].join(", ") : "any endpoint (tagging only)"}`)
out.push(`- On violation: ${r.onViolation} · preflight: ${r.preflight} · content fingerprints: ${deps.routing.fingerprints()}`)
if (sessionID) {
const lm = deps.routing.lastModel(sessionID)
const taint = taintCache.get(sessionID)
out.push(`- This session: model ${lm?.model ? `${lm.model.providerID}/${lm.model.id}` : "unknown"} → endpoint ${lm?.endpoint?.name ?? "none (cloud/unknown)"}`)
if (taint?.size) out.push(`- This session contains restricted data from: ${[...taint].map((t) => `\`${t}\``).join(", ")}`)
}
return out
}
const taintCache = new Map()
const taint = async (args, sessionID) => {
if (!deps.routing) return "Routing is not configured."
if (!sessionID) return "No session."
if (args[0] === "clear") {
await deps.routing.clearTaint(sessionID)
taintCache.delete(sessionID)
return "Cleared the restricted-data marker of this session. History that still contains such data keeps being blocked for other endpoints."
}
const t = await deps.routing.getTaint(sessionID)
return t.size
? `This session contains restricted data from: ${[...t].map((x) => `\`${x}\``).join(", ")}. Requests to other endpoints are blocked. \`/${name} taint clear\` removes the marker.`
: "This session contains no restricted data."
}
const secs = (ms) => (ms >= 10_000 ? `${(ms / 1000).toFixed(0)} s` : `${(ms / 1000).toFixed(1)} s`)
const num = (n) => Number(n ?? 0).toLocaleString("de-DE")
/** Local LLM scan: requests, time, tokens, hits/misses for this session (+ totals since start). */
const llmView = (llm, s) => {
if (!llm) return ["", "**Local LLM scan:** off (`llm_scan`)"]
const calls = s.llm_calls ?? 0
const checked = (s.llm_hit ?? 0) + (s.llm_miss ?? 0)
const pct = (n) => (checked ? ` (${Math.round((100 * n) / checked)} %)` : "")
const out = [
"",
`**Local LLM scan** – \`${llm.model}\` on \`${llm.endpoint}\``,
...(llm.status && !llm.status.available
? [
"",
`⚠️ **Unreachable since ${new Date(llm.status.downSince).toLocaleTimeString()}** (${llm.status.lastError}). Requests go out with rules and remembered values only; ${llm.status.uncheckedQueued} unchecked piece(s) are re-checked once the model answers – findings raise a leak alarm.`,
]
: []),
"",
"_Numbers: this session · since plugin start (all sessions)_",
"",
`- Requests to the model: ${num(calls)} · ${num(llm.total.calls)}`,
`- Time total / per request: ${secs(s.llm_ms ?? 0)} / ${calls ? secs((s.llm_ms ?? 0) / calls) : "–"} · ${secs(llm.total.ms ?? 0)} / ${llm.total.calls ? secs(llm.total.ms / llm.total.calls) : "–"}`,
`- Tokens in / out: ${num(s.llm_tokens_in)} / ${num(s.llm_tokens_out)} · ${num(llm.total.tokens_in)} / ${num(llm.total.tokens_out)}`,
`- Characters sent / size of the scanned texts: ${num(s.llm_chars_sent)} / ${num(s.llm_chars_total)}`,
`- Texts checked completely: ${num(checked)} – with findings ${num(s.llm_hit)}${pct(s.llm_hit ?? 0)}, nothing found ${num(s.llm_miss)}${pct(s.llm_miss ?? 0)}`,
`- Findings: ${num(s.llm_findings)} · ${num(llm.total.findings)} – only the LLM found them ${num(s.llm_only_llm)}, rules too ${num(s.llm_also_rules)}`,
`- Findings not located in the text (ignored): ${num(s.llm_unlocated)} · ${num(llm.total.skipped)}`,
`- Skipped: pre-filter (no credential cue) ${num(s.llm_prefiltered)}, compaction checkpoints ${num(s.llm_checkpoint)}`,
`- Results reused from cache: ${num(s.llm_cached)} · ${num(llm.total.cached)}`,
`- Over the time budget (checked in the background): ${num(s.llm_deferred)}${s.llm_dropped ? ` (${num(s.llm_dropped)} dropped: queue full)` : ""} – background checks done ${num(s.llm_background_calls)}`,
`- Late findings: ${s.llm_late_leaks ? "⚠️ " : ""}${num(s.llm_late_leaks)} had already gone out unmasked, ${num(s.llm_late_covered)} the rules had caught anyway`,
`- Errors: ${num(s.llm_errors)} · ${num(llm.total.errors)}`,
]
if (s.llm_late_leaks) out.push("", "⚠️ Values listed with ⚠️ below went to the provider unmasked before the delayed check finished – change them.")
return out
}
const cell = (s) => String(s ?? "").replace(/\|/g, "¦").replace(/`/g, "ʹ").slice(0, 90)
const learnView = (args) => {
const L = deps.learn
if (!L?.enabled) return "Learning is off (`learn.enabled: false`)."
if (args[0] === "clear") {
L.clear()
return "Collected miss contexts cleared."
}
const records = L.read()
if (!records.length) return `Nothing collected yet. Every time the local LLM finds a credential the rules missed, its context (never the value) is stored in \`${L.path}\`.`
const groups = groupMisses(records)
const lines = [
`**VibeGuard learn** – ${records.length} miss(es) in ${groups.length} pattern(s) (\`${L.path}\`)`,
"",
"Contexts in which the rules missed a credential the local LLM found. The value is shown only as its shape (‹Aa9!›: upper, lower, digit, symbol); other secrets as ‹CATEGORY›.",
"",
]
for (const g of groups.slice(0, 40)) {
const r = g.sample
const where = [...g.origins].sort((a, b) => b[1] - a[1]).slice(0, 2).map(([o, c]) => `${cell(o)} ×${c}`).join(", ")
lines.push(`- **${g.count}×** ${g.category} (length ${r.len}): …${cell(r.before.slice(-60))}⟨‹${r.shape}›⟩${cell(r.after)}…${where ? ` – in ${where}` : ""}`)
}
if (groups.length > 40) lines.push(`- … ${groups.length - 40} more patterns`)
lines.push("", `Recurring patterns can become fast rules (no LLM call needed). \`/${name} learn clear\` resets the collection.`)
return lines.join("\n")
}
const sessionView = (sessionID) => {
if (!deps.inspect) return "Not available."
if (!sessionID) return "No session."
const { session, stats, model, llm } = deps.inspect(sessionID)
const off = deps.filter?.get(sessionID)
const lines = [`**VibeGuard – this session**`, ""]
if (off) lines.push(`⚠️ **OFF** since ${off.since}${off.scope === "all" ? " (including routing rules)" : ""} – \`/${name} on\` turns it back on.`)
const lifted = deps.filter?.route?.get(sessionID)
if (lifted) lines.push(`⚠️ **Routing lifted** ${lifted.until ? `until ${new Date(lifted.until).toLocaleTimeString()}` : "until restart"} (secrets stay replaced) – \`/${name} route on\` restores it.`)
else if (model?.endpoint?.trusted) lines.push(`ℹ️ Current model ${model.model?.providerID}/${model.model?.id} is the trusted endpoint \`${model.endpoint.name}\`: requests go out **without** substitution.`)
else lines.push(`🛡️ Active${model?.model ? ` · current model ${model.model.providerID}/${model.model.id}` : ""}`)
const s = stats ?? {}
lines.push(
"",
`- Requests: ${s.requests ?? 0} – with replacements ${s.redacted_requests ?? 0}, trusted (plaintext) ${s.passthrough ?? 0}, unfiltered (off) ${s.unfiltered ?? 0}, blocked ${s.blocked ?? 0}`,
`- Payload safety net hits: ${s.guard ?? 0} · values handed to tools: ${s.tool_restores ?? 0}`,
)
if (s.since) lines.push("", `_Counting since ${s.since} (plugin start or first request; reset on restart)._`)
lines.push(...llmView(llm, s))
const seen = [...(session?.seen ?? new Map())]
if (!seen.length) {
lines.push("", "Nothing replaced in this session yet.")
return lines.join("\n")
}
const byCat = new Map()
for (const [, v] of seen) byCat.set(v.category, (byCat.get(v.category) ?? 0) + 1)
lines.push("", `**${seen.length} distinct value(s) replaced:** ${[...byCat].map(([c, n]) => `${c} ${n}`).join(" · ")}`, "")
for (const [ph, v] of seen.slice(-80).reverse()) {
const value = session.lookup(ph)
lines.push(`- ${new Date(v.at).toLocaleTimeString()} · ${v.late ? "⚠️ " : ""}${v.category} · \`${value === undefined ? "(expired)" : mask(value, visible)}\` · \`${ph}\``)
}
if (seen.length > 80) lines.push(`- … ${seen.length - 80} older`)
lines.push("", `_Values are masked on purpose: this output becomes part of the conversation. Visible characters: \`command.mask_chars\` (${visible})._`)
return lines.join("\n")
}
const filter = (sub, args, sessionID) => {
if (!deps.filter) return "Not available."
if (!sessionID) return "No session."
if (sub === "on") {
const was = deps.filter.get(sessionID)
deps.filter.set(sessionID, null)
return was
? "🛡️ **VibeGuard is active again for this session.** From the next request on, all known secrets and detected values in the whole history are replaced by placeholders again – including what was sent unfiltered before. What the provider already received cannot be taken back."
: "VibeGuard is already active for this session."
}
const scope = args[0] === "all" ? "all" : "secrets"
deps.filter.set(sessionID, scope)
return [
`⚠️ **VibeGuard is OFF for this session${scope === "all" ? " (including routing rules)" : ""}.**`,
"",
"- Requests go to the provider **unfiltered**: no placeholders, earlier placeholders in the history are sent as real values, no payload guard.",
"- Registered secret files are no longer protected from read tools.",
scope === "all"
? "- Routing rules are lifted: data from restricted sources (e.g. `exchange`) may go to this model."
: "- Routing rules stay active (restricted sources only on allowed endpoints). `/" + name + " off all` lifts them too.",
"- Other sessions are not affected. Every unfiltered request is written to the audit log.",
"",
`\`/${name} on\` turns protection back on. A restart of OpenCode turns it back on as well.`,
].join("\n")
}
/** /vibeguard route off [30m|2h|session] | route on | route: lift routing only, secrets stay replaced. */
const route = (args, sessionID) => {
const r = deps.filter?.route
if (!r) return "Not available."
if (!sessionID) return "No session."
const sub = (args[0] ?? "").toLowerCase()
const until = (lift) => (lift.until ? `until ${new Date(lift.until).toLocaleTimeString()}` : "until `/" + name + " route on` or a restart")
if (sub === "on") {
return r.set(sessionID, null)
? "🛡️ **Routing rules are active again for this session.** Data from restricted sources is only sent to allowed endpoints."
: "Routing rules are already active for this session."
}
if (sub !== "off") {
const lift = r.get(sessionID)
return lift ? `⚠️ Routing is lifted for this session ${until(lift)}. \`/${name} route on\` restores it.` : `Routing rules are active for this session. \`/${name} route off [30m|2h|session]\` lifts them (secrets stay replaced).`
}
const ms = liftDuration(args[1])
if (ms === null) return `Usage: \`/${name} route off [30m|2h|session]\` (default 1h).`
if (ms === undefined) return "Duration must be between 1 minute and 7 days."
const lift = r.set(sessionID, ms)
return [
`⚠️ **Routing rules are lifted for this session ${until(lift)}.**`,
"",
"- Data from restricted sources (e.g. `exchange`) may now go to the current model, also a cloud model; restricted tools are no longer refused.",
"- **Secrets stay replaced** (known secrets, rules, local LLM scan, remembered values, payload guard).",
"- Every request that carries restricted data is written to the audit log (`routing.lifted`). Other sessions are not affected.",
"",
`\`/${name} route on\` restores the rules; a restart of OpenCode does as well.`,
].join("\n")
}
const placeholderShape = () => new RegExp(`^${escapeRegex(config.prefix ?? "__VG_")}[A-Z0-9_]+_[a-f0-9]{12}(?:_\\d+)?__$`)
/**
* The argument of why/forget: a placeholder, or the value as the user sees it (answers show real values).
* undefined = no argument, null = not replaced in this session.
*/
const placeholderOf = async (rest, sessionID) => {
const arg = String(rest ?? "").trim().replace(/^(["'`])([\s\S]*)\1$/, "$2")
if (!arg) return undefined
if (placeholderShape().test(arg)) return arg
return (await deps.resolve?.(sessionID, arg)) ?? null
}
/** Argument of allow/allow-global: { placeholder?, value?, known } or null (no argument). Never echoed. */
const target = async (rest, sessionID) => {
const arg = String(rest ?? "").trim().replace(/^(["'`])([\s\S]*)\1$/, "$2")
if (!arg) return null
if (placeholderShape().test(arg)) return { placeholder: arg, known: Boolean(deps.allow?.isKnown(sessionID, arg)) }
const ph = (await deps.resolve?.(sessionID, arg)) ?? null
return { placeholder: ph ?? undefined, value: arg, known: Boolean(deps.allow?.isKnownValue(sessionID, arg) || (ph && deps.allow?.isKnown(sessionID, ph))) }
}
const knownRefusal = (ph) => `${ph ? `\`${ph}\`` : "This value"} is a **registered secret** (secrets file, Credential Manager, password manager). Registered secrets cannot be allowed; remove it with \`/${name} remove NAME\` if it is none.`
// the argument is never echoed: it may be a real value
const notReplaced = () => "That text is not a value VibeGuard replaced in this session (compare exactly, including signs at the end)."
const SOURCES = {
known: "a **known secret** (secrets file, Credential Manager, password manager, environment)",
llm_scan: "the **local LLM check**",
session_value: "**remembered value** of this session (found earlier, matched again)",
}
/** /vibeguard why <placeholder>: everything about a replacement except the value. */
const whyView = (ph, w) => {
const src = w.source ?? ""
const by = SOURCES[src] ?? (src.startsWith("sensitive_file:") ? `a **sensitive file** (key \`${cell(src.slice(15))}\` in .env/credentials/…)` : src ? `the rule **\`${cell(src)}\`**` : "unknown (replaced before the last restart)")
const before = (w.before ?? "").replace(/\s+/g, " ").trim().slice(-60)
const lines = [
`**VibeGuard – why \`${ph}\`**`,
"",
`- Category: **${w.category}**`,
`- Found by: ${by}`,
before ? `- Text in front of it (as sent): “…${cell(before)}”` : null,
w.at ? `- First replaced: ${new Date(w.at).toLocaleString()}${w.late ? " ⚠️ by the delayed check, after it had gone out" : ""}` : null,
w.classes ? `- Characters: ${w.classes} (a lower, A upper, 9 digit, # symbol)` : null,
w.count ? `- In the last request: ${w.count}×` : null,
`- Remembered for this session: ${w.forgotten ? "no – allowed (no secret) in this session" : w.remembered ? "yes (fingerprint, also after a restart)" : "no"}${w.allowedGlobal ? " · on the global exception list" : ""}`,
"",
w.forgotten || w.allowedGlobal
? "It is no longer replaced by any detector; known secrets still apply."
: src === "known"
? `It is a registered secret; remove it with \`/${name} remove NAME\` if it is none.`
: `Not a secret? \`/${name} allow ${ph}\` (this session) or \`/${name} allow-global ${ph}\` (every session).`,
]
return lines.filter((l) => l !== null).join("\n")
}
const SOURCE_SHORT = { known: "known secret", llm_scan: "local LLM", session_value: "remembered" }
const shortSource = (src) => SOURCE_SHORT[src] ?? (String(src ?? "").startsWith("sensitive_file:") ? `sensitive file (${String(src).slice(15)})` : src ? `rule ${src}` : "before the last restart")
/** /vibeguard why without argument: the replacements of this session, newest first – never values. */
const whyList = (sessionID) => {
const session = deps.inspect?.(sessionID)?.session
const seen = [...(session?.seen ?? new Map())].filter(([ph]) => session?.known?.lookup(ph) === undefined)
if (!seen.length) return `Nothing was replaced by a detector in this session yet (registered secrets are not listed). Usage: \`/${name} why <placeholder or value as you see it>\`.`
const lines = [`**VibeGuard – why values were replaced** (${seen.length}, newest first; registered secrets not listed)`, ""]
for (const [ph, v] of seen.slice(-30).reverse()) {
lines.push(`- \`${ph}\` · ${v.category} · ${shortSource(v.source)}${v.count > 1 ? ` · ${v.count}× in the last request` : ""}${v.late ? " · ⚠️ late" : ""}`)
}
if (seen.length > 30) lines.push(`- … ${seen.length - 30} older`)
lines.push("", `Details: \`/${name} why <placeholder>\`. No secret: \`/${name} allow <placeholder>\` (this session) or \`/${name} allow-global <placeholder>\` (everywhere).`)
return lines.join("\n")
}
/**
* Commands that weaken protection can be switched off by a company policy (command.permit.*); a per-session
* override may not go below a policy floor either. Returns the refusal text or null.
*/
const refused = (permit, label) =>
config.command?.permit?.[permit] === false
? `🔒 \`/${name} ${label}\` is switched off by the company policy (\`command.permit.${permit}\`). Ask your administrator if you need it.`
: null
const belowPolicy = (key, value) => {
const doc = config.policy?.doc
const central = doc?.settings ? key.split(".").reduce((o, k) => o?.[k], doc.settings) : undefined
if (central === undefined || modeFor(doc, key) === "default") return null
const s = modeFor(doc, key) === "enforce" ? (JSON.stringify(value) === JSON.stringify(central) ? value : central) : stricter(ruleFor(key), value, central)
return s === value ? null : `🔒 The company policy sets \`${key}\` to at least \`${central}\` – \`${value}\` is not possible.`
}
/** /vibeguard policy: the company policy and its effect on this installation. */
const policyView = () => {
const p = config.policy
if (!p?.doc) {
return [
"**VibeGuard – company policy**",
"",
"No company policy is installed. Only your own configuration applies.",
p?.keys ? `- ${p.keys} trusted signing key(s) configured: a policy must be signed with one of them.` : "",
...(config.errors ?? []).filter((e) => /polic|hub\.json/i.test(e)).map((e) => `- ⚠️ ${e}`),
]
.filter(Boolean)
.join("\n")
}
const meta = p.doc.policy
const show = (v) => (typeof v === "string" ? `\`${v}\`` : `\`${JSON.stringify(v)}\``)
const MODE = { enforce: "🔒 enforced", floor: "⬆️ minimum (you may be stricter)", default: "default (you may change it)" }
const lines = [
`**VibeGuard – company policy** ${meta.id ? `\`${meta.id}\` ` : ""}version ${meta.version}${meta.name ? ` – ${meta.name}` : ""}`,
"",
`- File: \`${p.file}\`${meta.published ? ` · published ${meta.published}` : ""}`,
`- Signature: ${p.signed ? "✅ valid (trusted key)" : p.keys ? "–" : "not checked (no signing key configured)"}`,
]
if (policyMtime() > (p.mtime ?? 0)) lines.push("- ⚠️ A newer policy file is waiting – it applies after a restart of OpenCode.")
const items = describePolicy(p.doc)
lines.push("", `**Settings of the policy** (${items.length})`)
for (const d of items.slice(0, 80)) lines.push(`- \`${d.key}\` · ${MODE[d.mode === "floor" && !d.rule ? "enforce" : d.mode]} · ${show(d.value)}`)
if (items.length > 80) lines.push(`- … ${items.length - 80} more`)
if (p.changed.length) {
lines.push("", `**Your own settings that do not apply** (${p.changed.length})`)
for (const c of p.changed) lines.push(`- \`${c.key}\` · yours ${show(c.local)} → applies ${show(c.value)} (${c.mode})`)
}
return lines.join("\n")
}
/** /vibeguard urls [allow|ask|deny] [30m|2h|session] | urls reset | urls */
const urls = (args, sessionID) => {
const u = deps.filter?.urls
if (!u) return "Not available."
if (!sessionID) return "No session."
const sub = (args[0] ?? "").toLowerCase()
const label = { allow: "handed over without asking", ask: "only after your approval", deny: "refused" }
const until = (o) => (o.until ? `until ${new Date(o.until).toLocaleTimeString()}` : "until `/" + name + " urls reset` or a restart")
if (sub === "reset" || sub === "default") {
const had = u.set(sessionID, null)
return `${had ? "Restored" : "Unchanged"}: real values in URL fields are ${label[u.default()]} (config \`restore.url_fields\`: ${u.default()}).`
}
if (!label[sub]) {
const o = u.get(sessionID)
return o
? `Real values in URL fields of tool inputs are **${label[o.effect]}** in this session ${until(o)} (configured: ${u.default()}). \`/${name} urls reset\` restores it.`
: `Real values in URL fields of tool inputs are **${label[u.default()]}** (config \`restore.url_fields\`: ${u.default()}). Change it for this session: \`/${name} urls allow|ask|deny [30m|2h|session]\`.`
}
const ms = liftDuration(args[1])
if (ms === null) return `Usage: \`/${name} urls allow|ask|deny [30m|2h|session]\` (default 1h).`
if (ms === undefined) return "Duration must be between 1 minute and 7 days."
const o = u.set(sessionID, sub, ms)
return [
`${sub === "allow" ? "⚠️ " : "🛡️ "}**Real values in URL fields are ${label[sub]} in this session ${until(o)}.**`,
"",
"URL fields are tool-input fields named url/href/endpoint/… and values that are URLs. A secret in a URL leaves this machine with the request (and often ends up in server logs).",
"Other sessions are not affected; tool rules (`restore.tools`) with ask/deny still apply.",
].join("\n")
}
const check = async (args) => {
const st = getState()
const named = (st.known?.entries ?? []).slice(0, st.known?.named ?? 0)
if (!named.length) return "No known secrets registered."
const lines = ["**VibeGuard secret check**", ""]
const nonStrong = named.filter((e) => e.strength !== "strong")
const collisions = nonStrong.length ? await scanProject(directory, nonStrong.map((e) => e.value)) : new Map()
let pwned = null
if (args.includes("--hibp")) pwned = await hibpCounts(named.map((e) => e.value))
lines.push("_Name · strength · match · why · in project files · breaches (HIBP)_", "")
for (const e of named.slice(0, 100)) {
const c = collisions.get(e.value)
const hits = e.strength === "strong" ? "–" : c ? `${c.files} file(s), ${c.hits}×` : "0"
const breach = pwned ? (pwned.get(e.value) === undefined ? "?" : pwned.get(e.value) ? `⚠️ ${pwned.get(e.value)}` : "0") : "–"
lines.push(`- **${e.category}** · ${STRENGTH[e.strength] ?? "?"} · ${e.mode} · ${(e.reasons ?? []).join(", ") || "–"} · files: ${hits} · breaches: ${breach}`)
}
lines.push(
"",
"Weak secrets are only replaced right after a credential key (`Passwort: …`, `-p…`, `user:…@`). Elsewhere they are left as they are, because replacing a common word breaks normal text and code and the context gives it away anyway. **Change weak passwords.**",
"Override per name with `NAME[exact|word|context|off]=…` in the secrets file or `secrets.match`.",
)
if (!pwned) lines.push("", `Breach check: \`/${name} check --hibp\` (k-anonymity: only the first 5 hex chars of each SHA-1 hash leave this machine).`)
return lines.join("\n")
}
const add = async (restText) => {
const flags = new Set([...restText.matchAll(/(?:^|\s)--(wincred|file)(?=\s|$)/g)].map((m) => m[1]))
const wincred = flags.has("wincred") || (config.secrets?.store === "wincred" && !flags.has("file"))
const rest = restText.replace(/(?:^|\s)--(?:wincred|file)(?=\s|$)/g, "").trim()
const eq = rest.indexOf("=")
const rawName = eq >= 0 ? rest.slice(0, eq) : rest
const key = sanitizeCategory(rawName.trim())
if (!rawName.trim()) return "Usage: `/vibeguard add NAME` (value from clipboard) or `/vibeguard add NAME=value`."
let value = eq >= 0 ? rest.slice(eq + 1).trim().replace(/^(["'`])(.*)\1$/, "$2") : ""
let from = "inline"
if (!value) {
const clip = await readClipboard()
if (clip.error) return `Could not read the clipboard: ${clip.error}`
value = clip.value.trim()
from = "clipboard"
}
if (value.length < 4) return "The value is shorter than 4 characters – not added."
if (/[\r\n]/.test(value)) return "Multi-line values are not supported – not added."
let where
if (wincred) {
const res = await writeCredential(`vibeguard:${key}`, value)
if (res.error) return `Credential Manager write failed: ${res.error}`
where = `Windows Credential Manager (\`vibeguard:${key}\`)`
} else {
const file = secretsFile()
const res = await addToSecretsFile(file, key, value)
where = `\`${file}\`${res.replaced ? " (replaced)" : ""}`
}
await rebuild("command add", { refreshSlow: wincred })
audit.write("command.add", { name: key, store: wincred ? "wincred" : "file", from })
const note = from === "inline" ? "\n\nThe value was typed into the chat input; it is redacted before every provider request from now on." : ""
return `Added **${key}** (\`${mask(value, visible)}\`, from ${from}) to ${where}. It is replaced by a placeholder from now on.${note}`
}
const remove = async (args) => {
const key = sanitizeCategory(args.join(" "))
if (!args.length) return "Usage: `/vibeguard remove NAME`"
const file = secretsFile()
const res = await removeFromSecretsFile(file, key)
let wc = { error: "skipped" }
if (hasWindowsInterop()) wc = await deleteCredential(`vibeguard:${key}`)
if (!res.removed && wc.error) return `**${key}** was not found in \`${file}\` or the Credential Manager.`
await rebuild("command remove", { refreshSlow: !wc.error })
audit.write("command.remove", { name: key })
return `Removed **${key}**${res.removed ? ` from \`${file}\`` : ""}${wc.error ? "" : " from the Credential Manager"}.`
}
const test = () => {
const res = selfTest()
const head = res.ok ? (res.warnings ? `✅ passed with ${res.warnings} warning(s)` : "✅ passed") : "❌ FAILED"
const icon = (c) => (c.ok ? "✅" : c.warn ? "⚠️" : "❌")
return [`**VibeGuard self-test: ${head}**`, "", ...res.checks.map((c) => `- ${icon(c)} ${c.name}${c.detail ? ` – ${c.detail}` : ""}`)].join("\n")
}
const auditTail = (args) => {
const n = Math.min(Math.max(Number(args[0]) || 20, 1), 200)
if (!audit.enabled) return "The audit log is disabled (`audit.enabled: false`)."
const rows = audit.tail(n)
if (!rows.length) return `No audit events yet (\`${audit.path}\`).`
const fmt = (r) => {
const { schema_version, ts, type, ...rest } = r
return `- \`${ts}\` **${type}** ${Object.entries(rest).map(([k, v]) => `${k}=${Array.isArray(v) ? v.join("/") : typeof v === "object" ? JSON.stringify(v) : v}`).join(" ")}`
}
return [`**Last ${rows.length} audit events** (\`${audit.path}\`)`, "", ...rows.map(fmt)].join("\n")
}
return {
name,
async run(text, ctx = {}) {
const body = String(text ?? "").trim().replace(new RegExp(`^/?${name}\\b`), "").trim()
const m = body.match(/^(\S+)\s*([\s\S]*)$/)
const sub = m?.[1] ?? "status"
const restText = m?.[2] ?? ""
const args = restText.split(/\s+/).filter(Boolean)
switch (sub.toLowerCase()) {
case "status":
return status(ctx.sessionID)
case "add":
return add(restText)
case "remove":
case "rm":
return remove(args)
case "check":
return check(args)
case "taint":
if ((args[0] ?? "").toLowerCase() === "clear") {
const no = refused("taint_clear", "taint clear")
if (no) return no
}
return taint(args, ctx.sessionID)
case "policy":
return policyView()
case "learn":
return learnView(args)
case "why": {
if (!deps.why) return "Not available."
if (!ctx.sessionID) return "No session."
const ph = await placeholderOf(restText, ctx.sessionID)
if (ph === undefined) return whyList(ctx.sessionID)
if (ph === null) return notReplaced()
const w = await deps.why(ctx.sessionID, ph)
if (!w) return `\`${ph}\` is not known in this session.`
return whyView(ph, w)
}
case "allow":
case "forget": {
if (!deps.allow || !deps.forget) return "Not available."
const sessionID = ctx.sessionID
if (!sessionID) return "No session."
const remove = /^(?:remove|rm|undo)\b/i.test(restText.trim())
if (!remove && sub.toLowerCase() === "allow") {
const no = refused("allow", "allow")
if (no) return no
}
const arg = remove ? restText.trim().replace(/^\S+\s*/, "") : restText
const t = await target(arg, sessionID)
if (!t) return `Usage: \`/${name} allow <value or placeholder>\` – no secret, **in this session** (all detectors). \`/${name} allow remove <…>\` undoes it; \`/${name} allow-global <…>\` applies to every session.`
if (t.known) return knownRefusal(t.placeholder)
if (remove) {
const ok = await deps.allow.sessionRemove(sessionID, t.placeholder, t.value)
return ok ? `🛡️ ${t.placeholder ? `\`${t.placeholder}\`` : "The value"} is replaced again in this session (when a detector finds it).` : "That value was not allowed in this session."
}
if (t.placeholder) {
const r = await deps.forget(sessionID, t.placeholder)
if (!r.found) return `\`${t.placeholder}\` is not known in this session.`
} else await deps.allow.sessionValue(sessionID, t.value)
return `✅ ${t.placeholder ? `\`${t.placeholder}\`` : "The value (not replaced so far)"} is **no secret in this session**: it is no longer replaced – by rules, the local LLM, the sensitive-file check or remembered values. Other sessions are not affected (\`/${name} allow-global …\` for all).`
}
case "allow-global":
case "allowglobal": {
if (!deps.allow) return "Not available."
const sessionID = ctx.sessionID
const sub = (args[0] ?? "").toLowerCase()
if (!sub || sub === "list") {
const list = await deps.allow.globalList()
if (!list.length) return `No global exceptions. \`/${name} allow-global <value or placeholder>\` adds one – it then applies at once in every session.`
return [
`**VibeGuard – global exceptions (${list.length})** – never replaced, in every session. Only fingerprints are stored, never the values.`,
"",
...list.slice(0, 100).map((e) => `- ${new Date(e.at).toLocaleString()} · ${e.category || "–"} · ${e.ph ? `\`${e.ph}\`` : "(added by value)"}`),
"",
`\`/${name} allow-global remove <value or placeholder>\` removes one.`,
].join("\n")
}
if (!sessionID) return "No session."
const remove = /^(?:remove|rm|undo)$/.test(sub)
if (!remove) {
const no = refused("allow_global", "allow-global")
if (no) return no
}
const arg = remove ? restText.trim().replace(/^\S+\s*/, "") : restText
const t = await target(arg, sessionID)
if (!t) return `Usage: \`/${name} allow-global <value or placeholder>\` | \`allow-global list\` | \`allow-global remove <…>\``
if (t.known) return knownRefusal(t.placeholder)
if (remove) {
const ok = await deps.allow.globalRemove(sessionID, t.placeholder, t.value)
return ok ? "🛡️ Removed from the global exceptions: it is replaced again in every session (when a detector finds it)." : "That value is not on the global list."
}
const r = await deps.allow.global(sessionID, t.placeholder, t.value)
if (!r.found) return `\`${t.placeholder}\` is not known in this session – use the value as you see it instead.`
return `✅ ${t.placeholder ? `\`${t.placeholder}\`` : "The value"} is **no secret – in every session**, from the next request on (other open projects within seconds). Stored as a fingerprint only. \`/${name} allow-global list\` shows the list.`
}
case "alert":
case "alerts": {
if (!deps.alerts) return "Not available."
const ch = deps.alerts.channels
if ((args[0] ?? "").toLowerCase() !== "test") return `Alert channels: desktop ${ch.desktop ? "on" : "off"} · e-mail ${ch.email ?? "off"}. Send a test with: ${name} alert test`
const r = await deps.alerts.test()
return `Test alarm sent – desktop: ${r.desktop ?? "off"} · e-mail: ${r.email ?? "off"}`
}
case "compact":
case "compaction": {
if (!deps.compact) return "Not available."
if (!ctx.sessionID) return "No session."
const r = await deps.compact(ctx.sessionID)
return r.ok
? "Compaction requested – OpenCode summarizes the older conversation at the next safe point and continues from the summary. Stored messages stay; images are not sent to the summary request."
: `Compaction could not be requested: ${r.error}`
}
case "session":
case "stats":
return sessionView(ctx.sessionID)
case "off":
case "on":
if (sub.toLowerCase() === "off") {
const no = refused("off", "off")
if (no) return no
}
return filter(sub.toLowerCase(), args, ctx.sessionID)
case "route":
case "routing":
if ((args[0] ?? "").toLowerCase() === "off") {
const no = refused("route_off", "route off")
if (no) return no
}
return route(args, ctx.sessionID)
case "fingerprints":
case "fp": {
if (!deps.routing?.prune) return "Routing is not configured."
if ((args[0] ?? "").toLowerCase() !== "prune") return `Content fingerprints of restricted sources: ${deps.routing.fingerprints()}. \`/${name} fingerprints prune\` removes common text (found in several sessions without data from the source).`
const r = await deps.routing.prune()
if (r.error) return `Not possible: ${r.error}`
return `Checked ${r.sessions} session(s): ${r.retired} fingerprint(s) of common text or tool documentation removed, ${r.left} left. Copied content from restricted sources is still recognized.`
}
case "urls":
case "url": {
const want = (args[0] ?? "").toLowerCase()
if (want === "allow") {
const no = refused("urls_allow", "urls allow")
if (no) return no
}
if (["allow", "ask", "deny"].includes(want)) {
const no = belowPolicy("restore.url_fields", want)
if (no) return no
}
return urls(args, ctx.sessionID)
}
case "reload":
await rebuild("command reload", { refreshSlow: true })
return `Reloaded.\n\n${await status(ctx.sessionID)}`
case "test":
case "selftest":
return test()
case "audit":
return auditTail(args)
default:
return HELP(name)
}
},
}
}