pantheon-opencode 1.7.0 → 2.0.0-beta.2

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.
Files changed (173) hide show
  1. package/AGENTS.global.md +2 -2
  2. package/AGENTS.md +3 -3
  3. package/CHANGELOG.md +85 -59
  4. package/README.md +74 -48
  5. package/README.pt-BR.md +19 -19
  6. package/bin/pantheon-init.mjs +11 -48
  7. package/package.json +9 -13
  8. package/plugin.json +2 -2
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +7 -6
  11. package/scripts/{check-plugin-v2-coverage.mjs → check-plugin-coverage.mjs} +7 -7
  12. package/scripts/{decision-router-v2-budget.mjs → decision-router-budget-gates.mjs} +1 -1
  13. package/scripts/{decision-router-v2-egress.mjs → decision-router-egress.mjs} +1 -1
  14. package/scripts/decision-router.mjs +2 -2
  15. package/scripts/docs-media.mjs +1 -1
  16. package/scripts/doctor.mjs +225 -136
  17. package/scripts/install/behavior-overrides.bundle.mjs +123 -0
  18. package/scripts/install/{v2-capabilities.mjs → capabilities.mjs} +7 -7
  19. package/scripts/install/config-migration.mjs +60 -253
  20. package/scripts/install/file-inventory.mjs +6 -4
  21. package/scripts/install/interactive.mjs +1 -1
  22. package/scripts/install/opencode-state.mjs +13 -12
  23. package/scripts/install/opencode-version.mjs +97 -162
  24. package/scripts/install/opencode.mjs +271 -428
  25. package/scripts/install/plan.mjs +1 -9
  26. package/scripts/install/plugin.mjs +19 -35
  27. package/scripts/install/shared.mjs +40 -1
  28. package/scripts/package-evidence.mjs +1 -4
  29. package/scripts/probe-pantheon-cost.mjs +1 -1
  30. package/scripts/reconcile.mjs +5 -7
  31. package/scripts/release-gates.mjs +22 -61
  32. package/scripts/setup-v2-config.mjs +10 -8
  33. package/scripts/setup.mjs +12 -22
  34. package/scripts/sync-tui.mjs +9 -17
  35. package/scripts/{test-opencode-v2-sandbox.sh → test-opencode-sandbox.sh} +9 -9
  36. package/scripts/update-skills-lock.mjs +24 -12
  37. package/scripts/update.mjs +17 -1
  38. package/scripts/validate-routing.mjs +79 -4
  39. package/scripts/validate-sandbox-install.mjs +3 -3
  40. package/skills-lock.json +25 -8
  41. package/src/agents/zeus.md +1 -0
  42. package/src/pantheon/behavior-overrides.ts +191 -0
  43. package/src/pantheon/{v2-bounded-read.ts → bounded-read.ts} +1 -1
  44. package/src/pantheon/cost-command.ts +1 -1
  45. package/src/pantheon/{v2-decision-contracts.ts → decision-contracts.ts} +3 -3
  46. package/src/pantheon/{v2-decision-points → decision-points}/p1-agent.ts +3 -3
  47. package/src/pantheon/{v2-decision-points → decision-points}/p10-claims.ts +2 -2
  48. package/src/pantheon/{v2-decision-points → decision-points}/p11-catalog.ts +2 -2
  49. package/src/pantheon/{v2-decision-points → decision-points}/p2-skill.ts +3 -3
  50. package/src/pantheon/{v2-decision-points → decision-points}/p3-complexity.ts +6 -6
  51. package/src/pantheon/{v2-decision-points → decision-points}/p4-memory.ts +2 -2
  52. package/src/pantheon/{v2-decision-points → decision-points}/p5-themis-verify.ts +2 -2
  53. package/src/pantheon/{v2-decision-points → decision-points}/p6-council.ts +3 -3
  54. package/src/pantheon/{v2-decision-points → decision-points}/p7-loop.ts +5 -5
  55. package/src/pantheon/{v2-decision-points → decision-points}/p8-guardrail.ts +2 -2
  56. package/src/pantheon/{v2-decision-points → decision-points}/p9-memory-compaction.ts +2 -2
  57. package/src/pantheon/{v2-decision-points.ts → decision-points.ts} +5 -5
  58. package/src/pantheon/{v2-decision-policy.ts → decision-policy.ts} +2 -2
  59. package/src/pantheon/{v2-decision-prompt-surface.ts → decision-prompt-surface.ts} +3 -3
  60. package/src/pantheon/{v2-decision-registry.ts → decision-registry.ts} +10 -13
  61. package/src/pantheon/{v2-decision-resource-ids.ts → decision-resource-ids.ts} +1 -1
  62. package/src/pantheon/{v2-decision-shadow.ts → decision-shadow.ts} +1 -1
  63. package/src/pantheon/{v2-decision-telemetry.ts → decision-telemetry.ts} +1 -1
  64. package/src/pantheon/{v2-execute-after.ts → execute-after.ts} +4 -4
  65. package/src/pantheon/goal-store.ts +7 -0
  66. package/src/pantheon/{v2-hook-engine.ts → hook-engine.ts} +3 -3
  67. package/src/pantheon/jev-decision-tool.ts +3 -3
  68. package/src/pantheon/jev-decisions.ts +12 -6
  69. package/src/pantheon/jev-escalation.ts +6 -6
  70. package/src/pantheon/jev-quality-score.ts +2 -2
  71. package/src/pantheon/jev-rank-verify.ts +2 -2
  72. package/src/pantheon/jev-risk-gate.ts +4 -4
  73. package/src/pantheon/local-decision-agents.ts +1 -1
  74. package/src/pantheon/local-decision-router.ts +1 -1
  75. package/src/pantheon/local-decision-tool.ts +2 -2
  76. package/src/pantheon/local-orchestration.ts +1 -1
  77. package/src/pantheon/model-command.ts +1 -1
  78. package/src/pantheon/{v2-vision.ts → native-vision.ts} +12 -15
  79. package/src/pantheon/pantheon-decision-catalog.ts +12 -0
  80. package/src/pantheon/{v2-shell-hooks.ts → shell-hooks.ts} +4 -4
  81. package/src/pantheon/{v2-tools.ts → tools.ts} +4 -4
  82. package/src/pantheon/{v2-unsupported.d.mts → unsupported.d.mts} +3 -3
  83. package/src/pantheon/{v2-unsupported.mjs → unsupported.mjs} +8 -8
  84. package/src/pantheon/update-notifier.ts +101 -0
  85. package/src/pantheon/vision-local.ts +12 -3
  86. package/src/pantheon/vision.ts +120 -2
  87. package/src/{plugin-v2 → plugin}/index.ts +7 -7
  88. package/src/plugin.ts +2870 -500
  89. package/src/plugins/hook-runner.ts +3 -3
  90. package/src/plugins/tui/dist/server.d.ts +23 -9
  91. package/src/plugins/tui/dist/server.d.ts.map +1 -1
  92. package/src/plugins/tui/dist/server.js +25 -12
  93. package/src/plugins/tui/dist/server.js.map +1 -1
  94. package/src/plugins/tui/dist/tui.d.ts +1023 -494
  95. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  96. package/src/plugins/tui/dist/tui.js +5612 -2086
  97. package/src/plugins/tui/dist/tui.js.map +1 -1
  98. package/src/plugins/tui/{index-v2.ts → index.ts} +1 -1
  99. package/src/plugins/tui/package-lock.json +2 -42
  100. package/src/plugins/tui/package.json +4 -10
  101. package/src/plugins/tui/src/cost-data.ts +1 -1
  102. package/src/plugins/tui/src/decision-router-state.ts +242 -0
  103. package/src/plugins/tui/src/doctor-state.ts +198 -0
  104. package/src/plugins/tui/src/index.tsx +4222 -2822
  105. package/src/plugins/tui/src/j1-gate-status.ts +85 -0
  106. package/src/plugins/tui/src/pantheon-settings-state.ts +245 -0
  107. package/src/plugins/tui/src/pantheon-settings.tsx +442 -0
  108. package/src/plugins/tui/src/preset-state.ts +143 -0
  109. package/src/plugins/tui/src/server.ts +23 -10
  110. package/src/plugins/tui/src/update-notice.ts +90 -0
  111. package/src/plugins/tui/src/update-status.ts +98 -0
  112. package/src/plugins/tui/tsconfig.typecheck.json +9 -2
  113. package/src/plugins/tui/tsdown.config.ts +3 -5
  114. package/src/plugins/tui/tui.ts +1 -2
  115. package/src/routing.yml +36 -0
  116. package/src/skills/README.md +16 -1
  117. package/src/skills/artifact-management/SKILL.md +10 -67
  118. package/src/skills/artifact-management/references/artifact-templates.md +71 -0
  119. package/src/skills/auto-continue/SKILL.md +10 -0
  120. package/src/skills/code-review-checklist/SKILL.md +11 -44
  121. package/src/skills/code-review-checklist/references/review-checklists.md +54 -0
  122. package/src/skills/instruction-forge/SKILL.md +57 -0
  123. package/src/skills/instruction-forge/references/agents-md-doctrine.md +50 -0
  124. package/src/skills/instruction-forge/references/eval-doctrine.md +37 -0
  125. package/src/skills/instruction-forge/references/skill-doctrine.md +62 -0
  126. package/src/skills/memory-bank/SKILL.md +11 -90
  127. package/src/skills/memory-bank/references/anti-patterns.md +33 -0
  128. package/src/skills/memory-bank/references/product-adoption.md +19 -0
  129. package/src/skills/memory-bank/references/storage-model.md +21 -0
  130. package/src/skills/memory-bank/references/structure-and-frequency.md +44 -0
  131. package/src/skills/reflect/SKILL.md +1 -0
  132. package/src/skills/session-goal/SKILL.md +7 -54
  133. package/src/skills/session-goal/references/goal-format.md +26 -0
  134. package/src/skills/session-goal/references/session-reuse.md +44 -0
  135. package/src/skills/tdd-with-agents/SKILL.md +11 -101
  136. package/src/skills/tdd-with-agents/references/advanced-testing-patterns.md +58 -0
  137. package/src/skills/tdd-with-agents/references/testing-by-layer.md +60 -0
  138. package/src/skills/visual-review-pipeline/SKILL.md +11 -120
  139. package/src/skills/visual-review-pipeline/references/findings-schema.md +49 -0
  140. package/src/skills/visual-review-pipeline/references/workflow-steps.md +111 -0
  141. package/scripts/hooks/log-session-start.sh +0 -48
  142. package/scripts/hooks/validate-post-conditions.sh +0 -21
  143. package/scripts/hooks/validate-talos-scope.sh +0 -50
  144. package/scripts/hooks/validate-tool-safety.sh +0 -49
  145. package/src/pantheon/goal-loop.ts +0 -314
  146. package/src/pantheon/idle-continuation.ts +0 -52
  147. package/src/pantheon/todo-preserve.ts +0 -301
  148. package/src/pantheon/tool-ceiling.ts +0 -159
  149. package/src/pantheon/v2-bridge.ts +0 -153
  150. package/src/plugin-v2.ts +0 -2954
  151. package/src/plugins/pantheon-hooks.ts +0 -1433
  152. package/src/plugins/tui/dist/server-v2.d.ts +0 -30
  153. package/src/plugins/tui/dist/server-v2.d.ts.map +0 -1
  154. package/src/plugins/tui/dist/server-v2.js +0 -33
  155. package/src/plugins/tui/dist/server-v2.js.map +0 -1
  156. package/src/plugins/tui/dist/tui-v2.d.ts +0 -1039
  157. package/src/plugins/tui/dist/tui-v2.d.ts.map +0 -1
  158. package/src/plugins/tui/dist/tui-v2.js +0 -4597
  159. package/src/plugins/tui/dist/tui-v2.js.map +0 -1
  160. package/src/plugins/tui/src/index-v2.tsx +0 -4496
  161. package/src/plugins/tui/src/server-v2.ts +0 -28
  162. package/src/plugins/tui/tui-v2.ts +0 -2
  163. /package/src/pantheon/{v2-decision-budget.ts → decision-budget.ts} +0 -0
  164. /package/src/pantheon/{v2-decision-egress.ts → decision-egress.ts} +0 -0
  165. /package/src/pantheon/{v2-decision-events.ts → decision-events.ts} +0 -0
  166. /package/src/pantheon/{v2-decision-heuristic.ts → decision-heuristic.ts} +0 -0
  167. /package/src/pantheon/{v2-decision-premises.ts → decision-premises.ts} +0 -0
  168. /package/src/pantheon/{v2-decision-rank.ts → decision-rank.ts} +0 -0
  169. /package/src/pantheon/{v2-decision-verify.ts → decision-verify.ts} +0 -0
  170. /package/src/pantheon/{v2-delegation-enforce.ts → delegation-policy.ts} +0 -0
  171. /package/src/pantheon/{v2-model-overrides.ts → model-overrides.ts} +0 -0
  172. /package/src/pantheon/{v2-native-decisions.ts → native-decisions.ts} +0 -0
  173. /package/src/plugins/tui/src/{opencode-v2.d.ts → opencode.d.ts} +0 -0
