@cybedefend/vibedefend 1.8.2 → 1.9.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 +185 -17
- package/dist/auth/auth-store.js +16 -0
- package/dist/auth/auth-store.js.map +1 -1
- package/dist/clients/antigravity.js +30 -6
- package/dist/clients/antigravity.js.map +1 -1
- package/dist/clients/claude-code.js +209 -17
- package/dist/clients/claude-code.js.map +1 -1
- package/dist/clients/codex.js +171 -11
- package/dist/clients/codex.js.map +1 -1
- package/dist/clients/cursor.js +149 -9
- package/dist/clients/cursor.js.map +1 -1
- package/dist/clients/dependency-check-wiring.js +24 -0
- package/dist/clients/dependency-check-wiring.js.map +1 -0
- package/dist/clients/opencode-plugin.js +905 -0
- package/dist/clients/opencode-plugin.js.map +1 -0
- package/dist/clients/opencode.js +653 -0
- package/dist/clients/opencode.js.map +1 -0
- package/dist/clients/registry.js +2 -0
- package/dist/clients/registry.js.map +1 -1
- package/dist/clients/vscode.js +106 -12
- package/dist/clients/vscode.js.map +1 -1
- package/dist/clients/windsurf.js +9 -1
- package/dist/clients/windsurf.js.map +1 -1
- package/dist/commands/mcp/index.js +11 -0
- package/dist/commands/mcp/index.js.map +1 -1
- package/dist/config.js +4 -1
- package/dist/config.js.map +1 -1
- package/dist/diagnostics.js +22 -3
- package/dist/diagnostics.js.map +1 -1
- package/dist/doctor.js +26 -1
- package/dist/doctor.js.map +1 -1
- package/dist/guards-evaluator/command-analysis.js +347 -86
- package/dist/guards-evaluator/command-analysis.js.map +1 -1
- package/dist/guards-evaluator/command-view.js +116 -16
- package/dist/guards-evaluator/command-view.js.map +1 -1
- package/dist/guards-evaluator/evaluate.js +185 -41
- package/dist/guards-evaluator/evaluate.js.map +1 -1
- package/dist/guards-evaluator/file-reads.js +202 -0
- package/dist/guards-evaluator/file-reads.js.map +1 -0
- package/dist/guards-evaluator/index.js +1 -1
- package/dist/guards-evaluator/index.js.map +1 -1
- package/dist/guards-evaluator/inline-danger.js +299 -0
- package/dist/guards-evaluator/inline-danger.js.map +1 -0
- package/dist/guards-evaluator/normalize.js +1186 -55
- package/dist/guards-evaluator/normalize.js.map +1 -1
- package/dist/guards-evaluator/regex.js +91 -4
- package/dist/guards-evaluator/regex.js.map +1 -1
- package/dist/guards-evaluator/shell-files.js +587 -0
- package/dist/guards-evaluator/shell-files.js.map +1 -0
- package/dist/guards-evaluator/triage.js +32 -2
- package/dist/guards-evaluator/triage.js.map +1 -1
- package/dist/hook-runner.js +25601 -5423
- package/dist/hooks/install.js +8 -3
- package/dist/hooks/install.js.map +1 -1
- package/dist/hooks/runtime/antigravity-session.js +109 -50
- package/dist/hooks/runtime/antigravity-session.js.map +1 -1
- package/dist/hooks/runtime/apply-patch.js +92 -0
- package/dist/hooks/runtime/apply-patch.js.map +1 -0
- package/dist/hooks/runtime/caller-gate.js +27 -0
- package/dist/hooks/runtime/caller-gate.js.map +1 -0
- package/dist/hooks/runtime/code-mode.js +259 -0
- package/dist/hooks/runtime/code-mode.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/api.js +179 -0
- package/dist/hooks/runtime/dependency-check/api.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/capabilities.js +99 -0
- package/dist/hooks/runtime/dependency-check/capabilities.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/checked-packages.js +48 -0
- package/dist/hooks/runtime/dependency-check/checked-packages.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/commands/cwd.js +154 -0
- package/dist/hooks/runtime/dependency-check/commands/cwd.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/commands/env.js +99 -0
- package/dist/hooks/runtime/dependency-check/commands/env.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/commands/flags.js +164 -0
- package/dist/hooks/runtime/dependency-check/commands/flags.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/commands/managers.js +418 -0
- package/dist/hooks/runtime/dependency-check/commands/managers.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/commands/peel.js +111 -0
- package/dist/hooks/runtime/dependency-check/commands/peel.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/commands/shell.js +217 -0
- package/dist/hooks/runtime/dependency-check/commands/shell.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/commands/types.js +4 -0
- package/dist/hooks/runtime/dependency-check/commands/types.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/commands.js +34 -0
- package/dist/hooks/runtime/dependency-check/commands.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/deadlines.js +69 -0
- package/dist/hooks/runtime/dependency-check/deadlines.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/dispatch.js +344 -0
- package/dist/hooks/runtime/dependency-check/dispatch.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/entering.js +63 -0
- package/dist/hooks/runtime/dependency-check/entering.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/exec-cache.js +36 -0
- package/dist/hooks/runtime/dependency-check/exec-cache.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/git-blob.js +116 -0
- package/dist/hooks/runtime/dependency-check/git-blob.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/hook.js +418 -0
- package/dist/hooks/runtime/dependency-check/hook.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/local-store.js +74 -0
- package/dist/hooks/runtime/dependency-check/local-store.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfile-walk.js +89 -0
- package/dist/hooks/runtime/dependency-check/lockfile-walk.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/bun.js +153 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/bun.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/by-name.js +46 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/by-name.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/cargo.js +91 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/cargo.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/composer.js +98 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/composer.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/gemfile.js +88 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/gemfile.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/go-mod.js +154 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/go-mod.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/gradle-lockfile.js +27 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/gradle-lockfile.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/graph.js +131 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/graph.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/npm.js +107 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/npm.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/nuget-packages-lock.js +60 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/nuget-packages-lock.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/pins.js +105 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/pins.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/pip-report.js +34 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/pip-report.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/pnpm.js +109 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/pnpm.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/poetry.js +105 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/poetry.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/uv.js +181 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/uv.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/yaml.js +319 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/yaml.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/yarn-berry.js +71 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/yarn-berry.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/yarn1.js +144 -0
- package/dist/hooks/runtime/dependency-check/lockfiles/yarn1.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/manifests/apply.js +110 -0
- package/dist/hooks/runtime/dependency-check/manifests/apply.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/manifests/diff.js +127 -0
- package/dist/hooks/runtime/dependency-check/manifests/diff.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/manifests/edit.js +259 -0
- package/dist/hooks/runtime/dependency-check/manifests/edit.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/manifests/json.js +109 -0
- package/dist/hooks/runtime/dependency-check/manifests/json.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/manifests/kind.js +40 -0
- package/dist/hooks/runtime/dependency-check/manifests/kind.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/manifests/patch.js +179 -0
- package/dist/hooks/runtime/dependency-check/manifests/patch.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/manifests/text.js +665 -0
- package/dist/hooks/runtime/dependency-check/manifests/text.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/manifests/toml.js +350 -0
- package/dist/hooks/runtime/dependency-check/manifests/toml.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/manifests.js +14 -0
- package/dist/hooks/runtime/dependency-check/manifests.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/messages.js +270 -0
- package/dist/hooks/runtime/dependency-check/messages.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/net-baseline.js +157 -0
- package/dist/hooks/runtime/dependency-check/net-baseline.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/net-state.js +70 -0
- package/dist/hooks/runtime/dependency-check/net-state.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/pending-forces.js +54 -0
- package/dist/hooks/runtime/dependency-check/pending-forces.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/post-tool-use.js +108 -0
- package/dist/hooks/runtime/dependency-check/post-tool-use.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/ranges.js +369 -0
- package/dist/hooks/runtime/dependency-check/ranges.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/requirement-files.js +144 -0
- package/dist/hooks/runtime/dependency-check/requirement-files.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/bun.js +38 -0
- package/dist/hooks/runtime/dependency-check/resolvers/bun.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/bundler.js +218 -0
- package/dist/hooks/runtime/dependency-check/resolvers/bundler.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/cargo.js +303 -0
- package/dist/hooks/runtime/dependency-check/resolvers/cargo.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/composer.js +250 -0
- package/dist/hooks/runtime/dependency-check/resolvers/composer.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/config-files.js +27 -0
- package/dist/hooks/runtime/dependency-check/resolvers/config-files.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/direct-only-registry.js +409 -0
- package/dist/hooks/runtime/dependency-check/resolvers/direct-only-registry.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/direct-only.js +290 -0
- package/dist/hooks/runtime/dependency-check/resolvers/direct-only.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/gem.js +89 -0
- package/dist/hooks/runtime/dependency-check/resolvers/gem.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/go.js +313 -0
- package/dist/hooks/runtime/dependency-check/resolvers/go.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/npm.js +81 -0
- package/dist/hooks/runtime/dependency-check/resolvers/npm.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/pip.js +229 -0
- package/dist/hooks/runtime/dependency-check/resolvers/pip.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/pipx.js +8 -0
- package/dist/hooks/runtime/dependency-check/resolvers/pipx.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/pnpm.js +68 -0
- package/dist/hooks/runtime/dependency-check/resolvers/pnpm.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/poetry.js +70 -0
- package/dist/hooks/runtime/dependency-check/resolvers/poetry.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/project.js +208 -0
- package/dist/hooks/runtime/dependency-check/resolvers/project.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/python-index.js +270 -0
- package/dist/hooks/runtime/dependency-check/resolvers/python-index.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/python.js +229 -0
- package/dist/hooks/runtime/dependency-check/resolvers/python.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/registry.js +221 -0
- package/dist/hooks/runtime/dependency-check/resolvers/registry.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/shared.js +440 -0
- package/dist/hooks/runtime/dependency-check/resolvers/shared.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/tree.js +131 -0
- package/dist/hooks/runtime/dependency-check/resolvers/tree.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/uv.js +433 -0
- package/dist/hooks/runtime/dependency-check/resolvers/uv.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/xml-lite.js +132 -0
- package/dist/hooks/runtime/dependency-check/resolvers/xml-lite.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/resolvers/yarn-berry.js +106 -0
- package/dist/hooks/runtime/dependency-check/resolvers/yarn-berry.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/sandbox.js +328 -0
- package/dist/hooks/runtime/dependency-check/sandbox.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/specs.js +171 -0
- package/dist/hooks/runtime/dependency-check/specs.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/static-view.js +90 -0
- package/dist/hooks/runtime/dependency-check/static-view.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/stop-net.js +278 -0
- package/dist/hooks/runtime/dependency-check/stop-net.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/stop-wiring.js +94 -0
- package/dist/hooks/runtime/dependency-check/stop-wiring.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/tool-call.js +130 -0
- package/dist/hooks/runtime/dependency-check/tool-call.js.map +1 -0
- package/dist/hooks/runtime/dependency-check/types.js +96 -0
- package/dist/hooks/runtime/dependency-check/types.js.map +1 -0
- package/dist/hooks/runtime/emit.js +240 -52
- package/dist/hooks/runtime/emit.js.map +1 -1
- package/dist/hooks/runtime/exit-deadlock-guard.js +24 -8
- package/dist/hooks/runtime/exit-deadlock-guard.js.map +1 -1
- package/dist/hooks/runtime/fetch-rules.js +78 -29
- package/dist/hooks/runtime/fetch-rules.js.map +1 -1
- package/dist/hooks/runtime/grep-include.js +228 -0
- package/dist/hooks/runtime/grep-include.js.map +1 -0
- package/dist/hooks/runtime/pre-compact.js +1 -1
- package/dist/hooks/runtime/pre-compact.js.map +1 -1
- package/dist/hooks/runtime/pre-invocation.js +3 -3
- package/dist/hooks/runtime/pre-invocation.js.map +1 -1
- package/dist/hooks/runtime/repo-registry.js +72 -0
- package/dist/hooks/runtime/repo-registry.js.map +1 -0
- package/dist/hooks/runtime/repo-scope.js +75 -0
- package/dist/hooks/runtime/repo-scope.js.map +1 -0
- package/dist/hooks/runtime/resolve.js +11 -2
- package/dist/hooks/runtime/resolve.js.map +1 -1
- package/dist/hooks/runtime/runner-args.js +17 -2
- package/dist/hooks/runtime/runner-args.js.map +1 -1
- package/dist/hooks/runtime/script-resolve.js +21 -5
- package/dist/hooks/runtime/script-resolve.js.map +1 -1
- package/dist/hooks/runtime/session-activation.js +71 -18
- package/dist/hooks/runtime/session-activation.js.map +1 -1
- package/dist/hooks/runtime/session-review.js +184 -88
- package/dist/hooks/runtime/session-review.js.map +1 -1
- package/dist/hooks/runtime/session-start.js +68 -13
- package/dist/hooks/runtime/session-start.js.map +1 -1
- package/dist/hooks/runtime/session-writes.js +11 -5
- package/dist/hooks/runtime/session-writes.js.map +1 -1
- package/dist/hooks/runtime/shell-writes.js +7 -88
- package/dist/hooks/runtime/shell-writes.js.map +1 -1
- package/dist/hooks/runtime/sniff.js +227 -2
- package/dist/hooks/runtime/sniff.js.map +1 -1
- package/dist/hooks/runtime/target-resolve.js +32 -17
- package/dist/hooks/runtime/target-resolve.js.map +1 -1
- package/dist/hooks/runtime/unmapped-tools.js +77 -1
- package/dist/hooks/runtime/unmapped-tools.js.map +1 -1
- package/dist/hooks/runtime/user-prompt-submit.js +1 -1
- package/dist/hooks/runtime/user-prompt-submit.js.map +1 -1
- package/dist/hooks/runtime/work-dir.js +3 -0
- package/dist/hooks/runtime/work-dir.js.map +1 -1
- package/dist/hooks/shim.js +27 -20
- package/dist/hooks/shim.js.map +1 -1
- package/dist/index.js +46 -10
- package/dist/index.js.map +1 -1
- package/dist/install-scope.js +12 -0
- package/dist/install-scope.js.map +1 -0
- package/dist/install.js +188 -78
- package/dist/install.js.map +1 -1
- package/dist/link.js +55 -5
- package/dist/link.js.map +1 -1
- package/dist/mcp/config/hook.js +25 -0
- package/dist/mcp/config/hook.js.map +1 -1
- package/dist/org.js +3 -1
- package/dist/org.js.map +1 -1
- package/dist/prompts.js +97 -13
- package/dist/prompts.js.map +1 -1
- package/dist/refresh-hooks.js +67 -15
- package/dist/refresh-hooks.js.map +1 -1
- package/dist/repo/exclude-block.js +112 -0
- package/dist/repo/exclude-block.js.map +1 -0
- package/dist/repo/footer.js +93 -0
- package/dist/repo/footer.js.map +1 -0
- package/dist/repo/git-repo.js +77 -0
- package/dist/repo/git-repo.js.map +1 -0
- package/dist/repo/guarded-write.js +45 -0
- package/dist/repo/guarded-write.js.map +1 -0
- package/dist/repo/install-repo.js +508 -0
- package/dist/repo/install-repo.js.map +1 -0
- package/dist/repo/machine-wiring.js +122 -0
- package/dist/repo/machine-wiring.js.map +1 -0
- package/dist/repo/mcp-json.js +57 -0
- package/dist/repo/mcp-json.js.map +1 -0
- package/dist/repo/registry.js +53 -0
- package/dist/repo/registry.js.map +1 -0
- package/dist/repo/repo-mode-guard.js +83 -0
- package/dist/repo/repo-mode-guard.js.map +1 -0
- package/dist/repo/repo-setups.js +123 -0
- package/dist/repo/repo-setups.js.map +1 -0
- package/dist/repo/repo-status.js +283 -0
- package/dist/repo/repo-status.js.map +1 -0
- package/dist/repo/uninstall-repo.js +56 -0
- package/dist/repo/uninstall-repo.js.map +1 -0
- package/dist/repo/unsupported.js +14 -0
- package/dist/repo/unsupported.js.map +1 -0
- package/dist/scan-diff.js +526 -0
- package/dist/scan-diff.js.map +1 -0
- package/dist/shim.js +9 -7
- package/dist/status.js +53 -11
- package/dist/status.js.map +1 -1
- package/dist/uninstall.js +51 -3
- package/dist/uninstall.js.map +1 -1
- package/dist/update-check-gate.js +17 -0
- package/dist/update-check-gate.js.map +1 -0
- package/dist/update.js +6 -1
- package/dist/update.js.map +1 -1
- package/dist/zip.js +95 -0
- package/dist/zip.js.map +1 -0
- package/package.json +6 -3
|
@@ -0,0 +1,905 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The OpenCode plugin (BACK-255).
|
|
3
|
+
*
|
|
4
|
+
* OpenCode runs no hook command: it loads every `*.js` file of its
|
|
5
|
+
* `plugins/` directory as an ES module and calls its hooks in-process. The
|
|
6
|
+
* adapter (`opencode.ts`) writes the file `renderOpenCodePlugin` returns to
|
|
7
|
+
* `<config dir>/plugins/cybedefend-vibedefend.js`.
|
|
8
|
+
*
|
|
9
|
+
* The plugin only TRANSPORTS. For each hook it spawns the hook runner,
|
|
10
|
+
* `[NODE, RUNNER, <sub>, '--client', 'opencode']`, writes an envelope on its
|
|
11
|
+
* stdin, and acts on the first stdout line that parses as a JSON object (the
|
|
12
|
+
* answer contract of `emitOpenCodeAnswer`, emit.ts). Every decision (which
|
|
13
|
+
* rules apply, whether a guard denies, what the bootstrap and the review
|
|
14
|
+
* say, whether a session was already reviewed) is the runner's.
|
|
15
|
+
*
|
|
16
|
+
* One file serves both OpenCodes: `export default { id, server, setup }`. V1
|
|
17
|
+
* (>= 1.18.29) wants `{ id, server }` and V2 `{ id, setup }`, and each ignores
|
|
18
|
+
* the key it does not know (`plugin/shared.ts` in V1, `plugin/module.ts` in
|
|
19
|
+
* V2). V1 also calls `setup`, with a context that has neither `tool` nor
|
|
20
|
+
* `location` (probe Q11, V1's `core/src/plugin/promise.ts`), so `setup` starts by
|
|
21
|
+
* looking for the two the guard needs and returns at once without them. Session
|
|
22
|
+
* start, the review and the MCP names each look for their own and are off alone
|
|
23
|
+
* when theirs is missing.
|
|
24
|
+
*
|
|
25
|
+
* ## `server`, for OpenCode V1
|
|
26
|
+
*
|
|
27
|
+
* - `config(cfg)`: remembers the MCP server names (`cfg.mcp` keys), which
|
|
28
|
+
* every envelope carries so the runner can read an MCP tool id.
|
|
29
|
+
* - `tool.execute.before`: for `write`, `edit`, `apply_patch` and `bash`,
|
|
30
|
+
* starts `fetch-rules` without waiting for it; then waits for
|
|
31
|
+
* `guard-check`. A `deny` (or Claude Code's `block`, which the runner
|
|
32
|
+
* answers on an envelope it failed to recognise) throws its reason:
|
|
33
|
+
* OpenCode does not run the tool and the model reads the message as the
|
|
34
|
+
* tool's error. A warn's `context` is kept for the after hook, and so is
|
|
35
|
+
* a note when guard-check could not answer (timeout, no process, an
|
|
36
|
+
* unreadable answer): the call goes through unverified.
|
|
37
|
+
* - `tool.execute.after`: appends that note, the kept warn, then the rules
|
|
38
|
+
* (awaited, bounded by the same timeout), to what the model reads of the
|
|
39
|
+
* result: `output.output` for a built-in tool, `output.content[]` for an
|
|
40
|
+
* MCP one.
|
|
41
|
+
* - `chat.message`: the first message of a ROOT session runs
|
|
42
|
+
* `session-start`; its context is pushed as a synthetic text part, which
|
|
43
|
+
* reaches the model and is hidden in the TUI.
|
|
44
|
+
* - `event`: `session.created` caches the session's parent, `session.error`
|
|
45
|
+
* marks it (a `chat.message` clears the mark), and `session.idle` of an
|
|
46
|
+
* unmarked root session runs `session-review` and sends its context back
|
|
47
|
+
* with `client.session.promptAsync`, under the agent of the session's
|
|
48
|
+
* last `chat.message` (without one, OpenCode would run the review turn
|
|
49
|
+
* with its default agent, even for a user in `plan` or a restricted
|
|
50
|
+
* agent). At most one review run per session is in flight: the runner's
|
|
51
|
+
* `reviewed` marker is not an atomic claim.
|
|
52
|
+
*
|
|
53
|
+
* Root vs child: OpenCode's `session.idle` carries only the session id, and
|
|
54
|
+
* `chat.message` also fires for a subagent's first message (and for the
|
|
55
|
+
* review prompt itself). The parent comes from `session.created`, else from
|
|
56
|
+
* ONE `client.session.get` per session, cached; a failed read counts as a
|
|
57
|
+
* root session. Every envelope also carries `rootSessionID`, the session at
|
|
58
|
+
* the top of that chain (a subagent's tool calls carry the child's own
|
|
59
|
+
* `sessionID`): the runner files a subagent's edits, violations and notices
|
|
60
|
+
* under the root session, whose review reads them.
|
|
61
|
+
*
|
|
62
|
+
* ## `setup`, for OpenCode V2
|
|
63
|
+
*
|
|
64
|
+
* One `setup` per location (a project directory), again after a hot reload,
|
|
65
|
+
* whose cleanup runs first. The envelope is V1's, stamped `opencode: 2`:
|
|
66
|
+
* `directory` is the location of the `setup` that handled the call, so moving
|
|
67
|
+
* a session cannot move what a later call is gated against, and the runner is
|
|
68
|
+
* spawned there too, since V2's one server runs from the user's home. A
|
|
69
|
+
* stringified `input` is parsed first, or sent as `{}`, so nothing of it is
|
|
70
|
+
* logged: V2 repairs it in a plugin of its own, which should run before this
|
|
71
|
+
* one, but that rests on an order read in the source and not probed.
|
|
72
|
+
*
|
|
73
|
+
* - `tool.hook('execute.before')`: for `write`, `edit`, `patch` and `shell`,
|
|
74
|
+
* starts `fetch-rules` without waiting for it; then waits for
|
|
75
|
+
* `guard-check`. A deny throws its reason, the one deliberate throw of this
|
|
76
|
+
* half. A warn, or a note that guard-check could not answer, is kept.
|
|
77
|
+
* - `tool.hook('execute.after')`: when the tool completed, puts that note,
|
|
78
|
+
* the warn, then the rules IN FRONT of the first text item of
|
|
79
|
+
* `result.content`. Not as an item of its own: a TUI shows only the first
|
|
80
|
+
* text item of `shell`, so its output would disappear (probe Q4). Not at the
|
|
81
|
+
* end: V2 truncates a result after this hook.
|
|
82
|
+
* - Code Mode: the model calls `execute` with a program, whose MCP calls fire
|
|
83
|
+
* the same two hooks under the same id, inner after-hook first, and what an
|
|
84
|
+
* inner after-hook adds never reaches the model. So guard-check runs on
|
|
85
|
+
* every inner call (its throw blocks that call alone) and whatever it says
|
|
86
|
+
* waits for the `execute` after-hook.
|
|
87
|
+
* - `session.hook('prompt')`: the first message of a root session runs
|
|
88
|
+
* `session-start` and puts its context in the session's hidden instructions
|
|
89
|
+
* under one key, which a later put replaces: a reload cannot double it.
|
|
90
|
+
* When that fails or does not exist, `session.hook('context')` carries the
|
|
91
|
+
* text instead, on every request of that session, since it does not persist.
|
|
92
|
+
* - `event.subscribe`: `session.created` caches the parent, and
|
|
93
|
+
* `session.execution.succeeded` of a root session runs `session-review` and
|
|
94
|
+
* sends its context with `session.prompt`, whose turn keeps the session's
|
|
95
|
+
* agent. That turn ends in a second `succeeded`: the runner's marker answers
|
|
96
|
+
* nothing to it. The cleanup aborts the subscription.
|
|
97
|
+
*
|
|
98
|
+
* Every location's `setup` gets every session's event: `load` in
|
|
99
|
+
* `core/src/plugin.ts` replaces a plugin's fiber context, so `local` in
|
|
100
|
+
* `core/src/bus.ts` finds no location and filters nothing, while a hook fires
|
|
101
|
+
* only in the session's own location (`instances.provide(session)`). So what is
|
|
102
|
+
* true of a session wherever it is read can come from an event (its parent), and
|
|
103
|
+
* what depends on where it is cannot be kept per `setup`:
|
|
104
|
+
*
|
|
105
|
+
* - Only the `setup` of the location the session is in now reviews it, asked of
|
|
106
|
+
* `session.get` when the event arrives and again before the prompt, since a
|
|
107
|
+
* session can move. An unreadable session gets no review: a lost review costs
|
|
108
|
+
* nothing, a doubled one a turn.
|
|
109
|
+
* - A session whose last execution failed gets no review. That is the session's
|
|
110
|
+
* `outcome`, the server's own answer: a mark kept here off
|
|
111
|
+
* `session.execution.failed` is set in every location and cleared only in the
|
|
112
|
+
* one whose `prompt` hook fired, so it goes stale in the others.
|
|
113
|
+
* - The review prompt carries `metadata`, which reaches the `prompt` hook of
|
|
114
|
+
* whichever location it fires in, so it never reads as a user's message there.
|
|
115
|
+
*
|
|
116
|
+
* Each location also evaluates this file on its own (`prepareSource`,
|
|
117
|
+
* `plugin/src/source.bun.ts` and `source.node.ts`), so a variable at the top of
|
|
118
|
+
* the module is per location too.
|
|
119
|
+
*
|
|
120
|
+
* A throw from `execute.after` fails that tool call, from `prompt` refuses the
|
|
121
|
+
* user's message, from `context` fails the whole execution (probe Q14), so every
|
|
122
|
+
* hook body is wrapped. The registration of `execute.before` is not: its failure
|
|
123
|
+
* rejects `setup`, and V2 lists the plugin as failed (`load`, `core/src/plugin.ts`).
|
|
124
|
+
*
|
|
125
|
+
* ## Both
|
|
126
|
+
*
|
|
127
|
+
* Constraints on the generated file (OpenCode facts 2 and 11):
|
|
128
|
+
* - ONE default export and no other: OpenCode skips a file with any
|
|
129
|
+
* export that is not a function.
|
|
130
|
+
* - It runs under Bun (the CLI) and Node (the desktop app's Electron), so
|
|
131
|
+
* it imports only `node:child_process` (the asynchronous `spawn`: a
|
|
132
|
+
* synchronous one blocks the whole server) and `node:fs`.
|
|
133
|
+
* - It never writes to the standard streams and never logs: ACP mode
|
|
134
|
+
* speaks its protocol on stdout. The runner's stderr is ignored.
|
|
135
|
+
* - Any failure (no node, no runner, a crash, a timeout, an unreadable
|
|
136
|
+
* answer) lets the call through: `{"decision":"allow"}` for the two
|
|
137
|
+
* tool hooks, `{}` for the others. A child is killed at the timeout,
|
|
138
|
+
* also when it answered but does not exit, so none outlives it. It is a
|
|
139
|
+
* direct child running the runner in its own process (the shim imports it),
|
|
140
|
+
* so the kill leaves nothing. The timer lives in OpenCode's process: if that
|
|
141
|
+
* dies first, the runner ends on its own requests' timeouts (8 to 10 s
|
|
142
|
+
* measured, against a gateway that never answers).
|
|
143
|
+
* - The timeout is {@link OPENCODE_GUARD_TIMEOUT_MS} for `guard-check`,
|
|
144
|
+
* {@link OPENCODE_PLUGIN_TIMEOUT_MS} for every other run. OpenCode waits
|
|
145
|
+
* for `tool.execute.before` with no bound of its own, and the guard's
|
|
146
|
+
* worst case is longer than 10 s: a stale rules cache refreshed (8 s), the
|
|
147
|
+
* judge (1.5 s), keychain reads (2 s each), the project lookup (4 s),
|
|
148
|
+
* node's start. Antigravity gives the same runner 30 s.
|
|
149
|
+
* - At most 8 `guard-check` runs are alive at once per evaluation of this
|
|
150
|
+
* file, in the order they asked; the timeout counts from the spawn.
|
|
151
|
+
*/
|
|
152
|
+
/**
|
|
153
|
+
* The first line of every plugin file vibedefend writes. A file at the
|
|
154
|
+
* plugin path is ours when it starts with this line AND references the hook
|
|
155
|
+
* runner (`textReferencesHookRunner`); any other file is never overwritten
|
|
156
|
+
* nor deleted.
|
|
157
|
+
*/
|
|
158
|
+
export const OPENCODE_PLUGIN_MARKER = '// cybedefend-vibedefend: written by vibedefend install, rewritten on every install and update.';
|
|
159
|
+
/** How long one runner run may take before the plugin kills it and lets the call through. */
|
|
160
|
+
export const OPENCODE_PLUGIN_TIMEOUT_MS = 10_000;
|
|
161
|
+
/** The same bound for `guard-check`, whose worst case is longer (see above). */
|
|
162
|
+
export const OPENCODE_GUARD_TIMEOUT_MS = 30_000;
|
|
163
|
+
/**
|
|
164
|
+
* The plugin source: the marker line, the imports, the constants as
|
|
165
|
+
* `JSON.stringify` literals, what both halves share, each half, then the
|
|
166
|
+
* single default export.
|
|
167
|
+
*/
|
|
168
|
+
export function renderOpenCodePlugin(opts) {
|
|
169
|
+
const timeoutMs = opts.timeoutMs ?? OPENCODE_PLUGIN_TIMEOUT_MS;
|
|
170
|
+
// NaN would render as `null` (a zero-delay timer), so every call would time
|
|
171
|
+
// out and be let through: refuse it here rather than ship a dead guard.
|
|
172
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
173
|
+
throw new RangeError(`timeoutMs must be a positive number of milliseconds, got ${timeoutMs}`);
|
|
174
|
+
}
|
|
175
|
+
return [
|
|
176
|
+
OPENCODE_PLUGIN_MARKER,
|
|
177
|
+
'// CybeDefend VibeDefend for OpenCode: hands every hook to the VibeDefend hook runner.',
|
|
178
|
+
'// Edits to this file are lost on the next vibedefend install or update.',
|
|
179
|
+
"import { spawn } from 'node:child_process';",
|
|
180
|
+
"import { existsSync } from 'node:fs';",
|
|
181
|
+
'',
|
|
182
|
+
`const RUNNER = ${JSON.stringify(opts.runnerPath)};`,
|
|
183
|
+
`const NODE_PATH = ${JSON.stringify(opts.nodePath)};`,
|
|
184
|
+
`const ENABLE_SESSION_REVIEW = ${JSON.stringify(opts.enableSessionReview === true)};`,
|
|
185
|
+
`const TIMEOUT_MS = ${JSON.stringify(Math.ceil(timeoutMs))};`,
|
|
186
|
+
`const GUARD_TIMEOUT_MS = ${JSON.stringify(Math.ceil((timeoutMs * OPENCODE_GUARD_TIMEOUT_MS) / OPENCODE_PLUGIN_TIMEOUT_MS))};`,
|
|
187
|
+
PLUGIN_SHARED,
|
|
188
|
+
PLUGIN_SERVER,
|
|
189
|
+
PLUGIN_SETUP,
|
|
190
|
+
"export default { id: 'cybedefend-vibedefend', server: serverV1, setup: setupV2 };",
|
|
191
|
+
'',
|
|
192
|
+
].join('\n');
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Everything below the constants is a raw string, so the plugin's own escapes
|
|
196
|
+
* (`'\n'`) reach the file as written; none holds a backtick or a `${`. This one
|
|
197
|
+
* is what both halves share.
|
|
198
|
+
*/
|
|
199
|
+
const PLUGIN_SHARED = String.raw `
|
|
200
|
+
// Tool calls whose context waits for their after hook (a failed tool gets none).
|
|
201
|
+
const MAX_PENDING = 200;
|
|
202
|
+
// Sessions remembered (parent, started, error mark).
|
|
203
|
+
const MAX_SESSIONS = 1000;
|
|
204
|
+
// How far up a chain of subagents the walk to the root session goes.
|
|
205
|
+
const MAX_SESSION_DEPTH = 16;
|
|
206
|
+
// Told of a call guard-check could not answer for, which went through.
|
|
207
|
+
const UNVERIFIED =
|
|
208
|
+
'CybeDefend Action Guards could not verify this tool call (no answer in time); it was allowed.';
|
|
209
|
+
// The answers runRunner made up itself (timeout, no process, unreadable).
|
|
210
|
+
const FALLBACKS = new WeakSet();
|
|
211
|
+
const DENY_FALLBACK =
|
|
212
|
+
'Blocked by CybeDefend: this tool call was NOT run. [VibeDefend Action Guards] A guard of this project blocks this action.';
|
|
213
|
+
// A program can make any number of calls at once. Spawned together they choke the
|
|
214
|
+
// machine until each misses its bound, which lets it through. So the others wait,
|
|
215
|
+
// oldest first, and their bound starts when they spawn.
|
|
216
|
+
const MAX_GUARD_RUNS = 8;
|
|
217
|
+
let guardRuns = 0;
|
|
218
|
+
const guardQueue = [];
|
|
219
|
+
|
|
220
|
+
function isObject(value) {
|
|
221
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function idOf(value) {
|
|
225
|
+
return typeof value === 'string' && value.length > 0 ? value : '';
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function contextOf(answer) {
|
|
229
|
+
return isObject(answer) && typeof answer.context === 'string' && answer.context.length > 0
|
|
230
|
+
? answer.context
|
|
231
|
+
: '';
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function isDeny(answer) {
|
|
235
|
+
return isObject(answer) && (answer.decision === 'deny' || answer.decision === 'block');
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function denyReason(answer) {
|
|
239
|
+
return typeof answer.reason === 'string' && answer.reason.length > 0 ? answer.reason : DENY_FALLBACK;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function fallbackFor(sub) {
|
|
243
|
+
return sub === 'guard-check' || sub === 'fetch-rules' ? { decision: 'allow' } : {};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function parseAnswer(line) {
|
|
247
|
+
const text = line.trim();
|
|
248
|
+
if (!text.startsWith('{')) return undefined;
|
|
249
|
+
try {
|
|
250
|
+
const value = JSON.parse(text);
|
|
251
|
+
return isObject(value) ? value : undefined;
|
|
252
|
+
} catch {
|
|
253
|
+
return undefined;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Insert (or refresh) a key, dropping the oldest past the bound.
|
|
258
|
+
function remember(map, key, value, max) {
|
|
259
|
+
map.delete(key);
|
|
260
|
+
map.set(key, value);
|
|
261
|
+
while (map.size > max) map.delete(map.keys().next().value);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function rememberIn(set, key, max) {
|
|
265
|
+
set.delete(key);
|
|
266
|
+
set.add(key);
|
|
267
|
+
while (set.size > max) set.delete(set.values().next().value);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Resolves with 'promise', or with 'fallback' after 'ms'. Never rejects.
|
|
271
|
+
function within(promise, ms, fallback) {
|
|
272
|
+
return new Promise((resolve) => {
|
|
273
|
+
const timer = setTimeout(() => resolve(fallback), ms);
|
|
274
|
+
Promise.resolve(promise).then(
|
|
275
|
+
(value) => {
|
|
276
|
+
clearTimeout(timer);
|
|
277
|
+
resolve(value);
|
|
278
|
+
},
|
|
279
|
+
() => {
|
|
280
|
+
clearTimeout(timer);
|
|
281
|
+
resolve(fallback);
|
|
282
|
+
},
|
|
283
|
+
);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// One run of the hook runner, in 'cwd' when one is given. Resolves with its
|
|
288
|
+
// answer, or with the fallback; never rejects, never writes anywhere but the
|
|
289
|
+
// child's stdin.
|
|
290
|
+
function runRunner(sub, envelope, cwd) {
|
|
291
|
+
if (sub !== 'guard-check') return spawnRunner(sub, envelope, cwd, () => {});
|
|
292
|
+
return new Promise((resolve) => {
|
|
293
|
+
const start = () => {
|
|
294
|
+
guardRuns += 1;
|
|
295
|
+
const gone = () => {
|
|
296
|
+
guardRuns -= 1;
|
|
297
|
+
const next = guardQueue.shift();
|
|
298
|
+
if (next) next();
|
|
299
|
+
};
|
|
300
|
+
spawnRunner(sub, envelope, cwd, gone).then(resolve);
|
|
301
|
+
};
|
|
302
|
+
if (guardRuns < MAX_GUARD_RUNS) start();
|
|
303
|
+
else guardQueue.push(start);
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// 'onGone' is called once, when the child no longer runs: it may outlive its answer.
|
|
308
|
+
function spawnRunner(sub, envelope, cwd, onGone) {
|
|
309
|
+
const fallback = fallbackFor(sub);
|
|
310
|
+
FALLBACKS.add(fallback);
|
|
311
|
+
return new Promise((resolve) => {
|
|
312
|
+
let child;
|
|
313
|
+
let settled = false;
|
|
314
|
+
let exited = false;
|
|
315
|
+
let isGone = false;
|
|
316
|
+
let rest = '';
|
|
317
|
+
const gone = () => {
|
|
318
|
+
if (isGone) return;
|
|
319
|
+
isGone = true;
|
|
320
|
+
onGone();
|
|
321
|
+
};
|
|
322
|
+
const settle = (answer) => {
|
|
323
|
+
if (settled) return;
|
|
324
|
+
settled = true;
|
|
325
|
+
resolve(answer);
|
|
326
|
+
if (exited) clearTimeout(timer);
|
|
327
|
+
};
|
|
328
|
+
const kill = () => {
|
|
329
|
+
try {
|
|
330
|
+
if (child && !exited) child.kill('SIGKILL');
|
|
331
|
+
} catch {}
|
|
332
|
+
};
|
|
333
|
+
// Kills the child at the timeout, answered or not: a runner that hangs
|
|
334
|
+
// on its way out must not outlive it.
|
|
335
|
+
const timer = setTimeout(() => {
|
|
336
|
+
settle(fallback);
|
|
337
|
+
kill();
|
|
338
|
+
gone();
|
|
339
|
+
}, sub === 'guard-check' ? GUARD_TIMEOUT_MS : TIMEOUT_MS);
|
|
340
|
+
const take = (line) => {
|
|
341
|
+
if (settled) return;
|
|
342
|
+
const answer = parseAnswer(line);
|
|
343
|
+
if (answer !== undefined) settle(answer);
|
|
344
|
+
};
|
|
345
|
+
try {
|
|
346
|
+
const node = existsSync(NODE_PATH) ? NODE_PATH : 'node';
|
|
347
|
+
child = spawn(node, [RUNNER, sub, '--client', 'opencode'], {
|
|
348
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
349
|
+
windowsHide: true,
|
|
350
|
+
...(cwd ? { cwd } : {}),
|
|
351
|
+
});
|
|
352
|
+
} catch {
|
|
353
|
+
clearTimeout(timer);
|
|
354
|
+
settle(fallback);
|
|
355
|
+
gone();
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
child.on('error', () => {
|
|
359
|
+
// No process (ENOENT, EACCES...), or a kill that failed.
|
|
360
|
+
if (child.pid === undefined) {
|
|
361
|
+
exited = true;
|
|
362
|
+
clearTimeout(timer);
|
|
363
|
+
gone();
|
|
364
|
+
}
|
|
365
|
+
settle(fallback);
|
|
366
|
+
});
|
|
367
|
+
child.on('exit', () => {
|
|
368
|
+
exited = true;
|
|
369
|
+
if (settled) clearTimeout(timer);
|
|
370
|
+
gone();
|
|
371
|
+
});
|
|
372
|
+
child.on('close', () => {
|
|
373
|
+
exited = true;
|
|
374
|
+
take(rest);
|
|
375
|
+
rest = '';
|
|
376
|
+
clearTimeout(timer);
|
|
377
|
+
settle(fallback);
|
|
378
|
+
});
|
|
379
|
+
if (child.stdin) child.stdin.on('error', () => {});
|
|
380
|
+
if (child.stdout) {
|
|
381
|
+
child.stdout.on('error', () => {});
|
|
382
|
+
child.stdout.setEncoding('utf8');
|
|
383
|
+
child.stdout.on('data', (chunk) => {
|
|
384
|
+
if (settled) return;
|
|
385
|
+
const lines = (rest + chunk).split('\n');
|
|
386
|
+
rest = lines.pop();
|
|
387
|
+
for (const line of lines) {
|
|
388
|
+
take(line);
|
|
389
|
+
if (settled) return;
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
try {
|
|
394
|
+
child.stdin.end(JSON.stringify(envelope));
|
|
395
|
+
} catch {
|
|
396
|
+
settle(fallback);
|
|
397
|
+
kill();
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// Who is whose parent, from what the events said, else from one read per session,
|
|
403
|
+
// cached; a failed read counts as a root session. 'readParentID' resolves with
|
|
404
|
+
// the parent's id, or with anything else for none.
|
|
405
|
+
function sessionTree(readParentID) {
|
|
406
|
+
// sessionID -> parent id (string), null for a root session, or the pending read.
|
|
407
|
+
const parents = new Map();
|
|
408
|
+
|
|
409
|
+
const readParent = async (sessionID) => {
|
|
410
|
+
try {
|
|
411
|
+
return idOf(await readParentID(sessionID)) || null;
|
|
412
|
+
} catch {
|
|
413
|
+
return null;
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
// The session's parent id, or null for a root session.
|
|
418
|
+
const parentOf = async (sessionID) => {
|
|
419
|
+
if (parents.has(sessionID)) return parents.get(sessionID);
|
|
420
|
+
const read = readParent(sessionID);
|
|
421
|
+
remember(parents, sessionID, read, MAX_SESSIONS);
|
|
422
|
+
const parentID = await read;
|
|
423
|
+
if (parents.get(sessionID) === read) parents.set(sessionID, parentID);
|
|
424
|
+
return parentID;
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
// The session at the top of the parent chain: the session itself for a
|
|
428
|
+
// root session, or when a parent cannot be read; a cycle ends the walk.
|
|
429
|
+
const rootOf = async (sessionID) => {
|
|
430
|
+
let id = sessionID;
|
|
431
|
+
const seen = new Set([id]);
|
|
432
|
+
for (let depth = 0; depth < MAX_SESSION_DEPTH; depth++) {
|
|
433
|
+
const parentID = await parentOf(id);
|
|
434
|
+
if (!parentID || seen.has(parentID)) return id;
|
|
435
|
+
seen.add(parentID);
|
|
436
|
+
id = parentID;
|
|
437
|
+
}
|
|
438
|
+
return id;
|
|
439
|
+
};
|
|
440
|
+
|
|
441
|
+
return {
|
|
442
|
+
parentOf,
|
|
443
|
+
rootOf,
|
|
444
|
+
setParent: (sessionID, parentID) => remember(parents, sessionID, parentID, MAX_SESSIONS),
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// The plugin's envelope; async because it names the root session.
|
|
449
|
+
function envelopeMaker(opencode, directory, worktree, rootOf, serverNames) {
|
|
450
|
+
return async (hook, sessionID, call) => ({
|
|
451
|
+
opencode,
|
|
452
|
+
hook,
|
|
453
|
+
sessionID,
|
|
454
|
+
...(sessionID ? { rootSessionID: await rootOf(sessionID) } : {}),
|
|
455
|
+
...(call || {}),
|
|
456
|
+
directory,
|
|
457
|
+
worktree,
|
|
458
|
+
mcpServers: await serverNames(),
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
`;
|
|
462
|
+
/** The V1 factory, `default.server`. */
|
|
463
|
+
const PLUGIN_SERVER = String.raw `
|
|
464
|
+
// The tools that write a file or run a command: the ones rules are fetched for.
|
|
465
|
+
const RULE_TOOLS = new Set(['write', 'edit', 'apply_patch', 'bash']);
|
|
466
|
+
const BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
|
467
|
+
|
|
468
|
+
// A part id as OpenCode makes one (Identifier.ascending('part')): 'prt_',
|
|
469
|
+
// 12 hex digits of Date.now() * 0x1000 + counter, 14 base-62 characters.
|
|
470
|
+
let lastMs = 0;
|
|
471
|
+
let counter = 0;
|
|
472
|
+
function partId() {
|
|
473
|
+
const ms = Date.now();
|
|
474
|
+
if (ms !== lastMs) {
|
|
475
|
+
lastMs = ms;
|
|
476
|
+
counter = 0;
|
|
477
|
+
}
|
|
478
|
+
counter += 1;
|
|
479
|
+
const now = BigInt(ms) * BigInt(0x1000) + BigInt(counter);
|
|
480
|
+
let hex = '';
|
|
481
|
+
for (let i = 0; i < 6; i++) {
|
|
482
|
+
hex += Number((now >> BigInt(40 - 8 * i)) & BigInt(0xff)).toString(16).padStart(2, '0');
|
|
483
|
+
}
|
|
484
|
+
let tail = '';
|
|
485
|
+
for (let i = 0; i < 14; i++) tail += BASE62[Math.floor(Math.random() * 62)];
|
|
486
|
+
return 'prt_' + hex + tail;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
async function serverV1({ client, directory, worktree }) {
|
|
490
|
+
let mcpServers = [];
|
|
491
|
+
// callID -> { rules?: Promise<answer>, guard?: string, unverified?: true }
|
|
492
|
+
const pending = new Map();
|
|
493
|
+
const started = new Set();
|
|
494
|
+
const errored = new Set();
|
|
495
|
+
const reviewing = new Set();
|
|
496
|
+
// sessionID -> the agent of its last chat.message.
|
|
497
|
+
const agents = new Map();
|
|
498
|
+
|
|
499
|
+
const { parentOf, rootOf, setParent } = sessionTree(async (sessionID) => {
|
|
500
|
+
const res = await within(client.session.get({ path: { id: sessionID } }), TIMEOUT_MS, undefined);
|
|
501
|
+
return isObject(res) && isObject(res.data) ? res.data.parentID : undefined;
|
|
502
|
+
});
|
|
503
|
+
const envelope = envelopeMaker(1, directory, worktree, rootOf, () => mcpServers.slice());
|
|
504
|
+
|
|
505
|
+
const keep = (callID, entry) => remember(pending, callID, entry, MAX_PENDING);
|
|
506
|
+
|
|
507
|
+
const review = async (sessionID) => {
|
|
508
|
+
if (!ENABLE_SESSION_REVIEW || !sessionID) return;
|
|
509
|
+
if (errored.has(sessionID) || reviewing.has(sessionID)) return;
|
|
510
|
+
reviewing.add(sessionID);
|
|
511
|
+
try {
|
|
512
|
+
if ((await parentOf(sessionID)) !== null) return;
|
|
513
|
+
const text = contextOf(
|
|
514
|
+
await runRunner('session-review', await envelope('session.idle', sessionID)),
|
|
515
|
+
);
|
|
516
|
+
if (!text) return;
|
|
517
|
+
// The review prompt fires chat.message too: it is no session start.
|
|
518
|
+
rememberIn(started, sessionID, MAX_SESSIONS);
|
|
519
|
+
const agent = agents.get(sessionID);
|
|
520
|
+
await client.session.promptAsync({
|
|
521
|
+
path: { id: sessionID },
|
|
522
|
+
body: { ...(agent ? { agent } : {}), parts: [{ type: 'text', text }] },
|
|
523
|
+
});
|
|
524
|
+
} catch {
|
|
525
|
+
// An error of the client is not ours to report.
|
|
526
|
+
} finally {
|
|
527
|
+
reviewing.delete(sessionID);
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
return {
|
|
532
|
+
config: async (cfg) => {
|
|
533
|
+
try {
|
|
534
|
+
mcpServers = isObject(cfg) && isObject(cfg.mcp) ? Object.keys(cfg.mcp) : [];
|
|
535
|
+
} catch {
|
|
536
|
+
mcpServers = [];
|
|
537
|
+
}
|
|
538
|
+
},
|
|
539
|
+
|
|
540
|
+
'tool.execute.before': async (input, output) => {
|
|
541
|
+
let reason;
|
|
542
|
+
try {
|
|
543
|
+
const tool = isObject(input) && typeof input.tool === 'string' ? input.tool : '';
|
|
544
|
+
const callID = isObject(input) ? idOf(input.callID) : '';
|
|
545
|
+
const call = {
|
|
546
|
+
...(callID ? { callID } : {}),
|
|
547
|
+
tool,
|
|
548
|
+
args: isObject(output) ? output.args : undefined,
|
|
549
|
+
};
|
|
550
|
+
const sent = await envelope('tool.before', isObject(input) ? idOf(input.sessionID) : '', call);
|
|
551
|
+
let entry;
|
|
552
|
+
if (RULE_TOOLS.has(tool)) {
|
|
553
|
+
entry = { rules: runRunner('fetch-rules', sent) };
|
|
554
|
+
if (callID) keep(callID, entry);
|
|
555
|
+
}
|
|
556
|
+
const answer = await runRunner('guard-check', sent);
|
|
557
|
+
if (isDeny(answer)) {
|
|
558
|
+
if (callID) pending.delete(callID);
|
|
559
|
+
reason = denyReason(answer);
|
|
560
|
+
} else {
|
|
561
|
+
const text = contextOf(answer);
|
|
562
|
+
const unverified = FALLBACKS.has(answer);
|
|
563
|
+
if ((text || unverified) && callID) {
|
|
564
|
+
entry = entry || {};
|
|
565
|
+
if (text) entry.guard = text;
|
|
566
|
+
if (unverified) entry.unverified = true;
|
|
567
|
+
keep(callID, entry);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
} catch {
|
|
571
|
+
// A fault of the plugin lets the call through.
|
|
572
|
+
}
|
|
573
|
+
if (reason !== undefined) throw new Error(reason);
|
|
574
|
+
},
|
|
575
|
+
|
|
576
|
+
'tool.execute.after': async (input, output) => {
|
|
577
|
+
try {
|
|
578
|
+
const callID = isObject(input) ? idOf(input.callID) : '';
|
|
579
|
+
const entry = callID ? pending.get(callID) : undefined;
|
|
580
|
+
if (!entry) return;
|
|
581
|
+
pending.delete(callID);
|
|
582
|
+
const texts = [];
|
|
583
|
+
if (entry.unverified) texts.push(UNVERIFIED);
|
|
584
|
+
if (entry.guard) texts.push(entry.guard);
|
|
585
|
+
if (entry.rules) {
|
|
586
|
+
const rules = contextOf(await entry.rules);
|
|
587
|
+
if (rules) texts.push(rules);
|
|
588
|
+
}
|
|
589
|
+
if (texts.length === 0 || !isObject(output)) return;
|
|
590
|
+
const text = texts.join('\n\n');
|
|
591
|
+
if (typeof output.output === 'string') output.output += '\n\n' + text;
|
|
592
|
+
else if (Array.isArray(output.content)) output.content.push({ type: 'text', text });
|
|
593
|
+
} catch {}
|
|
594
|
+
},
|
|
595
|
+
|
|
596
|
+
'chat.message': async (input, output) => {
|
|
597
|
+
try {
|
|
598
|
+
const sessionID = isObject(input) ? idOf(input.sessionID) : '';
|
|
599
|
+
if (!sessionID) return;
|
|
600
|
+
errored.delete(sessionID);
|
|
601
|
+
const agent = idOf(input.agent);
|
|
602
|
+
if (agent) remember(agents, sessionID, agent, MAX_SESSIONS);
|
|
603
|
+
if (started.has(sessionID)) return;
|
|
604
|
+
rememberIn(started, sessionID, MAX_SESSIONS);
|
|
605
|
+
if ((await parentOf(sessionID)) !== null) return;
|
|
606
|
+
const text = contextOf(
|
|
607
|
+
await runRunner('session-start', await envelope('chat.message', sessionID)),
|
|
608
|
+
);
|
|
609
|
+
if (!text || !isObject(output) || !Array.isArray(output.parts)) return;
|
|
610
|
+
const messageID = isObject(output.message) ? idOf(output.message.id) : '';
|
|
611
|
+
if (!messageID) return;
|
|
612
|
+
output.parts.push({ id: partId(), sessionID, messageID, type: 'text', text, synthetic: true });
|
|
613
|
+
} catch {}
|
|
614
|
+
},
|
|
615
|
+
|
|
616
|
+
// OpenCode does not wait for this hook (and drops what it returns): it
|
|
617
|
+
// must never reject.
|
|
618
|
+
event: async (input) => {
|
|
619
|
+
try {
|
|
620
|
+
const event = isObject(input) ? input.event : undefined;
|
|
621
|
+
if (!isObject(event)) return;
|
|
622
|
+
const props = isObject(event.properties) ? event.properties : {};
|
|
623
|
+
if (event.type === 'session.created') {
|
|
624
|
+
const info = isObject(props.info) ? props.info : {};
|
|
625
|
+
const id = idOf(info.id) || idOf(props.sessionID);
|
|
626
|
+
if (id) setParent(id, idOf(info.parentID) || null);
|
|
627
|
+
} else if (event.type === 'session.error') {
|
|
628
|
+
const id = idOf(props.sessionID);
|
|
629
|
+
if (id) rememberIn(errored, id, MAX_SESSIONS);
|
|
630
|
+
} else if (event.type === 'session.idle') {
|
|
631
|
+
await review(idOf(props.sessionID));
|
|
632
|
+
}
|
|
633
|
+
} catch {}
|
|
634
|
+
},
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
`;
|
|
638
|
+
/** The V2 setup, `default.setup`. */
|
|
639
|
+
const PLUGIN_SETUP = String.raw `
|
|
640
|
+
// V2's names for the tools rules are fetched for.
|
|
641
|
+
const RULE_TOOLS_V2 = new Set(['write', 'edit', 'patch', 'shell']);
|
|
642
|
+
// Code Mode's tool: the calls of its program run under its id.
|
|
643
|
+
const CODE_MODE_TOOL = 'execute';
|
|
644
|
+
// A program makes any number of inner calls: what is said of them stays readable.
|
|
645
|
+
const MAX_CALL_WARNS = 20;
|
|
646
|
+
// The session start's key in a session's instructions.
|
|
647
|
+
const INSTRUCTIONS_KEY = 'cybedefend';
|
|
648
|
+
const SESSION_EVENTS = ['session.created', 'session.execution.succeeded'];
|
|
649
|
+
// What the review's prompt carries, as a goal's carries its own.
|
|
650
|
+
const REVIEW_METADATA = { source: 'cybedefend-review' };
|
|
651
|
+
// What 'within' answers for a call that failed or did not answer in time.
|
|
652
|
+
const NO_ANSWER = {};
|
|
653
|
+
|
|
654
|
+
// What the guard needs, which V1's own call to setup does not hand over. A host
|
|
655
|
+
// that renames anything else loses that feature alone, never the guard.
|
|
656
|
+
function isV2Context(ctx) {
|
|
657
|
+
try {
|
|
658
|
+
return isObject(ctx) && typeof ctx.tool?.hook === 'function' && idOf(ctx.location?.directory) !== '';
|
|
659
|
+
} catch {
|
|
660
|
+
return false;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// Whether 'read' finds a function. What is absent, or throws when read, is not there.
|
|
665
|
+
function isThere(read) {
|
|
666
|
+
try {
|
|
667
|
+
return typeof read() === 'function';
|
|
668
|
+
} catch {
|
|
669
|
+
return false;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// A stringified input as its object, or {}: the raw string goes nowhere.
|
|
674
|
+
function argsOf(input) {
|
|
675
|
+
if (typeof input !== 'string') return input;
|
|
676
|
+
try {
|
|
677
|
+
const parsed = JSON.parse(input);
|
|
678
|
+
return isObject(parsed) ? parsed : {};
|
|
679
|
+
} catch {
|
|
680
|
+
return {};
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// The note in front of what the model reads of a result.
|
|
685
|
+
function prependNote(result, note) {
|
|
686
|
+
const content = result.content;
|
|
687
|
+
if (typeof content === 'string') {
|
|
688
|
+
result.content = note + '\n\n' + content;
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
const items = Array.isArray(content) ? content : [];
|
|
692
|
+
const first = items[0];
|
|
693
|
+
result.content =
|
|
694
|
+
isObject(first) && first.type === 'text' && typeof first.text === 'string'
|
|
695
|
+
? [{ ...first, text: note + '\n\n' + first.text }, ...items.slice(1)]
|
|
696
|
+
: [{ type: 'text', text: note }, ...items];
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
async function setupV2(ctx) {
|
|
700
|
+
if (!isV2Context(ctx)) return undefined;
|
|
701
|
+
|
|
702
|
+
const directory = ctx.location.directory;
|
|
703
|
+
const worktree = idOf(ctx.location.project?.directory) || directory;
|
|
704
|
+
const run = (sub, sent) => runRunner(sub, sent, directory);
|
|
705
|
+
const canStartSessions = isThere(() => ctx.session.hook);
|
|
706
|
+
const canReview = isThere(() => ctx.session.get) && isThere(() => ctx.session.prompt);
|
|
707
|
+
const canListServers = isThere(() => ctx.mcp.list);
|
|
708
|
+
const controller = new AbortController();
|
|
709
|
+
let stopped = false;
|
|
710
|
+
let mcpServers = [];
|
|
711
|
+
// callID -> { unverified: boolean, warns: string[], rules: Promise<answer>[] }
|
|
712
|
+
const pending = new Map();
|
|
713
|
+
// The ids whose execute before-hook fired: their other calls are a program's.
|
|
714
|
+
const programs = new Set();
|
|
715
|
+
const started = new Set();
|
|
716
|
+
const reviewing = new Set();
|
|
717
|
+
// sessionID -> the session start its instructions could not take.
|
|
718
|
+
const contextOnly = new Map();
|
|
719
|
+
|
|
720
|
+
const { parentOf, rootOf, setParent } = sessionTree(async (sessionID) => {
|
|
721
|
+
const res = await within(ctx.session.get({ sessionID }), TIMEOUT_MS, undefined);
|
|
722
|
+
return isObject(res) ? res.parentID : undefined;
|
|
723
|
+
});
|
|
724
|
+
|
|
725
|
+
const serverNames = async () => {
|
|
726
|
+
if (!canListServers) return [];
|
|
727
|
+
try {
|
|
728
|
+
const res = await within(ctx.mcp.list(), TIMEOUT_MS, undefined);
|
|
729
|
+
if (isObject(res) && Array.isArray(res.data)) {
|
|
730
|
+
mcpServers = res.data.map((server) => (isObject(server) ? idOf(server.name) : '')).filter(Boolean);
|
|
731
|
+
}
|
|
732
|
+
} catch {
|
|
733
|
+
// The last names read stay.
|
|
734
|
+
}
|
|
735
|
+
return mcpServers.slice();
|
|
736
|
+
};
|
|
737
|
+
const envelope = envelopeMaker(2, directory, worktree, rootOf, serverNames);
|
|
738
|
+
|
|
739
|
+
const remind = (callID, unverified, warn, rules) => {
|
|
740
|
+
const entry = pending.get(callID) || { unverified: false, warns: [], rules: [] };
|
|
741
|
+
if (unverified) entry.unverified = true;
|
|
742
|
+
if (warn && !entry.warns.includes(warn) && entry.warns.length < MAX_CALL_WARNS) entry.warns.push(warn);
|
|
743
|
+
if (rules) entry.rules.push(rules);
|
|
744
|
+
remember(pending, callID, entry, MAX_PENDING);
|
|
745
|
+
};
|
|
746
|
+
|
|
747
|
+
const beforeTool = async (ev) => {
|
|
748
|
+
let reason;
|
|
749
|
+
try {
|
|
750
|
+
const tool = typeof ev.tool === 'string' ? ev.tool : '';
|
|
751
|
+
const callID = idOf(ev.id);
|
|
752
|
+
const outer = tool === CODE_MODE_TOOL;
|
|
753
|
+
if (outer && callID) rememberIn(programs, callID, MAX_PENDING);
|
|
754
|
+
const inner = !outer && programs.has(callID);
|
|
755
|
+
const sent = await envelope('tool.before', idOf(ev.sessionID), {
|
|
756
|
+
...(callID ? { callID } : {}),
|
|
757
|
+
tool,
|
|
758
|
+
args: argsOf(ev.input),
|
|
759
|
+
});
|
|
760
|
+
const rules = RULE_TOOLS_V2.has(tool) ? run('fetch-rules', sent) : undefined;
|
|
761
|
+
const answer = await run('guard-check', sent);
|
|
762
|
+
if (isDeny(answer)) {
|
|
763
|
+
// An inner call's deny fails that call: its program goes on, with what it gathered.
|
|
764
|
+
if (!inner) {
|
|
765
|
+
pending.delete(callID);
|
|
766
|
+
programs.delete(callID);
|
|
767
|
+
}
|
|
768
|
+
reason = denyReason(answer);
|
|
769
|
+
} else if (callID) {
|
|
770
|
+
const warn = contextOf(answer);
|
|
771
|
+
const unverified = FALLBACKS.has(answer);
|
|
772
|
+
if (warn || unverified || rules) remind(callID, unverified, warn, rules);
|
|
773
|
+
}
|
|
774
|
+
} catch {
|
|
775
|
+
// A fault of the plugin lets the call through.
|
|
776
|
+
}
|
|
777
|
+
if (reason !== undefined) throw new Error(reason);
|
|
778
|
+
};
|
|
779
|
+
|
|
780
|
+
const afterTool = async (ev) => {
|
|
781
|
+
try {
|
|
782
|
+
const callID = idOf(ev.id);
|
|
783
|
+
// An inner call's result never reaches the model: its program's does.
|
|
784
|
+
if (!callID || (ev.tool !== CODE_MODE_TOOL && programs.has(callID))) return;
|
|
785
|
+
programs.delete(callID);
|
|
786
|
+
const entry = pending.get(callID);
|
|
787
|
+
if (!entry) return;
|
|
788
|
+
pending.delete(callID);
|
|
789
|
+
if (ev.status !== 'completed') return;
|
|
790
|
+
const texts = entry.unverified ? [UNVERIFIED] : [];
|
|
791
|
+
texts.push(...entry.warns);
|
|
792
|
+
for (const rules of await Promise.all(entry.rules)) {
|
|
793
|
+
const text = contextOf(rules);
|
|
794
|
+
if (text) texts.push(text);
|
|
795
|
+
}
|
|
796
|
+
if (texts.length > 0) prependNote(ev.result, texts.join('\n\n'));
|
|
797
|
+
} catch {}
|
|
798
|
+
};
|
|
799
|
+
|
|
800
|
+
// Hidden instructions when the session takes them (absent, the call throws
|
|
801
|
+
// here like a refusal), else the context hook's text.
|
|
802
|
+
const startSession = async (sessionID, text) => {
|
|
803
|
+
const put = Promise.resolve().then(() =>
|
|
804
|
+
ctx.session.instructions.entry.put({ sessionID, key: INSTRUCTIONS_KEY, value: text }),
|
|
805
|
+
);
|
|
806
|
+
const answer = await within(put, TIMEOUT_MS, NO_ANSWER);
|
|
807
|
+
if (answer === NO_ANSWER) remember(contextOnly, sessionID, text, MAX_SESSIONS);
|
|
808
|
+
};
|
|
809
|
+
|
|
810
|
+
const onPrompt = async (ev) => {
|
|
811
|
+
try {
|
|
812
|
+
const sessionID = idOf(ev.sessionID);
|
|
813
|
+
if (!sessionID) return;
|
|
814
|
+
// The review's prompt fires this hook too: it is no user's message.
|
|
815
|
+
if (ev.metadata?.source === REVIEW_METADATA.source) return;
|
|
816
|
+
if (started.has(sessionID)) return;
|
|
817
|
+
rememberIn(started, sessionID, MAX_SESSIONS);
|
|
818
|
+
if ((await parentOf(sessionID)) !== null) return;
|
|
819
|
+
const text = contextOf(await run('session-start', await envelope('chat.message', sessionID)));
|
|
820
|
+
if (text) await startSession(sessionID, text);
|
|
821
|
+
} catch {}
|
|
822
|
+
};
|
|
823
|
+
|
|
824
|
+
const onContext = (ev) => {
|
|
825
|
+
try {
|
|
826
|
+
const text = contextOnly.get(idOf(ev.sessionID));
|
|
827
|
+
if (text && Array.isArray(ev.system)) ev.system.push({ type: 'text', text });
|
|
828
|
+
} catch {}
|
|
829
|
+
};
|
|
830
|
+
|
|
831
|
+
// Whether this setup may review the session, read from the server just now.
|
|
832
|
+
const isReviewableHere = async (sessionID) => {
|
|
833
|
+
const session = await within(ctx.session.get({ sessionID }), TIMEOUT_MS, undefined);
|
|
834
|
+
return (
|
|
835
|
+
isObject(session) &&
|
|
836
|
+
isObject(session.location) &&
|
|
837
|
+
session.location.directory === directory &&
|
|
838
|
+
session.outcome !== 'failed'
|
|
839
|
+
);
|
|
840
|
+
};
|
|
841
|
+
|
|
842
|
+
const review = async (sessionID) => {
|
|
843
|
+
if (!ENABLE_SESSION_REVIEW || !canReview) return;
|
|
844
|
+
if (reviewing.has(sessionID)) return;
|
|
845
|
+
reviewing.add(sessionID);
|
|
846
|
+
try {
|
|
847
|
+
if ((await parentOf(sessionID)) !== null) return;
|
|
848
|
+
if (!(await isReviewableHere(sessionID))) return;
|
|
849
|
+
const text = contextOf(await run('session-review', await envelope('session.idle', sessionID)));
|
|
850
|
+
if (!text || stopped) return;
|
|
851
|
+
// The run takes seconds: the session may have moved or failed, or this setup ended.
|
|
852
|
+
if (!(await isReviewableHere(sessionID)) || stopped) return;
|
|
853
|
+
await ctx.session.prompt({ sessionID, text, metadata: REVIEW_METADATA });
|
|
854
|
+
} catch {
|
|
855
|
+
// An error of the host is not ours to report.
|
|
856
|
+
} finally {
|
|
857
|
+
reviewing.delete(sessionID);
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
|
|
861
|
+
const onEvent = (event) => {
|
|
862
|
+
try {
|
|
863
|
+
const data = isObject(event) && isObject(event.data) ? event.data : {};
|
|
864
|
+
const sessionID = idOf(data.sessionID);
|
|
865
|
+
if (!sessionID) return;
|
|
866
|
+
if (event.type === 'session.created') setParent(sessionID, idOf(data.parentID) || null);
|
|
867
|
+
else if (event.type === 'session.execution.succeeded') review(sessionID);
|
|
868
|
+
} catch {}
|
|
869
|
+
};
|
|
870
|
+
|
|
871
|
+
const listen = async () => {
|
|
872
|
+
try {
|
|
873
|
+
const events = ctx.event.subscribe({ types: SESSION_EVENTS, signal: controller.signal });
|
|
874
|
+
for await (const event of events) {
|
|
875
|
+
if (stopped) return;
|
|
876
|
+
onEvent(event);
|
|
877
|
+
}
|
|
878
|
+
} catch {
|
|
879
|
+
// The other hooks go on without a review.
|
|
880
|
+
}
|
|
881
|
+
};
|
|
882
|
+
|
|
883
|
+
const register = async (domain, name, callback) => {
|
|
884
|
+
try {
|
|
885
|
+
await domain.hook(name, callback);
|
|
886
|
+
} catch {}
|
|
887
|
+
};
|
|
888
|
+
// Not wrapped: a rejected setup shows as a failed plugin, where a guard that did
|
|
889
|
+
// not register would just be silently off.
|
|
890
|
+
await ctx.tool.hook('execute.before', beforeTool);
|
|
891
|
+
await register(ctx.tool, 'execute.after', afterTool);
|
|
892
|
+
if (canStartSessions) {
|
|
893
|
+
await register(ctx.session, 'prompt', onPrompt);
|
|
894
|
+
await register(ctx.session, 'context', onContext);
|
|
895
|
+
}
|
|
896
|
+
// Not awaited: setup must be fast, and the stream only ends with the cleanup.
|
|
897
|
+
if (isThere(() => ctx.event.subscribe)) listen();
|
|
898
|
+
|
|
899
|
+
return () => {
|
|
900
|
+
stopped = true;
|
|
901
|
+
controller.abort();
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
`;
|
|
905
|
+
//# sourceMappingURL=opencode-plugin.js.map
|