@@ -1,1433 +0,0 @@
1
- /**
2
- * pantheon-hooks.ts — Pantheon runtime security-hook plugin for OpenCode.
3
- *
4
- * Re-created per Council Synthesis 2026-08-05 (P0): the previous hook plugin
5
- * was removed on 24-25/07 because it used the Bun Shell `$` from the plugin
6
- * API, whose interface has NO `.timeout()` method — every hook crashed with
7
- * `TypeError: $.quiet().nothrow().timeout is not a function`. The 10 functional
8
- * scripts in scripts/hooks/ (gitleaks covers only staged files, NOT tool
9
- * calls) were left orphaned. This plugin wires them back into the opencode
10
- * runtime via `node:child_process` (version-proof — see hook-runner.ts).
11
- *
12
- * Hook mapping (Claude Code protocol payload {tool_name, tool_input,
13
- * agent_id, session_id} delivered on the script stdin):
14
- * - tool.execute.before → validate-talos-scope.sh, scan-secrets.sh,
15
- * validate-tool-safety.sh + on-subagent-delegation-start.sh (only when the
16
- * tool is a delegation tool such as `task`, to keep the audit log honest)
17
- * - tool.execute.after → format-multi-language.sh, log-session-start.sh +
18
- * on-subagent-delegation-stop.sh (delegation tool only)
19
- * - event session.created → log-session-start.sh, validate-post-conditions.sh
20
- *
21
- * Notes:
22
- * - `agent_id` is NOT present in the opencode tool.execute hook payloads
23
- * ({tool, sessionID, callID}). P0-4 (2026-08-06): a `chat.params` hook
24
- * records the active agent per session (sessionAgent map), so payloadFor()
25
- * now resolves the real agent_id — validate-talos-scope.sh enforces the
26
- * Talos file-count boundary; the agent-agnostic scan-secrets and
27
- * validate-tool-safety protections remain fully active.
28
- * - tool.execute.before CAN hard-deny — the old "cannot hard-deny" claim
29
- * below this line is OUTDATED for 1.18.x (verified 2026-08-06 on the
30
- * INSTALLED 1.18.13 binary + the opencode plugin docs): a `throw new
31
- * Error(...)` from the hook propagates because Plugin.trigger invokes
32
- * each hook as `yield* v.promise(async () => hook(input, output))` with
33
- * NO try/catch — the rejection fails the tool's execute promise BEFORE
34
- * the tool body runs (the docs' .env-protection example relies on this).
35
- * The permission system remains the primary deny path, but a thrown
36
- * hook error is now a supported hard block (hybrid blocking, Fix 2
37
- * 2026-08-06): scan-secrets.sh exits 2 on high-confidence token matches
38
- * → the plugin logs via reportFailure (non-TUI channels) and THEN throws
39
- * the DELIBERATE block error — the ONLY throw in this plugin. Exit 1
40
- * (low-confidence header/KEY names) stays advisory: toast + logs, no
41
- * block.
42
- * - Logging policy (P0 fix 2026-08-06): NON-ZERO exit → NEVER console.
43
- * `console.error` in a plugin writes to the process stderr, which the
44
- * opencode TUI renders directly into the terminal — that polluted the
45
- * chat with `[pantheon-hooks:scan-secrets.sh] exit 1: [SECRET SCAN]...`
46
- * spam on every tool call. Non-zero exits now go to THREE non-TUI channels:
47
- * 1. client.tui.showToast() — one short, deduped TUI toast (per
48
- * (script, exit code, masked match) per session) so the user gets a
49
- * single visible signal instead of terminal spam;
50
- * 2. client.app.log() — structured entry in the opencode log file
51
- * (service "pantheon-hooks", level "error") — never the TUI;
52
- * 3. .pantheon/logs/hooks.log — project-local one-line append, matching
53
- * the audit-hook pattern of persisting to log files on disk.
54
- * Zero exit → SILENT by default. Audit scripts (log-session-start,
55
- * on-subagent-delegation-*) still write their log FILES (sessions.log,
56
- * delegations.log) from inside the .sh scripts. Set PANTHEON_HOOKS_LOG=1
57
- * (or "debug") to re-enable the zero-exit audit echo for debugging — it is
58
- * routed to the structured log + hooks.log, never the TUI.
59
- * The env var is read once at plugin load time (opencode startup).
60
- * - Hooks NEVER throw: every body is try/catch'd and only logs. All three
61
- * reporting channels (toast, app.log, file append) are individually
62
- * try/catch'd so a failure in one can never take down the session.
63
- * EXCEPTION (Fix 2, 2026-08-06): the deliberate scan-secrets high-
64
- * confidence block — when scan-secrets.sh exits 2, the hook awaits
65
- * reportFailure FIRST (app.log + hooks.log) and only then throws. The
66
- * throw is deliberately NOT swallowed by the surrounding try/catch
67
- * (handled via a blockError variable thrown after it), because that
68
- * rejection is what opencode propagates to fail the tool call.
69
- * - TUI lifecycle toasts (PANTHEON_TOASTS gate, read once at plugin load):
70
- * the base toast mechanism (notifyToast → client.tui.showToast) surfaces
71
- * hook-failure error toasts plus subagent delegation lifecycle events —
72
- * "🚀 <agent> em execução" (tool.execute.before), "✅ <agent> concluiu"
73
- * (tool.execute.after), and olympians/council summaries. The gate is now
74
- * CATEGORY-based — each notification declares one of `errors`,
75
- * `delegations` or `council` and only fires when its category is enabled:
76
- * PANTHEON_TOASTS=off → no categories (empty set)
77
- * PANTHEON_TOASTS=errors → {errors} (hook/agent failures only)
78
- * PANTHEON_TOASTS=delegations → {errors, delegations, council} (default)
79
- * PANTHEON_TOASTS=council → {errors, council}
80
- * PANTHEON_TOASTS=all → {errors, delegations, council}
81
- * Unknown values fall back to the default. The gate controls the TUI
82
- * display only — every fired toast is also
83
- * recorded to the structured log + hooks.log (script 'toast', level
84
- * 'info') so the toast trail stays auditable at any setting.
85
- * - Severity priority (2026-08-06): errors/blockers — hook failures
86
- * ("⚠️ Hook ..."), derivable agent failures ("⚠️ <agent> falhou: ...")
87
- * and session.error events — ALWAYS notify individually, exempt from the
88
- * 2s throttle and from aggregation. Success/completion notifications
89
- * aggregate (olympians summaries / 3-in-6s group), never individually
90
- * when the agent belongs to a detected group.
91
- * - Olympians detection (2026-08-06): 2+ delegation task calls within
92
- * OLYMPIANS_DETECT_WINDOW_MS collapse into ONE group. The 2nd call fires a
93
- * single "⚙️ Olympians: N agentes em formação"; later members only update
94
- * the group buffer. When every member's completion has been observed the
95
- * group fires one "✅ Olympians: N/N concluídos (...)" aggregate.
96
- * One group buffer at a time (groups rarely overlap); a task call more
97
- * than OLYMPIANS_DETECT_WINDOW_MS after the previous one starts a fresh
98
- * group.
99
- * - session.idle handling (2026-08-06): the `event` hook additionally handles
100
- * `session.idle` to reset partial aggregation state and interrupted council
101
- * counters. Completion visibility remains in the board and TUI only.
102
- * - Council notifications (new category 2026-08-06): a `task` whose prompt/
103
- * description matches "council"/"conselho"/"synthesi" is treated as council
104
- * activity — "🏛️ Council: especialistas consultados" on start and
105
- * "✅ Veredito pronto" once every dispatched council specialist completes.
106
- * Category `council` (gated independently of `delegations`).
107
- * - OpenCode 1.18.13 DROPS tui.toast.show (diagnosed 2026-08-06 via sandbox
108
- * probe: headless `opencode serve` on 1.18.13 + /event SSE observation):
109
- * the TUI core handler gates on `if (workspace !== workspace.current())
110
- * return;` and /tui/show-toast publishes events with NO workspace tag
111
- * (properties are {title, message, variant, duration} only). The
112
- * `?directory=` query param even routes the event OFF the global event
113
- * stream (to a directory-scoped stream a plugin client never subscribes
114
- * to), and `?workspace=` requires a per-TUI-client `wrk_` id a plugin
115
- * cannot discover (non-wrk values → HTTP 500 "Expected a string starting
116
- * with wrk"). The upstream fix (server-side workspace tagging) only exists
117
- * in NEWER opencode versions. THEREFORE on 1.18.13 the toast path below is
118
- * a documented TUI no-op and agent-lifecycle feedback is surfaced via the
119
- * no transcript fallback is used. Toasts stay in place for future opencode
120
- * versions that render them — upgrade opencode for real TUI toasts.
121
- * - tool.execute.after payload fix (P1-1 follow-up, 2026-08-06): the after
122
- * hook receives `(input, output)` where `output` = {title, output,
123
- * metadata} — the REAL tool result. It is now merged into the payload
124
- * passed to the stop-hook scripts as `tool_output` (additive key) plus a
125
- * plugin-derived `status` ('success' | 'failure' | 'dispatched' |
126
- * 'unknown'), so on-subagent-delegation-stop.sh can log honest completion
127
- * instead of the old args-only 'unknown'. Payload schema stays compatible
128
- * — scripts read stdin JSON; new keys are additive.
129
- * - P0-5 (2026-08-06, user test battery): the task tool's BACKGROUND dispatch
130
- * arrives as free TEXT — `<task id="ses_..." state="running">\n<summary>
131
- * Background task started</summary>...` — NOT JSON (verified in the
132
- * installed 1.18.14 binary; metadata carries `background:true` + `jobId`,
133
- * no state key). deriveResultStatus now detects the TEXT signature (+
134
- * `metadata.background === true`) so background launches record
135
- * 'dispatched' instead of the previous false 'success'; extractTaskId
136
- * pulls the real `ses_...` id via `task id="ses_..."`. appendHookLog
137
- * splits multi-line messages so EVERY hooks.log line carries the ISO
138
- * prefix. GAP C: the bash tool's non-zero exit codes now fire an
139
- * individual ⚠️ error notification (signal: `metadata.exit`, verified
140
- * 1.18.14 — {title, output, metadata: {output, exit, truncated}}).
141
- * - Background-mode contract (P0-1/P0-2, 2026-08-06, 2nd council session):
142
- * the `task` tool in BACKGROUND mode returns IMMEDIATELY with
143
- * {task_id, state:'running'} — tool.execute.after therefore observes
144
- * DISPATCH, not completion. The stop-hook payload now separates the
145
- * delegation-LIFECYCLE fields (agent, delegation_id, task_id, status,
146
- * duration_ms) from the free-text result blob (tool_output): agent, status
147
- * and session_id are never derived from result text (prim() sanitizer
148
- * strips non-primitive junk), and a background launch is recorded as
149
- * status:'dispatched' — never 'success'. REAL completion of background
150
- * tasks is NOT observable via tool.execute.after on opencode 1.18.13 (no
151
- * second after-event fires) — documented platform limitation, not a
152
- * telemetry bug. delegation_id is generated in tool.execute.before
153
- * (crypto.randomUUID), keyed by callID, and threaded to BOTH the start and
154
- * the stop hook so delegations.log joins Start↔Stop on it; duration_ms is
155
- * computed from the before-record start timestamp; task_id is extracted
156
- * from the result into its OWN payload field.
157
- * - P0-5 (2026-08-06, user test battery): the runtime ACTUALLY delivers the
158
- * background dispatch as free TEXT, not JSON — `<task id="ses_..."
159
- * state="running">\n<summary>Background task started</summary>...` (verified
160
- * in the installed 1.18.14 binary; metadata carries `background:true` +
161
- * `jobId`, no state key). deriveResultStatus now detects that TEXT
162
- * signature (+ `metadata.background === true`) and extractTaskId pulls the
163
- * `ses_...` id via `task id="ses_..."`. The stop-hook script's TSV handoff
164
- * (8 fields read with `cut -fN`) was replaced by a JSON round-trip because
165
- * a REAL newline in result_snippet shifted fields 5-8 into garbage;
166
- * result_snippet is newline/tab-collapsed + 200-char-truncated before the
167
- * JSON. appendHookLog splits multi-line messages so EVERY line gets the
168
- * ISO prefix. GAP C: bash tool non-zero exit codes now fire an individual
169
- * ⚠️ error notification (signal: `metadata.exit`, verified 1.18.14).
170
- *
171
- * IMPORTANT (OpenCode 1.18.11 legacy loader): this module must export EXACTLY
172
- * ONE function-valued export — the default plugin (see src/plugin.ts L47-52).
173
- * Helpers live in ./hook-runner.ts and are imported from there.
174
- */
175
-
176
- import { appendFile, mkdir } from 'node:fs/promises'
177
- import { join } from 'node:path'
178
- import type { Plugin, PluginInput } from '@opencode-ai/plugin'
179
- import { pantheonPluginOnce } from '../pantheon/plugin-once.ts'
180
- import { getSharedBoard } from '../pantheon/shared-board.ts'
181
- import { type HookPayload, type HookResult, runHook } from './hook-runner.ts'
182
-
183
- /** Tools that represent a subagent delegation (opencode `task` tool etc.). */
184
- const DELEGATION_TOOL_RE = /^(task|.*subagent.*)$/i
185
-
186
- /**
187
- * When set to a truthy value ("1" or "debug"), zero-exit audit-hook output is
188
- * echoed for debugging (opt-in). Default (unset): fully silent on success —
189
- * the .sh scripts still persist their log FILES on disk. Read at plugin load.
190
- * The debug echo goes to the structured log + hooks.log, never the TUI.
191
- */
192
- const AUDIT_LOG_ENABLED = (process.env.PANTHEON_HOOKS_LOG ?? '').trim() !== ''
193
-
194
- /** Scripts whose zero-exit stderr is relayed when PANTHEON_HOOKS_LOG is set. */
195
- const AUDIT_HOOKS = new Set([
196
- 'log-session-start.sh',
197
- 'on-subagent-delegation-start.sh',
198
- 'on-subagent-delegation-stop.sh',
199
- 'validate-post-conditions.sh',
200
- ])
201
-
202
- /**
203
- * Dedupe keys for TUI toasts: `${script}|${exit code}|${masked match}`.
204
- * Same security signal is toasted at most once per session — repeated false
205
- * positives on every tool call must not re-toast and annoy the user.
206
- */
207
- const toastShown = new Set<string>()
208
-
209
- /** Notification categories gated by PANTHEON_TOASTS (see header). */
210
- type ToastCategory = 'errors' | 'delegations' | 'council'
211
-
212
- /**
213
- * TUI toast gate — PANTHEON_TOASTS=off|errors|delegations|council|all, read
214
- * once at plugin load (opencode startup). Default "delegations" = {errors,
215
- * delegations, council}: hook-failure + delegation-lifecycle + council toasts. The gate is a Set
216
- * of enabled categories; every notification declares its category and is
217
- * skipped unless enabled. "off" = empty set, "all" = every category. Unknown
218
- * values fall back to the default. The gate controls the TUI display +
219
- * display only — the structured log + hooks.log channels
220
- * always write (every fired toast is recorded via reportFailure with script
221
- * 'toast').
222
- */
223
- const rawToastMode = (process.env.PANTHEON_TOASTS ?? '').trim().toLowerCase()
224
- function parseToastCategories(mode: string): ReadonlySet<ToastCategory> {
225
- switch (mode) {
226
- case 'off':
227
- return new Set()
228
- case 'errors':
229
- return new Set(['errors'])
230
- case 'council':
231
- return new Set(['errors', 'council'])
232
- case 'all':
233
- return new Set(['errors', 'delegations', 'council'])
234
- default:
235
- // Unknown value (or unset) → default: errors + delegations + council.
236
- return new Set(['errors', 'delegations', 'council'])
237
- }
238
- }
239
- const ENABLED_TOAST_CATEGORIES: ReadonlySet<ToastCategory> = parseToastCategories(rawToastMode)
240
-
241
- function toastCategoryEnabled(cat: ToastCategory): boolean {
242
- return ENABLED_TOAST_CATEGORIES.has(cat)
243
- }
244
-
245
- /**
246
- * Delegation toast anti-spam: olympians dispatch up to 5 subagents in parallel,
247
- * so raw per-agent toasts would spam the TUI. Two guards:
248
- * - Rate limit: at most ONE delegation toast per 2000ms (lastToastAt).
249
- * Throttled toasts are skipped, never backlogged — the aggregate summary
250
- * covers them. Error toasts bypass this throttle (severity priority).
251
- * - Aggregation: 3+ distinct agents completing within a 6s window collapse
252
- * into a single "✅ N agentes concluídos (...)" toast via a small rolling
253
- * buffer (Map<agent, completion timestamp>) flushed on the 3rd in-window
254
- * completion. Agents belonging to a detected group use olympians
255
- * aggregation instead (see OLYMPIANS_DETECT_WINDOW_MS below).
256
- */
257
- const TOAST_MIN_INTERVAL_MS = 2000
258
- const GROUP_COMPLETE_WINDOW_MS = 6000
259
- const GROUP_COMPLETE_MIN = 3
260
- let lastToastAt = 0
261
- const completedAgents = new Map<string, number>()
262
-
263
- /**
264
- * Olympians detection (see header): 2+ delegation task calls within the window
265
- * collapse into ONE group. `detected` flips on the 2nd in-window call (the
266
- * olympians-start notification fires exactly once); `pendingCompletions`
267
- * tracks members whose completion has NOT yet been observed, so the idle
268
- * flush can report partial groups. A task call more than
269
- * OLYMPIANS_DETECT_WINDOW_MS after the previous one (lastTaskAt) starts a
270
- * fresh group buffer.
271
- */
272
- const OLYMPIANS_DETECT_WINDOW_MS = 10_000
273
-
274
- type Olympians = {
275
- id: string
276
- agents: Set<string>
277
- startedAt: number
278
- lastTaskAt: number
279
- pendingCompletions: Set<string>
280
- doneCount: number
281
- detected: boolean
282
- }
283
-
284
- let activeOlympians: Olympians | null = null
285
- let olympiansSeq = 0
286
-
287
- /**
288
- * Council notifications (new category, see header): a `task` whose prompt/
289
- * description matches the council markers is treated as council activity.
290
- * `councilStartNotified` fires "🏛️ Council: especialistas consultados" once;
291
- * `pendingCouncilCalls` tracks the callIDs of dispatched council specialists
292
- * (the after-hook args do NOT repeat the description, so completion is matched
293
- * by callID); `✅ Veredito pronto` fires when every dispatched council
294
- * specialist has completed. Counters reset on fire and at session.idle (an
295
- * interrupted council must not block a later council's verdict).
296
- */
297
- const COUNCIL_RE = /council|conselho|synthesi/i
298
- let councilStartNotified = false
299
- let councilDispatchCount = 0
300
- let councilDoneCount = 0
301
- const pendingCouncilCalls = new Set<string>()
302
-
303
- /**
304
- * P0-4 session→agent map: opencode tool.execute hooks carry NO agent_id in
305
- * their payload ({tool, sessionID, callID}), so validate-talos-scope.sh never
306
- * knows who called the tool. The `chat.params` hook fires per assistant turn
307
- * with the active agent name — record it per session here, then payloadFor()
308
- * resolves agent_id from this map (falling back to an inline agent field when
309
- * present). Bounded: entries older than 30min are pruned when the map exceeds
310
- * 50 sessions, so stale sessions cannot accumulate.
311
- */
312
- const sessionAgent = new Map<string, { agent: string; at: number }>()
313
-
314
- /**
315
- * P0-4 advisory content guard: risky edit/write/bash targets (migrations,
316
- * alembic, models/, auth, secrets) or bulk multi-file operations (>3 unique
317
- * file-ish args) surface as a 'warn' log line via reportFailure — advisory
318
- * ONLY, never blocks (the permission system is the real deny path).
319
- */
320
- const RISKY_PATH_RE = /migration|schema\.sql|alembic|models\/|auth|password|token|secret/i
321
-
322
- /**
323
- * Fix 1 (2026-08-06): high-confidence secret token formats — mirrors
324
- * scripts/hooks/scan-secrets.sh HIGH_CONFIDENCE_PATTERNS. Used by maskSecret()
325
- * to REDACT secret VALUES from any plugin log line: the talos-guard must
326
- * never write a raw credential to hooks.log (a real `sk-bf-...` token leaked
327
- * in plain text there on 2026-08-06). Header/KEY names (the Bifrost header alone,
328
- * api_key=...) are deliberately NOT matched — they are not secret values.
329
- */
330
- const SECRET_MASK_RE =
331
- /(sk-bf-[A-Za-z0-9_-]{8,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9_]{36,}|glpat-[A-Za-z0-9_-]{20}|sk-[a-zA-Z0-9]{20,}|sk_live_[a-zA-Z0-9]{20,}|sk_test_[a-zA-Z0-9]{20,}|xox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24}|bearer\s+[a-zA-Z0-9_.-]{20,}|eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*)/gi
332
-
333
- /**
334
- * Fix 1: replace every high-confidence secret match with '****' so log lines
335
- * (hooks.log, structured log, toasts, chat reminders) can never expose a raw
336
- * token value. Applied to every path that echoes tool-arg or tool-result
337
- * content (talos-guard hit, safeRun script output, agentFailedToast reason).
338
- */
339
- function maskSecret(text: string): string {
340
- return text.replace(SECRET_MASK_RE, '****')
341
- }
342
-
343
- /**
344
- * Fix 2 (2026-08-06): message thrown when scan-secrets.sh exits 2
345
- * (HIGH_CONFIDENCE token match). This is the ONLY deliberate throw in the
346
- * plugin — it is thrown AFTER reportFailure so the log channels always write
347
- * first, and it is NOT swallowed by the hook's try/catch: opencode's
348
- * Plugin.trigger has no catch around hook invocations, so the rejection
349
- * propagates and fails the tool's execute promise BEFORE the tool runs.
350
- */
351
- const SECRET_BLOCK_MESSAGE =
352
- '[pantheon-hooks] Bloqueado: segredo de alta confiança detectado no tool input — consulte .pantheon/logs/hooks.log'
353
-
354
- /**
355
- * P2 (2026-08-06): talos-guard is restricted to WRITE-INTENT operations.
356
- * Read-only tools (find/grep/search) legitimately match RISKY_PATH_RE (e.g.
357
- * grepping for 'auth') and must NEVER trigger the advisory. edit/write/patch
358
- * always write; bash only when the command contains a write operator
359
- * (redirect to a file, mv/cp/rm/tee, sed -i, git commit/push). `2>&1` fd
360
- * duplication is NOT a file write and does not trigger.
361
- */
362
- const WRITE_INTENT_TOOLS = new Set(['edit', 'write', 'patch'])
363
- const BASH_WRITE_INTENT_RE = />>|>(?!&)|\b(mv|cp|rm|tee)\b|\bsed\s+-i\b|\bgit\s+(commit|push)\b/
364
-
365
- /**
366
- * Strong failure markers for the tool RESULT (tool.execute.after output).
367
- * Deliberately conservative — a completed task whose output merely mentions
368
- * an error word must not be mislabeled a failure. Mirrored by the stop-hook
369
- * script's own markers.
370
- */
371
- const RESULT_FAILURE_MARKERS =
372
- /\b(refused|denied|traceback|exception|unhandled|fatal)\b|failed to|unable to|timed out|error:/i
373
-
374
- /**
375
- * P0-2 delegation correlation: every delegation gets a delegation_id in
376
- * tool.execute.before (crypto.randomUUID), threaded through the payload to
377
- * BOTH the start and the stop hook so delegations.log joins Start↔Stop on it.
378
- * Records are keyed by callID (stable across before/after for the same tool
379
- * call — the council tracking already relies on this) and hold the BEFORE-time
380
- * agent, so the after-hook agent can never be contaminated by a merged result
381
- * blob. Bounded: at most DELEGATION_TRACK_MAX entries, entries older than
382
- * DELEGATION_TRACK_TTL_MS are pruned.
383
- */
384
- type DelegationStart = {
385
- delegation_id: string
386
- agent: string
387
- startedAt: number
388
- }
389
- const delegationStarts = new Map<string, DelegationStart>()
390
- const DELEGATION_TRACK_MAX = 100
391
- const DELEGATION_TRACK_TTL_MS = 30 * 60 * 1000
392
-
393
- /** P0-1: background-dispatch state values (dispatch, not completion). */
394
- const BACKGROUND_STATE_RE = /^(running|queued|pending|scheduled|dispatched)$/i
395
-
396
- /** P0-1: free-text task_id extraction from a JSON-ish tool result. */
397
- const TASK_ID_RE = /"task_id"\s*:\s*"?([^",\s}]+)"?/i
398
-
399
- /**
400
- * P0-5 (2026-08-06): TEXT background-dispatch signature — the ACTUAL runtime
401
- * format of the task tool in BACKGROUND mode on opencode 1.18.x (verified in
402
- * the installed 1.18.14 binary): the tool returns IMMEDIATELY with free TEXT
403
- * (not JSON) `<task id="ses_..." state="running">\n<summary>Background task
404
- * started</summary>...` plus `metadata.background === true` and a `jobId`.
405
- * Attribute order is id-then-state (as emitted by the runtime); the `i` flag
406
- * tolerates case differences. Matched against title+output text.
407
- */
408
- const BACKGROUND_DISPATCH_TEXT_RE =
409
- /<task\s+[^>]*\bid="(ses_[^"]+)"[^>]*\bstate="(running|queued|pending|scheduled|dispatched)"/i
410
-
411
- /** P0-5: extract the REAL task id from the TEXT form `task id="ses_..."`. */
412
- const TASK_ID_TEXT_RE = /\btask\s+id="(ses_[^"]+)"/i
413
-
414
- /**
415
- * Delegation lifecycle state is intentionally not mirrored into the transcript.
416
- * The board/list/read tools and TUI toasts are the supported visibility channels.
417
- */
418
-
419
- /** Variants accepted by the opencode TUI showToast (TuiShowToastData.body.variant). */
420
- type ToastVariant = 'info' | 'success' | 'warning' | 'error'
421
-
422
- /** Options for notifyToast: message, TUI variant, category gate, duration, optional session dedupe key. */
423
- type ToastOptions = {
424
- message: string
425
- variant: ToastVariant
426
- /** Gate category — the toast only fires when PANTHEON_TOASTS enables it. */
427
- category: ToastCategory
428
- duration?: number
429
- dedupeKey?: string
430
- /** Optional TUI toast headline (opencode showToast body.title). */
431
- title?: string
432
- }
433
-
434
- /** Logging context threaded through safeRun — provided by the plugin input. */
435
- type HookContext = Pick<PluginInput, 'client' | 'directory'>
436
-
437
- /** The tool.execute.after hook result ({title, output, metadata} — see header). */
438
- type ToolExecuteAfterResult = { title: string; output: string; metadata: unknown }
439
-
440
- function trim(s: string, max = 2000): string {
441
- const t = s.trim()
442
- return t.length > max ? `${t.slice(0, max)}…` : t
443
- }
444
-
445
- /** Translate the opencode hook event into the Claude Code protocol payload. */
446
- function payloadFor(
447
- input: { tool: string; sessionID: string },
448
- toolInput: unknown,
449
- extra?: Record<string, unknown>,
450
- ): HookPayload {
451
- return {
452
- tool_name: input.tool,
453
- tool_input: toolInput ?? {},
454
- // tool.execute hooks carry no agent — resolve it from the sessionAgent map
455
- // (populated by the chat.params hook) with an inline agent field fallback.
456
- agent_id:
457
- sessionAgent.get(input.sessionID)?.agent ??
458
- (input as { agent?: { id?: string } }).agent?.id ??
459
- '',
460
- session_id: input.sessionID,
461
- ...(extra ?? {}),
462
- }
463
- }
464
-
465
- /**
466
- * P0-1/P0-2: the tool.execute.after payload. Separates the delegation-
467
- * LIFECYCLE fields (agent, delegation_id, task_id, status, duration_ms) from
468
- * the free-text result blob (tool_output). `start` is the tool.execute.before
469
- * record keyed by callID — when present, its agent wins (the after-hook args
470
- * may carry the MERGED background result {task_id, state}, never a
471
- * subagent_type). Additive keys only — scripts read stdin JSON, so the schema
472
- * stays compatible with older payloads.
473
- */
474
- function afterPayloadFor(
475
- input: { tool: string; sessionID: string },
476
- args: unknown,
477
- result: ToolExecuteAfterResult | null,
478
- start?: DelegationStart,
479
- ): HookPayload {
480
- const extra: Record<string, unknown> = {
481
- tool_output: result,
482
- status: deriveResultStatus(result),
483
- }
484
- if (start !== undefined) {
485
- extra.agent_id = start.agent
486
- extra.delegation_id = start.delegation_id
487
- extra.duration_ms = Math.max(0, Date.now() - start.startedAt)
488
- }
489
- const taskID = extractTaskId(result)
490
- if (taskID !== '') extra.task_id = taskID
491
- return payloadFor(input, args, extra)
492
- }
493
-
494
- /**
495
- * Derive 'success' | 'failure' | 'dispatched' | 'unknown' from the tool
496
- * result. Precedence:
497
- * 1. background-dispatch signature → 'dispatched': the task tool in
498
- * BACKGROUND mode returns immediately with {task_id, state:'running'}
499
- * (or 'queued'/'pending') — that is DISPATCH, not completion (P0-1);
500
- * 2. explicit status-ish fields in metadata (existing logic);
501
- * 3. failure markers in the result text;
502
- * 4. non-empty output (real completion evidence) → 'success';
503
- * 5. 'unknown'. Never throws.
504
- */
505
- function deriveResultStatus(
506
- result: ToolExecuteAfterResult | null | undefined,
507
- ): 'success' | 'failure' | 'dispatched' | 'unknown' {
508
- if (result === null || result === undefined) return 'unknown'
509
- const meta = result.metadata
510
- if (meta !== null && typeof meta === 'object') {
511
- const m = meta as Record<string, unknown>
512
- // P0-1: background-dispatch state values first ('running'/'queued'/...).
513
- for (const key of ['status', 'state']) {
514
- const v = m[key]
515
- if (typeof v === 'string' && BACKGROUND_STATE_RE.test(v.trim())) return 'dispatched'
516
- }
517
- for (const key of ['status', 'state', 'ok', 'success', 'error', 'failed']) {
518
- if (key in m) {
519
- const v = m[key]
520
- if (typeof v === 'boolean') return v ? 'success' : 'failure'
521
- if (typeof v === 'string') {
522
- const low = v.trim().toLowerCase()
523
- if (
524
- [
525
- 'success',
526
- 'successful',
527
- 'completed',
528
- 'complete',
529
- 'done',
530
- 'finished',
531
- 'ok',
532
- 'true',
533
- '1',
534
- ].includes(low)
535
- ) {
536
- return 'success'
537
- }
538
- if (
539
- [
540
- 'failure',
541
- 'failed',
542
- 'error',
543
- 'refused',
544
- 'denied',
545
- 'exception',
546
- 'false',
547
- '0',
548
- 'cancelled',
549
- 'canceled',
550
- 'aborted',
551
- ].includes(low)
552
- ) {
553
- return 'failure'
554
- }
555
- }
556
- }
557
- }
558
- // P0-1: task_id field with no terminal status above — background dispatch.
559
- if (m.task_id !== undefined || m.taskId !== undefined) return 'dispatched'
560
- // P0-5: `background: true` marks a background launch (verified 1.18.14:
561
- // the dispatch result metadata is {..., background: true, jobId}).
562
- if (m.background === true) return 'dispatched'
563
- }
564
- const text = `${result.title ?? ''} ${result.output ?? ''}`
565
- // P0-1: JSON-as-string output {"task_id":..., "state":"running"} — the
566
- // background dispatch signature delivered as free text inside the result.
567
- if (typeof result.output === 'string' && result.output.trim() !== '') {
568
- const parsed = tryParseJsonObject(result.output)
569
- if (parsed !== null && (parsed.task_id !== undefined || parsed.taskId !== undefined)) {
570
- return 'dispatched'
571
- }
572
- // P0-5: TEXT background-dispatch signature — the ACTUAL runtime format on
573
- // 1.18.x: `<task id="ses_..." state="running">\n<summary>Background task
574
- // started</summary>...`. Without this, the blob fell through to the
575
- // non-empty-output → 'success' branch below — the false success observed
576
- // by the user's test battery (2026-08-06).
577
- if (BACKGROUND_DISPATCH_TEXT_RE.test(text)) return 'dispatched'
578
- }
579
- if (RESULT_FAILURE_MARKERS.test(text)) return 'failure'
580
- if (typeof result.output === 'string' && result.output.trim() !== '') return 'success'
581
- return 'unknown'
582
- }
583
-
584
- /**
585
- * P0-1 sanitizer: coerce a payload value to a plain string; non-primitive junk
586
- * (objects/arrays from a merged result blob) becomes ''. Guards the
587
- * delegation-lifecycle fields so agent/status/task_id can never be polluted.
588
- */
589
- function prim(v: unknown): string {
590
- if (typeof v === 'string') return v
591
- if (typeof v === 'number' || typeof v === 'boolean' || typeof v === 'bigint') return String(v)
592
- return ''
593
- }
594
-
595
- /** Parse a JSON-object string into a plain record (null when not JSON). */
596
- function tryParseJsonObject(text: string): Record<string, unknown> | null {
597
- const t = text.trim()
598
- if (!t.startsWith('{')) return null
599
- try {
600
- const v = JSON.parse(t) as unknown
601
- if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
602
- return v as Record<string, unknown>
603
- }
604
- } catch {
605
- // Not JSON — null.
606
- }
607
- return null
608
- }
609
-
610
- /**
611
- * P0-1: extract the background `task_id` into its OWN clean field — never
612
- * concatenated into agent/status. Sources: metadata (task_id/taskId) →
613
- * JSON-as-string in output → free-text regex over the result.
614
- */
615
- function extractTaskId(result: ToolExecuteAfterResult | null | undefined): string {
616
- if (result === null || result === undefined) return ''
617
- const meta = result.metadata
618
- if (meta !== null && typeof meta === 'object') {
619
- const m = meta as Record<string, unknown>
620
- const direct = m.task_id ?? m.taskId
621
- if (direct !== undefined) return prim(direct)
622
- }
623
- if (typeof result.output === 'string' && result.output.trim() !== '') {
624
- const parsed = tryParseJsonObject(result.output)
625
- if (parsed !== null) {
626
- const direct = parsed.task_id ?? parsed.taskId
627
- if (direct !== undefined) return prim(direct)
628
- }
629
- const m = TASK_ID_RE.exec(result.output)
630
- if (m?.[1] !== undefined) return m[1]
631
- // P0-5: TEXT form `<task id="ses_..." state="running">` — the runtime
632
- // background-dispatch format (id sits in its own attribute, not JSON).
633
- const mt = TASK_ID_TEXT_RE.exec(result.output)
634
- if (mt?.[1] !== undefined) return mt[1]
635
- }
636
- return ''
637
- }
638
-
639
- /** P0-2: prune stale delegation records; over the cap, drop oldest first. */
640
- function pruneDelegationStarts(now: number): void {
641
- for (const [callID, rec] of delegationStarts) {
642
- if (now - rec.startedAt > DELEGATION_TRACK_TTL_MS) delegationStarts.delete(callID)
643
- }
644
- while (delegationStarts.size >= DELEGATION_TRACK_MAX) {
645
- let oldestID: string | null = null
646
- let oldestAt = Infinity
647
- for (const [callID, rec] of delegationStarts) {
648
- if (rec.startedAt < oldestAt) {
649
- oldestAt = rec.startedAt
650
- oldestID = callID
651
- }
652
- }
653
- if (oldestID === null) break
654
- delegationStarts.delete(oldestID)
655
- }
656
- }
657
-
658
- /** Append one line to .pantheon/logs/hooks.log under the project directory. */
659
- async function appendHookLog(directory: string, line: string): Promise<void> {
660
- const dir = join(directory, '.pantheon', 'logs')
661
- await mkdir(dir, { recursive: true })
662
- // P2 (2026-08-06): every line carries an ISO timestamp so the hook trail is
663
- // chronologically readable — [2026-08-06T13:00:00.000Z] message.
664
- // P0-5 (2026-08-06): a message containing real newlines (e.g. multi-line
665
- // stderr) used to produce continuation lines WITHOUT the timestamp prefix
666
- // (user evidence: `[SECRET SCAN] High-confidence hardcoded secret
667
- // detected…` with no prefix). Split on \n, trim each piece, skip empties,
668
- // and write `[ISO] piece` per line — one message → N fully-timestamped
669
- // lines. Same ISO stamp for the whole message (they are one event).
670
- const stamp = new Date().toISOString()
671
- const body = line
672
- .split('\n')
673
- .map((p) => p.trim())
674
- .filter((p) => p !== '')
675
- .map((p) => `[${stamp}] ${p}`)
676
- .join('\n')
677
- if (body === '') return
678
- await appendFile(join(dir, 'hooks.log'), `${body}\n`, 'utf8')
679
- }
680
-
681
- /**
682
- * Persist a hook result line to the non-TUI channels: the opencode structured
683
- * log (client.app.log) and the project hooks.log file. Both are best-effort
684
- * and individually guarded — a reporting failure must never throw out of a hook.
685
- */
686
- async function reportFailure(
687
- ctx: HookContext,
688
- message: string,
689
- extra: Record<string, unknown>,
690
- level: 'error' | 'info' | 'warn' = 'error',
691
- ): Promise<void> {
692
- try {
693
- await ctx.client.app.log({
694
- body: { service: 'pantheon-hooks', level, message, extra },
695
- })
696
- } catch {
697
- // Structured log is best-effort; the file append below still runs.
698
- }
699
- try {
700
- await appendHookLog(ctx.directory, message)
701
- } catch {
702
- // File log is best-effort; nothing else to fall back to.
703
- }
704
- }
705
-
706
- /**
707
- * Show ONE short, single-line TUI toast with an optional dedupe key. Deduped
708
- * per key per session (key added before showing, so repeated signals toast at
709
- * most once). Gated by the notification's category (PANTHEON_TOASTS). Best-
710
- * effort: headless mode or a missing TUI endpoint must never throw out of a
711
- * hook. Every fired toast is also recorded via reportFailure (script 'toast',
712
- * level 'info') so the toast trail is auditable — the log channels write
713
- * regardless of the display gate.
714
- */
715
- async function notifyToast(ctx: HookContext, opts: ToastOptions): Promise<void> {
716
- try {
717
- if (opts.dedupeKey) {
718
- if (toastShown.has(opts.dedupeKey)) return
719
- toastShown.add(opts.dedupeKey)
720
- }
721
- if (!toastCategoryEnabled(opts.category)) return
722
- await ctx.client.tui.showToast({
723
- body: {
724
- ...(opts.title !== undefined ? { title: opts.title } : {}),
725
- message: opts.message,
726
- variant: opts.variant,
727
- duration: opts.duration ?? 4000,
728
- },
729
- })
730
- await reportFailure(
731
- ctx,
732
- `[pantheon-hooks:toast] ${opts.message}`,
733
- {
734
- script: 'toast',
735
- category: opts.category,
736
- title: opts.title ?? null,
737
- variant: opts.variant,
738
- duration: opts.duration ?? 4000,
739
- dedupeKey: opts.dedupeKey ?? null,
740
- },
741
- 'info',
742
- )
743
- } catch {
744
- // No TUI / headless: toast is best-effort, logs already persisted.
745
- }
746
- }
747
-
748
- /**
749
- * Rate-limited delegation toast: at most ONE per TOAST_MIN_INTERVAL_MS.
750
- * Throttled toasts are skipped (never queued/backlogged) — the aggregated
751
- * completion summary covers the group. Only applies to delegation lifecycle
752
- * toasts; error toasts (hook failures, agent failures) bypass the throttle
753
- * entirely (severity priority) and keep their plain session dedupe.
754
- */
755
- async function throttledToast(ctx: HookContext, opts: ToastOptions): Promise<void> {
756
- const now = Date.now()
757
- if (now - lastToastAt < TOAST_MIN_INTERVAL_MS) return
758
- lastToastAt = now
759
- await notifyToast(ctx, opts)
760
- }
761
-
762
- /**
763
- * Extract the subagent type from a delegation tool's args (opencode `task`
764
- * tool passes `subagent_type`, e.g. 'apollo' / 'hermes'). Falls back to the
765
- * tool name when the field is missing so the toast still identifies what ran.
766
- * Never throws — malformed args are treated as empty.
767
- */
768
- function delegationAgent(tool: string, args?: unknown): string {
769
- try {
770
- const a = (args ?? {}) as Record<string, unknown>
771
- const candidate = a.subagent_type ?? a.subagentType
772
- if (typeof candidate === 'string' && candidate.trim() !== '') return candidate
773
- } catch {
774
- // Malformed args — fall through to the tool name.
775
- }
776
- return tool
777
- }
778
-
779
- /**
780
- * beta.5: mirror a native background task dispatch onto the SHARED board
781
- * (getSharedBoard) so the existing finalize path in plugin.ts (session.idle
782
- * event + 30s idle scan) writes the terminal report and the TUI delegation
783
- * panel tracks the child end-to-end. Fire-and-forget and silent: a mirror
784
- * failure must never surface into the tool call or the transcript.
785
- * registerLaunchIfAbsent keeps it idempotent against any other dispatcher
786
- * (plugin double-load, repeated after-hook firings).
787
- */
788
- function mirrorNativeBackgroundDispatch(
789
- input: { tool: string; sessionID: string },
790
- args: unknown,
791
- result: ToolExecuteAfterResult | null,
792
- ): void {
793
- const taskID = extractTaskId(result)
794
- if (taskID === '' || typeof input.sessionID !== 'string' || input.sessionID === '') return
795
- const description = trim(delegationDescription(args) ?? `native ${input.tool} dispatch`, 200)
796
- try {
797
- getSharedBoard()
798
- .registerLaunchIfAbsent({
799
- taskID,
800
- parentSessionID: input.sessionID,
801
- agent: delegationAgent(input.tool, args),
802
- description,
803
- })
804
- .catch(() => {
805
- // Mirror is best-effort — never surface into the tool call.
806
- })
807
- } catch {
808
- // Never let the mirror take down the tool call.
809
- }
810
- }
811
-
812
- /** Task description from task-tool args (description ?? prompt); undefined when absent. */
813
- function delegationDescription(args: unknown): string | undefined {
814
- try {
815
- const a = (args ?? {}) as Record<string, unknown>
816
- const raw = a.description ?? a.prompt
817
- if (typeof raw === 'string' && raw.trim() !== '') return raw
818
- } catch {
819
- // Malformed args — fall through to the generic description.
820
- }
821
- return undefined
822
- }
823
-
824
- /** 🚀 delegation-started toast (variant 'info', 2500ms), deduped per agent. */
825
- async function delegationStartedToast(ctx: HookContext, agent: string): Promise<void> {
826
- await throttledToast(ctx, {
827
- title: 'Delegação',
828
- message: `🚀 ${agent} em execução`,
829
- variant: 'info',
830
- duration: 2500,
831
- category: 'delegations',
832
- dedupeKey: `${agent}|start`,
833
- })
834
- }
835
-
836
- /**
837
- * ✅ delegation-completed toast (variant 'success', 3000ms), deduped per agent.
838
- * Anti-spam aggregation: when 3+ distinct agents complete within a 6s window,
839
- * the individual toasts are REPLACED by one "✅ N agentes concluídos (...)"
840
- * toast and the buffer is flushed. The aggregate bypasses the 2s throttle so
841
- * the group summary is always visible — it is inherently rare (≥3 agents / 6s).
842
- * Agents belonging to a detected group are handled by olympians aggregation
843
- * instead (handleOlympiansCompletion) and never reach this path.
844
- */
845
- async function delegationDoneToast(ctx: HookContext, agent: string): Promise<void> {
846
- const now = Date.now()
847
- for (const [name, at] of completedAgents) {
848
- if (now - at > GROUP_COMPLETE_WINDOW_MS) completedAgents.delete(name)
849
- }
850
- completedAgents.set(agent, now)
851
- if (completedAgents.size >= GROUP_COMPLETE_MIN) {
852
- const count = completedAgents.size
853
- const names = [...completedAgents.keys()].sort().join(', ')
854
- completedAgents.clear()
855
- await notifyToast(ctx, {
856
- title: 'Delegação',
857
- message: `✅ ${count} agentes concluídos (${names})`,
858
- variant: 'success',
859
- duration: 4000,
860
- category: 'delegations',
861
- dedupeKey: `group-complete|${names}`,
862
- })
863
- return
864
- }
865
- await throttledToast(ctx, {
866
- title: 'Delegação',
867
- message: `✅ ${agent} concluiu`,
868
- variant: 'success',
869
- duration: 3000,
870
- category: 'delegations',
871
- dedupeKey: `${agent}|done`,
872
- })
873
- }
874
-
875
- /** ⚙️ olympians-detected toast — fires ONCE per group (on the 2nd in-window task call). */
876
- async function notifyOlympiansStarted(ctx: HookContext, olympians: Olympians): Promise<void> {
877
- const count = olympians.agents.size
878
- await notifyToast(ctx, {
879
- title: 'Olympians',
880
- message: `⚙️ Olympians: ${count} agentes em formação`,
881
- variant: 'info',
882
- duration: 3000,
883
- category: 'delegations',
884
- dedupeKey: `olympians-start|${olympians.id}`,
885
- })
886
- }
887
-
888
- /** ✅ olympians-complete toast — fires once when every group member has completed. */
889
- async function notifyOlympiansComplete(ctx: HookContext, olympians: Olympians): Promise<void> {
890
- const names = [...olympians.agents].sort().join(', ')
891
- await notifyToast(ctx, {
892
- title: 'Olympians',
893
- message: `✅ Olympians: ${olympians.doneCount}/${olympians.agents.size} concluídos (${names})`,
894
- variant: 'success',
895
- duration: 4000,
896
- category: 'delegations',
897
- dedupeKey: `olympians-complete|${olympians.id}`,
898
- })
899
- }
900
-
901
- /**
902
- * ⚠️ agent-failed toast (severity priority — category 'errors', individual,
903
- * exempt from throttle and aggregation). Fired when the tool result carries
904
- * failure evidence. Never deduped: every failure surfaces.
905
- */
906
- async function agentFailedToast(
907
- ctx: HookContext,
908
- agent: string,
909
- result: ToolExecuteAfterResult | null,
910
- ): Promise<void> {
911
- const raw = result?.output ?? result?.title ?? ''
912
- // Fix 1: the failure reason echoes tool RESULT content — mask any token so
913
- // the toast/hooks.log trail never exposes a raw secret.
914
- const reason = maskSecret(
915
- trim(typeof raw === 'string' && raw.trim() !== '' ? raw : 'tool failed', 120),
916
- )
917
- await notifyToast(ctx, {
918
- title: 'Delegação',
919
- message: `⚠️ ${agent} falhou: ${reason}`,
920
- variant: 'error',
921
- duration: 5000,
922
- category: 'errors',
923
- })
924
- }
925
-
926
- /**
927
- * GAP C (2026-08-06): ⚠️ bash-command-failed notification (severity priority
928
- * — category 'errors', individual, exempt from the 2s throttle and from
929
- * aggregation, never deduped). Fired when the bash tool result reports a
930
- * non-zero exit code; exit 0 → silent. The exit-code signal is
931
- * `metadata.exit` on the after-hook result — empirically verified against the
932
- * installed opencode 1.18.14 binary: the shell tool returns
933
- * {title, output, metadata: {output, exit, truncated}} where `exit` is the
934
- * real process exit code (number, or null on timeout/abort). Fix 1: the
935
- * reason echoes tool RESULT content — mask any token so the trail never
936
- * exposes a raw secret.
937
- */
938
- async function bashFailedToast(
939
- ctx: HookContext,
940
- exitCode: number | null,
941
- result: ToolExecuteAfterResult | null,
942
- ): Promise<void> {
943
- const raw = result?.output ?? result?.title ?? ''
944
- const firstLine = typeof raw === 'string' ? (raw.split('\n')[0] ?? '').trim() : ''
945
- const reason = maskSecret(trim(firstLine, 100))
946
- await notifyToast(ctx, {
947
- title: 'Comando',
948
- message:
949
- exitCode !== null
950
- ? `⚠️ comando falhou: exit ${exitCode}${reason !== '' ? ` — ${reason}` : ''}`
951
- : `⚠️ comando falhou${reason !== '' ? `: ${reason}` : ''}`,
952
- variant: 'error',
953
- duration: 5000,
954
- category: 'errors',
955
- })
956
- }
957
-
958
- /**
959
- * Olympians-aware delegation start. Returns nothing; side effects:
960
- * - 1st task of a window → starts a group buffer + fires the individual 🚀
961
- * - 2nd+ task within the window → joins the group; the 2nd call fires the
962
- * single ⚙️ olympians notification (later members only update the buffer)
963
- */
964
- function onDelegationStart(ctx: HookContext, agent: string): void {
965
- const now = Date.now()
966
- if (activeOlympians !== null && now - activeOlympians.lastTaskAt <= OLYMPIANS_DETECT_WINDOW_MS) {
967
- activeOlympians.lastTaskAt = now
968
- activeOlympians.agents.add(agent)
969
- activeOlympians.pendingCompletions.add(agent)
970
- if (activeOlympians.agents.size === 2) {
971
- activeOlympians.detected = true
972
- void notifyOlympiansStarted(ctx, activeOlympians)
973
- }
974
- // No individual 🚀 toast for 2nd+ members — the group notification covers them.
975
- return
976
- }
977
- activeOlympians = {
978
- id: `olympians-${now}-${++olympiansSeq}`,
979
- agents: new Set([agent]),
980
- startedAt: now,
981
- lastTaskAt: now,
982
- pendingCompletions: new Set([agent]),
983
- doneCount: 0,
984
- detected: false,
985
- }
986
- void delegationStartedToast(ctx, agent)
987
- }
988
-
989
- /**
990
- * Olympians-aware delegation completion. Returns true when the completion was
991
- * consumed by the group (its individual ✅ is suppressed in favor of the group
992
- * aggregate); false when the agent is not part of a detected group and should
993
- * fall through to the normal 3-in-6s / individual completion toast. Also
994
- * invoked for FAILED members (severity): the failure toast fires separately
995
- * and the member still counts as done for the group summary.
996
- */
997
- function handleOlympiansCompletion(ctx: HookContext, agent: string): boolean {
998
- if (activeOlympians === null || !activeOlympians.agents.has(agent)) return false
999
- if (activeOlympians.pendingCompletions.has(agent)) {
1000
- activeOlympians.doneCount++
1001
- activeOlympians.pendingCompletions.delete(agent)
1002
- }
1003
- if (!activeOlympians.detected) {
1004
- // Never became a real group (only this agent) — release and fall through.
1005
- activeOlympians = null
1006
- return false
1007
- }
1008
- if (activeOlympians.doneCount >= activeOlympians.agents.size) {
1009
- void notifyOlympiansComplete(ctx, activeOlympians)
1010
- activeOlympians = null
1011
- }
1012
- return true
1013
- }
1014
-
1015
- /** Conservative council detection: description/prompt mentions council terms. */
1016
- function isCouncilTask(tool: string, args?: unknown): boolean {
1017
- if (!DELEGATION_TOOL_RE.test(tool)) return false
1018
- try {
1019
- const a = (args ?? {}) as Record<string, unknown>
1020
- const text = [a.prompt, a.description, a.task, a.taskDesc, a.detail]
1021
- .filter((x): x is string => typeof x === 'string')
1022
- .join(' ')
1023
- return COUNCIL_RE.test(text)
1024
- } catch {
1025
- // Malformed args — not a council task.
1026
- return false
1027
- }
1028
- }
1029
-
1030
- /** 🏛️ council-started notification — fires once per council (category 'council'). */
1031
- function onCouncilStart(ctx: HookContext): void {
1032
- councilDispatchCount++
1033
- if (councilStartNotified) return
1034
- councilStartNotified = true
1035
- void notifyToast(ctx, {
1036
- title: 'Council',
1037
- message: '🏛️ Council: especialistas consultados',
1038
- variant: 'info',
1039
- duration: 3500,
1040
- category: 'council',
1041
- })
1042
- }
1043
-
1044
- /** ✅ council verdict notification — fires once all dispatched specialists finished. */
1045
- function onCouncilDone(ctx: HookContext): void {
1046
- councilDoneCount++
1047
- if (councilDispatchCount > 0 && councilDoneCount >= councilDispatchCount) {
1048
- void notifyToast(ctx, {
1049
- title: 'Council',
1050
- message: '✅ Veredito pronto',
1051
- variant: 'success',
1052
- duration: 4000,
1053
- category: 'council',
1054
- })
1055
- // Reset so a subsequent council session starts fresh (verdicts never re-fire).
1056
- councilDispatchCount = 0
1057
- councilDoneCount = 0
1058
- councilStartNotified = false
1059
- pendingCouncilCalls.clear()
1060
- }
1061
- }
1062
-
1063
- function flushIdleReminders(ctx: HookContext): void {
1064
- activeOlympians = null
1065
-
1066
- // Interrupted council counters must not block a later council's verdict —
1067
- // but ONLY when no council specialist is still running. Synchronous
1068
- // councils finish specialists at different times (nyx ~11s / prometheus
1069
- // ~21s / themis ~38s): session.idle fires mid-flight, so resetting here
1070
- // would drop the "✅ Veredito pronto" toast. Skip the reset while
1071
- // pendingCouncilCalls is non-empty — onCouncilDone resets on the verdict.
1072
- if (pendingCouncilCalls.size === 0) {
1073
- councilDispatchCount = 0
1074
- councilDoneCount = 0
1075
- councilStartNotified = false
1076
- }
1077
-
1078
- void reportFailure(
1079
- ctx,
1080
- '[pantheon-hooks:idle-flush] delegation state reset',
1081
- {
1082
- script: 'idle-flush',
1083
- },
1084
- 'info',
1085
- )
1086
- }
1087
-
1088
- /**
1089
- * Run one hook with the logging policy; NEVER throw out of the hook.
1090
- *
1091
- * Non-zero exit → structured log + hooks.log + one deduped TUI toast.
1092
- * Zero exit → silent, unless PANTHEON_HOOKS_LOG is set for audit scripts
1093
- * (echo routed to structured log + hooks.log, never the TUI).
1094
- * No console.error / console.log anywhere in this path — the TUI stays clean.
1095
- *
1096
- * Returns the underlying HookResult (or null on unexpected failure) so the
1097
- * tool.execute.before handler can inspect scan-secrets.sh's exit code for the
1098
- * Fix-2 hybrid block (code 2 = high-confidence token → throw after logging).
1099
- */
1100
- async function safeRun(
1101
- ctx: HookContext,
1102
- script: string,
1103
- payload: HookPayload,
1104
- ): Promise<HookResult | null> {
1105
- try {
1106
- const result = await runHook(script, payload)
1107
- const tag = `[pantheon-hooks:${script}]`
1108
- const extra = { script, code: result.code, timedOut: result.timedOut, tool: payload.tool_name }
1109
- if (result.code !== 0) {
1110
- // Fix 1: maskSecret() defense-in-depth — script stderr is normally
1111
- // already masked by the .sh scripts, but the hook trail must never
1112
- // echo a raw token even if a future script regresses.
1113
- const message = `${tag} exit ${result.code}${result.timedOut ? ' (timed out)' : ''}: ${maskSecret(trim(result.stderr || result.stdout || 'no output'))}`
1114
- await reportFailure(ctx, message, extra)
1115
- const match = maskSecret(trim(result.stderr || result.stdout || 'no output', 120))
1116
- const suffix = result.timedOut ? ' (timeout)' : ''
1117
- void notifyToast(ctx, {
1118
- title: 'Pantheon Hook',
1119
- message: `⚠️ Hook ${script}: exit ${result.code}${suffix} — see log`,
1120
- variant: 'error',
1121
- duration: 4000,
1122
- category: 'errors',
1123
- dedupeKey: `${script}|${result.code}|${match}`,
1124
- })
1125
- } else if (AUDIT_LOG_ENABLED && AUDIT_HOOKS.has(script) && result.stderr.trim()) {
1126
- // Opt-in only (PANTHEON_HOOKS_LOG=1): audit scripts echo their FILE
1127
- // writes here for debugging. Default is silence — the .sh scripts
1128
- // already persist sessions.log / delegations.log on disk. Echo goes to
1129
- // the structured log + hooks.log, never the TUI console.
1130
- const message = `${tag} ${maskSecret(trim(result.stderr))}`
1131
- await reportFailure(ctx, message, extra, 'info')
1132
- }
1133
- return result
1134
- } catch (err) {
1135
- // runHook never throws, but the hook body must survive anything.
1136
- const message = `[pantheon-hooks:${script}] unexpected failure: ${maskSecret(err instanceof Error ? err.message : String(err))}`
1137
- try {
1138
- await ctx.client.app.log({
1139
- body: {
1140
- service: 'pantheon-hooks',
1141
- level: 'error',
1142
- message,
1143
- extra: { script, tool: payload.tool_name },
1144
- },
1145
- })
1146
- } catch {
1147
- // Best-effort; never throw out of the hook.
1148
- }
1149
- try {
1150
- await appendHookLog(ctx.directory, message)
1151
- } catch {
1152
- // Best-effort; never throw out of the hook.
1153
- }
1154
- return null
1155
- }
1156
- }
1157
-
1158
- const plugin: Plugin = async ({ client, directory }) => {
1159
- // release-134: runtime guard against DOUBLE registration (duplicate toasts +
1160
- // duplicate task_ids in one process — 2026-08-12 live logs). opencode
1161
- // merges the global config (npm-package plugin paths) with the project
1162
- // config (repo source paths), so this module loads from TWO filesystem
1163
- // paths in the same process and the factory would otherwise run twice —
1164
- // every lifecycle hook (tool.execute.before/after and event) firing
1165
- // TWICE. The second invocation becomes a no-op (empty hooks object) so
1166
- // hooks register exactly once.
1167
- if (pantheonPluginOnce('pantheon:hooks')) {
1168
- return {}
1169
- }
1170
- const ctx: HookContext = { client, directory }
1171
- return {
1172
- 'tool.execute.before': async (input, output) => {
1173
- // Fix 2 (2026-08-06): the ONLY deliberate throw in this plugin. Set
1174
- // inside the try but thrown AFTER it — every log channel (safeRun's
1175
- // reportFailure + the explicit block reportFailure below) is awaited
1176
- // BEFORE the throw, and the throw is not swallowed by the hook's
1177
- // catch: opencode propagates the rejection to fail the tool call.
1178
- let blockError: Error | null = null
1179
- try {
1180
- const hooks = ['validate-talos-scope.sh', 'scan-secrets.sh', 'validate-tool-safety.sh']
1181
- // P0-2: the delegation record must exist BEFORE the payload is built
1182
- // so the start hook receives the delegation_id the stop hook joins on.
1183
- let payload = payloadFor(input, output?.args ?? {})
1184
- if (DELEGATION_TOOL_RE.test(input.tool)) {
1185
- hooks.push('on-subagent-delegation-start.sh')
1186
- // tool.execute.before carries args on `output` (typed); `input.args`
1187
- // also exists at runtime — read from whichever is present.
1188
- const args = output?.args ?? (input as { args?: unknown }).args
1189
- const start: DelegationStart = {
1190
- delegation_id: crypto.randomUUID(),
1191
- agent: delegationAgent(input.tool, args),
1192
- startedAt: Date.now(),
1193
- }
1194
- delegationStarts.set(input.callID, start)
1195
- pruneDelegationStarts(start.startedAt)
1196
- // P0-1: agent_id + delegation_id ride on the payload — the stop
1197
- // hook resolves its agent from the START record, never from
1198
- // after-time args that may carry the merged background result.
1199
- payload = payloadFor(input, args, {
1200
- agent_id: start.agent,
1201
- delegation_id: start.delegation_id,
1202
- })
1203
- if (isCouncilTask(input.tool, args)) {
1204
- // Track by callID — the after-hook args do NOT repeat the
1205
- // council description, so completion is matched via this set.
1206
- pendingCouncilCalls.add(input.callID)
1207
- onCouncilStart(ctx)
1208
- }
1209
- onDelegationStart(ctx, start.agent)
1210
- }
1211
- // P2 (2026-08-06): talos-guard is restricted to WRITE-INTENT operations
1212
- // — edit/write/patch, or bash with a write operator (>, >>, mv, cp, rm,
1213
- // sed -i, tee, git commit/push). Read-only find/grep must NEVER trigger
1214
- // (they legitimately match RISKY_PATH_RE, e.g. grepping for 'auth').
1215
- // Advisory only, never blocks, never throws.
1216
- const guardArgs = (output?.args ?? (input as { args?: unknown }).args ?? {}) as Record<
1217
- string,
1218
- unknown
1219
- >
1220
- const rawCommand = guardArgs.command ?? guardArgs.cmd
1221
- const bashCommand = typeof rawCommand === 'string' ? rawCommand : ''
1222
- const isWriteIntent =
1223
- WRITE_INTENT_TOOLS.has(input.tool) ||
1224
- (input.tool === 'bash' && BASH_WRITE_INTENT_RE.test(bashCommand))
1225
- if (isWriteIntent) {
1226
- try {
1227
- const values: string[] = []
1228
- const scan = (v: unknown): void => {
1229
- if (typeof v === 'string') values.push(v)
1230
- else if (Array.isArray(v)) v.forEach(scan)
1231
- else if (v !== null && typeof v === 'object') {
1232
- for (const x of Object.values(v)) scan(x)
1233
- }
1234
- }
1235
- scan(guardArgs)
1236
- let hit: string | null = null
1237
- for (const v of values) {
1238
- if (RISKY_PATH_RE.test(v)) {
1239
- hit = v
1240
- break
1241
- }
1242
- }
1243
- if (hit !== null) {
1244
- // Fix 1: NEVER log the raw matched value — a real secret in a
1245
- // write-intent arg (e.g. bash `old_token = "sk-bf-..."`) leaked
1246
- // in plain text to hooks.log on 2026-08-06. maskSecret() keeps
1247
- // only the tool name + masked path/arg context + signal count.
1248
- void reportFailure(
1249
- ctx,
1250
- `[talos-guard] ⚠️ Operação em área sensível: ${maskSecret(hit.slice(0, 160))}`,
1251
- { script: 'talos-guard', tool: input.tool, category: 'errors' },
1252
- 'warn',
1253
- )
1254
- } else {
1255
- const uniqueFiles = new Set(
1256
- values.filter((v) => v.includes('/') && /(^|\/)[^/\s]+\.[a-z0-9]+$/i.test(v)),
1257
- )
1258
- if (uniqueFiles.size > 3) {
1259
- void reportFailure(
1260
- ctx,
1261
- `[talos-guard] ⚠️ Operação multi-arquivo: ${uniqueFiles.size} arquivos`,
1262
- {
1263
- script: 'talos-guard',
1264
- tool: input.tool,
1265
- category: 'errors',
1266
- count: uniqueFiles.size,
1267
- },
1268
- 'warn',
1269
- )
1270
- }
1271
- }
1272
- } catch {
1273
- // Advisory only — a failure here must never take down the hook.
1274
- }
1275
- }
1276
- // Fix 2 hybrid blocking: safeRun returns each script's HookResult;
1277
- // scan-secrets.sh exits 2 on HIGH_CONFIDENCE token matches
1278
- // (sk-bf-*, AKIA..., ghp_..., glpat-..., JWT, bearer...) → BLOCK the
1279
- // tool call. Exit 1 (low-confidence header/KEY names) stays advisory
1280
- // — safeRun already logged + toasted it, no block. The toast for
1281
- // code 1/2 fires inside safeRun BEFORE we reach the throw, and the
1282
- // reportFailure below is awaited first — log channels always write.
1283
- const results = await Promise.all(
1284
- hooks.map(async (script) => ({ script, result: await safeRun(ctx, script, payload) })),
1285
- )
1286
- const scan = results.find((r) => r.script === 'scan-secrets.sh')
1287
- if (scan?.result?.code === 2) {
1288
- await reportFailure(
1289
- ctx,
1290
- SECRET_BLOCK_MESSAGE,
1291
- { script: 'scan-secrets', tool: input.tool, blocked: true, code: 2 },
1292
- 'error',
1293
- )
1294
- blockError = new Error(SECRET_BLOCK_MESSAGE)
1295
- }
1296
- } catch {
1297
- // Never let a hook take down the opencode session — except the
1298
- // deliberate high-confidence block thrown below.
1299
- }
1300
- if (blockError !== null) throw blockError
1301
- },
1302
- 'tool.execute.after': async (input, output) => {
1303
- try {
1304
- const args = (input as { args?: unknown }).args ?? {}
1305
- // P1-1 fix: `output` is the REAL tool result ({title, output,
1306
- // metadata}). P0-1/P0-2: the lifecycle fields (agent, delegation_id,
1307
- // task_id, status, duration_ms) are derived from the before-record +
1308
- // result — never from result text blobs.
1309
- const result: ToolExecuteAfterResult | null = output ?? null
1310
- // GAP C (2026-08-06): monitor command-runner exit codes. Signal used:
1311
- // `metadata.exit` on the after-hook result — empirically verified
1312
- // against the installed opencode 1.18.14 binary (the shell tool
1313
- // returns {title, output, metadata: {output, exit, truncated}}). The
1314
- // exit code is a real number; non-zero → individual error
1315
- // notification (severity priority — never throttled/aggregated);
1316
- // exit 0 → silent. Fallback for custom runners where `exit` is
1317
- // absent: strong failure markers in the output trigger the same
1318
- // notification (documented signal: marker match).
1319
- if (input.tool === 'bash' && result !== null) {
1320
- let exitCode: number | null = null
1321
- if (result.metadata !== null && typeof result.metadata === 'object') {
1322
- const m = result.metadata as Record<string, unknown>
1323
- if (typeof m.exit === 'number') exitCode = m.exit
1324
- }
1325
- if (exitCode !== null && exitCode !== 0) {
1326
- void bashFailedToast(ctx, exitCode, result)
1327
- } else if (
1328
- exitCode === null &&
1329
- typeof result.output === 'string' &&
1330
- RESULT_FAILURE_MARKERS.test(result.output)
1331
- ) {
1332
- void bashFailedToast(ctx, null, result)
1333
- }
1334
- }
1335
- let payload = afterPayloadFor(input, args, result)
1336
- const hooks = ['format-multi-language.sh']
1337
- if (DELEGATION_TOOL_RE.test(input.tool)) {
1338
- hooks.push('on-subagent-delegation-stop.sh')
1339
- const start = delegationStarts.get(input.callID)
1340
- // P0-1: agent comes from the START record (before-time args are
1341
- // clean); the after-hook args may hold the MERGED background result
1342
- // {task_id, state} with no subagent_type — never derive from those.
1343
- const agent = start?.agent ?? delegationAgent(input.tool, args)
1344
- const resultStatus = deriveResultStatus(result)
1345
- if (start !== undefined) {
1346
- payload = afterPayloadFor(input, args, result, start)
1347
- delegationStarts.delete(input.callID)
1348
- }
1349
- // Severity (c): agent failures notify individually — never
1350
- // throttled, never aggregated. Success/completion aggregates.
1351
- if (resultStatus === 'failure') {
1352
- void agentFailedToast(ctx, agent, result)
1353
- void handleOlympiansCompletion(ctx, agent)
1354
- } else if (resultStatus === 'dispatched') {
1355
- // P0-1: BACKGROUND launch — tool.execute.after fires at dispatch
1356
- // (the task tool returns {task_id, state:'running'} immediately).
1357
- // NOT a completion: do not mark the group done and do not fire ✅
1358
- // — that would corrupt olympians aggregation. Real completion of
1359
- // background tasks is unobservable on 1.18.13 (see header).
1360
- // beta.5: mirror the native background child onto the SHARED
1361
- // board so the existing finalize path (session.idle + idle scan
1362
- // in plugin.ts) writes the terminal report and the TUI
1363
- // delegation panel tracks the child end-to-end. Fire-and-forget.
1364
- mirrorNativeBackgroundDispatch(input, args, result)
1365
- } else {
1366
- const handledByOlympians = handleOlympiansCompletion(ctx, agent)
1367
- if (!handledByOlympians) void delegationDoneToast(ctx, agent)
1368
- }
1369
- if (pendingCouncilCalls.delete(input.callID)) onCouncilDone(ctx)
1370
- }
1371
- await Promise.all(hooks.map((script) => safeRun(ctx, script, payload)))
1372
- } catch {
1373
- // Never let a hook take down the opencode session.
1374
- }
1375
- },
1376
- // P0-4 session→agent map: fires per assistant turn with the active agent
1377
- // name — record it so tool.execute hooks can resolve agent_id for
1378
- // validate-talos-scope.sh. 'title' (session-title turns) is ignored.
1379
- // Bounded: prunes entries older than 30min once the map exceeds 50.
1380
- 'chat.params': async (input) => {
1381
- try {
1382
- if (input.agent && input.agent !== 'title') {
1383
- sessionAgent.set(input.sessionID, { agent: input.agent, at: Date.now() })
1384
- if (sessionAgent.size > 50) {
1385
- const cutoff = Date.now() - 30 * 60 * 1000
1386
- for (const [k, v] of sessionAgent) {
1387
- if (v.at < cutoff) sessionAgent.delete(k)
1388
- }
1389
- }
1390
- }
1391
- } catch {
1392
- // Never let a hook take down the opencode session.
1393
- }
1394
- },
1395
- event: async ({ event: ev }) => {
1396
- try {
1397
- if (ev.type === 'session.created') {
1398
- const payload: HookPayload = { session_id: ev.properties.info.id }
1399
- await Promise.all(
1400
- ['log-session-start.sh', 'validate-post-conditions.sh'].map((script) =>
1401
- safeRun(ctx, script, payload),
1402
- ),
1403
- )
1404
- } else if (ev.type === 'session.idle') {
1405
- // Primary flush trigger for pending completion reminders (see header).
1406
- flushIdleReminders(ctx)
1407
- } else if (ev.type === 'session.error') {
1408
- // Severity (c): any ❌/⚠️ event notifies individually, never
1409
- // aggregated or throttled.
1410
- const err: unknown = ev.properties.error
1411
- const msg =
1412
- typeof err === 'object' &&
1413
- err !== null &&
1414
- 'message' in err &&
1415
- typeof (err as { message: unknown }).message === 'string'
1416
- ? String((err as { message: string }).message)
1417
- : 'session error'
1418
- void notifyToast(ctx, {
1419
- title: 'Pantheon',
1420
- message: `❌ ${trim(msg, 120)}`,
1421
- variant: 'error',
1422
- duration: 5000,
1423
- category: 'errors',
1424
- })
1425
- }
1426
- } catch {
1427
- // Never let a hook take down the opencode session.
1428
- }
1429
- },
1430
- }
1431
- }
1432
-
1433
- export default plugin