pantheon-opencode 1.6.2-beta.1 → 1.6.2-beta.10

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 (144) hide show
  1. package/CHANGELOG.md +163 -0
  2. package/README.md +236 -60
  3. package/README.pt-BR.md +19 -1
  4. package/bin/pantheon-init.mjs +195 -13
  5. package/package.json +11 -3
  6. package/plugin.json +1 -1
  7. package/prompts/README.md +58 -0
  8. package/prompts/debug-issue.prompt.md +46 -0
  9. package/prompts/dynamic/agora-generated.txt +38 -0
  10. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  11. package/prompts/focus.prompt.md +42 -0
  12. package/prompts/implement-feature.prompt.md +39 -0
  13. package/prompts/optimize-database.prompt.md +58 -0
  14. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  15. package/prompts/plan-architecture.prompt.md +59 -0
  16. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  17. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  18. package/prompts/semantic-summarize.md +50 -0
  19. package/prompts/sketch.prompt.md +91 -0
  20. package/prompts/subtask.prompt.md +131 -0
  21. package/pyproject.toml +1 -1
  22. package/scripts/decision-router-budget.mjs +780 -0
  23. package/scripts/decision-router-v2-budget.mjs +218 -0
  24. package/scripts/decision-router-v2-egress.mjs +272 -0
  25. package/scripts/decision-router.mjs +758 -0
  26. package/scripts/docs-check-changelog.mjs +5 -3
  27. package/scripts/install/component-selection.mjs +9 -4
  28. package/scripts/install/decision-layer-preview.mjs +376 -0
  29. package/scripts/install/decision-router-config.mjs +560 -0
  30. package/scripts/install/health-check.mjs +20 -11
  31. package/scripts/install/interactive.mjs +103 -14
  32. package/scripts/install/interrupt.mjs +4 -3
  33. package/scripts/install/migrate.mjs +123 -72
  34. package/scripts/install/opencode.mjs +178 -122
  35. package/scripts/install/plan.mjs +8 -1
  36. package/scripts/install/plugin.mjs +4 -3
  37. package/scripts/install/state.mjs +12 -0
  38. package/scripts/install/strings.mjs +22 -0
  39. package/scripts/install/venv.mjs +34 -17
  40. package/scripts/mcp_resources.py +11 -9
  41. package/scripts/release-notes.mjs +30 -7
  42. package/scripts/restore.mjs +22 -10
  43. package/scripts/sync-tui.mjs +3 -3
  44. package/scripts/test-opencode-v2-sandbox.sh +10 -6
  45. package/scripts/versioning.mjs +41 -5
  46. package/src/agents/aphrodite.md +6 -1
  47. package/src/agents/apollo.md +1 -0
  48. package/src/agents/athena.md +1 -0
  49. package/src/agents/demeter.md +1 -1
  50. package/src/agents/gaia.md +1 -0
  51. package/src/agents/hephaestus.md +1 -1
  52. package/src/agents/hermes.md +8 -10
  53. package/src/agents/iris.md +1 -1
  54. package/src/agents/mnemosyne.md +1 -0
  55. package/src/agents/nyx.md +1 -1
  56. package/src/agents/prometheus.md +1 -1
  57. package/src/agents/talos.md +6 -1
  58. package/src/agents/themis.md +1 -1
  59. package/src/agents/zeus.md +52 -62
  60. package/src/mcp/eval_store.py +11 -4
  61. package/src/mcp/mcp_resources.py +11 -9
  62. package/src/mcp/memory_mcp.py +293 -150
  63. package/src/pantheon/cost-command.ts +30 -133
  64. package/src/pantheon/jev-decision-tool.ts +347 -0
  65. package/src/pantheon/jev-decisions.ts +625 -0
  66. package/src/pantheon/local-decision-agents.ts +170 -0
  67. package/src/pantheon/local-decision-budget.ts +1046 -0
  68. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  69. package/src/pantheon/local-decision-prompt.ts +256 -0
  70. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  71. package/src/pantheon/local-decision-router.ts +225 -0
  72. package/src/pantheon/local-decision-skills.ts +281 -0
  73. package/src/pantheon/local-decision-tool.ts +160 -0
  74. package/src/pantheon/local-decision-turn.ts +101 -0
  75. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  76. package/src/pantheon/local-orchestration.ts +322 -0
  77. package/src/pantheon/model-pricing.ts +1 -536
  78. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  79. package/src/pantheon/v2-decision-budget.ts +456 -0
  80. package/src/pantheon/v2-decision-contracts.ts +300 -0
  81. package/src/pantheon/v2-decision-egress.ts +203 -0
  82. package/src/pantheon/v2-decision-events.ts +180 -0
  83. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  84. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  85. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  86. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  87. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  88. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  89. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  90. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  91. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  92. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  93. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  94. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  95. package/src/pantheon/v2-decision-points.ts +242 -0
  96. package/src/pantheon/v2-decision-policy.ts +166 -0
  97. package/src/pantheon/v2-decision-premises.ts +146 -0
  98. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  99. package/src/pantheon/v2-decision-rank.ts +91 -0
  100. package/src/pantheon/v2-decision-registry.ts +391 -0
  101. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  102. package/src/pantheon/v2-decision-shadow.ts +123 -0
  103. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  104. package/src/pantheon/v2-decision-verify.ts +51 -0
  105. package/src/pantheon/v2-hook-engine.ts +307 -0
  106. package/src/pantheon/v2-native-decisions.ts +365 -0
  107. package/src/pantheon/v2-shell-hooks.ts +66 -2
  108. package/src/pantheon/v2-tools.ts +38 -15
  109. package/src/plugin-v2.ts +419 -26
  110. package/src/plugin.ts +4 -0
  111. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  112. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  113. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  114. package/src/plugins/tui/dist/server-v2.js +19 -666
  115. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  116. package/src/plugins/tui/dist/tui-v2.d.ts +11 -203
  117. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  118. package/src/plugins/tui/dist/tui-v2.js +187 -1917
  119. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  120. package/src/plugins/tui/dist/tui.js +1 -1
  121. package/src/plugins/tui/package-lock.json +17 -2
  122. package/src/plugins/tui/package.json +4 -2
  123. package/src/plugins/tui/src/cost-data.ts +607 -0
  124. package/src/plugins/tui/src/index-v2.tsx +213 -54
  125. package/src/plugins/tui/src/model-pricing.ts +536 -0
  126. package/src/plugins/tui/src/server-v2.ts +18 -838
  127. package/src/plugins/tui/tsdown.config.ts +28 -6
  128. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  129. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  130. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  131. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  132. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  133. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  134. package/src/plugins/tui/dist/quota-cli.js +0 -184
  135. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  136. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +0 -390
  137. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
  138. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  139. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  140. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  141. package/src/plugins/tui/src/quota-cli.ts +0 -237
  142. package/src/plugins/tui/src/quota-rpc.ts +0 -209
  143. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  144. package/src/plugins/tui/src/quota-v2.tsx +0 -986
@@ -0,0 +1,214 @@
1
+ /**
2
+ * V2 decision telemetry — allowlist sanitisation, closing defect D10.
3
+ *
4
+ * Telemetry must never carry prompt, response, user content, credentials or
5
+ * free-form text. The strongest way to guarantee that is not to scrub known
6
+ * keys but to accept only a small allowlist whose values are constrained to
7
+ * short tokens and bounded numbers:
8
+ *
9
+ * schemaVersion, point, decision, effect, reason, mode, durationMs, candidateCount
10
+ *
11
+ * Any other key is dropped and only a count is reported. Neither the key nor
12
+ * its value is ever copied into the result, so no attacker-controlled string
13
+ * reaches telemetry through a rejection path.
14
+ *
15
+ * `effect` is fixed to `'none'`. An event that claims anything else is rejected
16
+ * outright: this layer has no measured effect to report, and silently rewriting
17
+ * the claim would hide the caller's error.
18
+ *
19
+ * The sink is in-memory and bounded. It performs no I/O, so the offline harness
20
+ * can assert exactly what would be emitted.
21
+ */
22
+
23
+ import type { DecisionPointId } from './v2-decision-registry.ts'
24
+
25
+ export const TELEMETRY_SCHEMA_VERSION = 1
26
+ export const TELEMETRY_FIELDS = [
27
+ 'schemaVersion',
28
+ 'point',
29
+ 'decision',
30
+ 'effect',
31
+ 'reason',
32
+ 'mode',
33
+ 'durationMs',
34
+ 'candidateCount',
35
+ ] as const
36
+
37
+ export type TelemetryField = (typeof TELEMETRY_FIELDS)[number]
38
+ export type TelemetryMode = 'shadow' | 'active' | 'off' | 'migration'
39
+
40
+ export interface DecisionTelemetryEvent {
41
+ readonly schemaVersion: typeof TELEMETRY_SCHEMA_VERSION
42
+ readonly point: DecisionPointId
43
+ readonly decision: string
44
+ readonly effect: 'none'
45
+ readonly reason: string
46
+ readonly mode?: TelemetryMode
47
+ readonly durationMs?: number
48
+ readonly candidateCount?: number
49
+ }
50
+
51
+ export type TelemetryRejection = 'INVALID_INPUT' | 'MISSING_REQUIRED_FIELD' | 'EFFECT_NOT_MEASURED'
52
+
53
+ export type TelemetryResult =
54
+ | {
55
+ readonly ok: true
56
+ readonly event: DecisionTelemetryEvent
57
+ readonly droppedFieldCount: number
58
+ }
59
+ | {
60
+ readonly ok: false
61
+ readonly reasonCode: TelemetryRejection
62
+ readonly droppedFieldCount: number
63
+ }
64
+
65
+ const TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/
66
+ const POINT_ID = /^P(?:[1-9]|1[01])$/
67
+ const TELEMETRY_KEYS: ReadonlySet<string> = new Set(TELEMETRY_FIELDS)
68
+ const MODES: ReadonlySet<string> = new Set(['shadow', 'active', 'off', 'migration'])
69
+ const DURATION_MAX_MS = 60_000
70
+ const CANDIDATE_MAX = 10_000
71
+ function isRecord(value: unknown): value is Record<string, unknown> {
72
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
73
+ }
74
+
75
+ function isToken(value: unknown): value is string {
76
+ return typeof value === 'string' && TOKEN.test(value)
77
+ }
78
+
79
+ function isPointId(value: unknown): value is DecisionPointId {
80
+ return typeof value === 'string' && POINT_ID.test(value)
81
+ }
82
+
83
+ function rejected(reasonCode: TelemetryRejection, droppedFieldCount: number): TelemetryResult {
84
+ return { ok: false, reasonCode, droppedFieldCount }
85
+ }
86
+
87
+ /**
88
+ * Reduce an arbitrary record to the telemetry allowlist.
89
+ *
90
+ * Required survivors: `point`, `decision` and `reason`. `effect`, when present,
91
+ * must already be `'none'`; the output always carries `'none'`.
92
+ */
93
+ export function sanitizeTelemetry(input: unknown): TelemetryResult {
94
+ if (!isRecord(input)) return rejected('INVALID_INPUT', 0)
95
+
96
+ let droppedFieldCount = 0
97
+ const drop = (): void => {
98
+ droppedFieldCount += 1
99
+ }
100
+
101
+ let point: DecisionPointId | null = null
102
+ let decision: string | null = null
103
+ let reason: string | null = null
104
+ let mode: TelemetryMode | null = null
105
+ let durationMs: number | null = null
106
+ let candidateCount: number | null = null
107
+ let effectNotMeasured = false
108
+
109
+ for (const key of Object.keys(input).sort()) {
110
+ const value = input[key]
111
+ if (!TELEMETRY_KEYS.has(key)) {
112
+ drop()
113
+ continue
114
+ }
115
+ switch (key) {
116
+ case 'schemaVersion':
117
+ if (value !== TELEMETRY_SCHEMA_VERSION) drop()
118
+ break
119
+ case 'point':
120
+ if (isPointId(value)) point = value
121
+ else drop()
122
+ break
123
+ case 'decision':
124
+ if (isToken(value)) decision = value
125
+ else drop()
126
+ break
127
+ case 'reason':
128
+ if (isToken(value)) reason = value
129
+ else drop()
130
+ break
131
+ case 'mode':
132
+ if (typeof value === 'string' && MODES.has(value)) {
133
+ mode = value as TelemetryMode
134
+ } else {
135
+ drop()
136
+ }
137
+ break
138
+ case 'durationMs':
139
+ if (
140
+ typeof value === 'number' &&
141
+ Number.isFinite(value) &&
142
+ value >= 0 &&
143
+ value <= DURATION_MAX_MS
144
+ ) {
145
+ durationMs = value
146
+ } else {
147
+ drop()
148
+ }
149
+ break
150
+ case 'candidateCount':
151
+ if (
152
+ Number.isInteger(value) &&
153
+ (value as number) >= 0 &&
154
+ (value as number) <= CANDIDATE_MAX
155
+ ) {
156
+ candidateCount = value as number
157
+ } else {
158
+ drop()
159
+ }
160
+ break
161
+ case 'effect':
162
+ if (value === 'none') break
163
+ effectNotMeasured = true
164
+ drop()
165
+ break
166
+ default:
167
+ drop()
168
+ }
169
+ }
170
+
171
+ if (effectNotMeasured) return rejected('EFFECT_NOT_MEASURED', droppedFieldCount)
172
+ if (point === null || decision === null || reason === null) {
173
+ return rejected('MISSING_REQUIRED_FIELD', droppedFieldCount)
174
+ }
175
+
176
+ const event: DecisionTelemetryEvent = {
177
+ schemaVersion: TELEMETRY_SCHEMA_VERSION,
178
+ point,
179
+ decision,
180
+ effect: 'none',
181
+ reason,
182
+ ...(mode !== null ? { mode } : {}),
183
+ ...(durationMs !== null ? { durationMs } : {}),
184
+ ...(candidateCount !== null ? { candidateCount } : {}),
185
+ }
186
+ return { ok: true, event: Object.freeze(event), droppedFieldCount }
187
+ }
188
+
189
+ /** In-memory, bounded telemetry collector. No I/O, no network. */
190
+ export interface TelemetrySink {
191
+ emit(input: unknown): TelemetryResult
192
+ events(): readonly DecisionTelemetryEvent[]
193
+ size(): number
194
+ }
195
+
196
+ export function createTelemetrySink(maxEvents = 1_000): TelemetrySink {
197
+ if (!Number.isInteger(maxEvents) || maxEvents < 0 || maxEvents > 100_000) {
198
+ throw new RangeError('maxEvents must be an integer in 0..100000')
199
+ }
200
+ const collected: DecisionTelemetryEvent[] = []
201
+ return {
202
+ emit(input: unknown) {
203
+ const result = sanitizeTelemetry(input)
204
+ if (result.ok && collected.length < maxEvents) collected.push(result.event)
205
+ return result
206
+ },
207
+ events() {
208
+ return Object.freeze([...collected])
209
+ },
210
+ size() {
211
+ return collected.length
212
+ },
213
+ }
214
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * V2 verification contract — explicit verdicts, never inferred.
3
+ *
4
+ * `failed_to_respond` during mandatory verification is `BLOCK`; during advisory
5
+ * verification it is `FAIL`. Neither is ever `PASS`, and no scalar can stand in
6
+ * for a verdict.
7
+ */
8
+
9
+ export const VERIFY_VERDICTS = ['PASS', 'FAIL', 'BLOCK'] as const
10
+ export type VerifyVerdict = (typeof VERIFY_VERDICTS)[number]
11
+
12
+ export interface VerifyRequirement {
13
+ readonly id: string
14
+ readonly mandatory: boolean
15
+ }
16
+
17
+ export type VerifyReasonCode = 'VERDICT' | 'FAILED_TO_RESPOND' | 'UNRECOGNIZED_VERDICT'
18
+
19
+ export interface VerifyOutcome {
20
+ readonly requirementId: string
21
+ readonly verdict: VerifyVerdict
22
+ readonly reasonCode: VerifyReasonCode
23
+ readonly mandatory: boolean
24
+ }
25
+
26
+ /**
27
+ * Resolve a verification verdict.
28
+ *
29
+ * The verdict must be stated explicitly. `failed_to_respond` during a
30
+ * mandatory verification is `BLOCK`; during an advisory verification it is
31
+ * `FAIL`. Neither case is ever `PASS`, and no certainty scalar can stand in
32
+ * for a verdict.
33
+ */
34
+ export function resolveVerify(requirement: VerifyRequirement, response: unknown): VerifyOutcome {
35
+ const base = { requirementId: requirement.id, mandatory: requirement.mandatory }
36
+ if (typeof response === 'string') {
37
+ if (response === 'PASS' || response === 'FAIL' || response === 'BLOCK') {
38
+ return { ...base, verdict: response, reasonCode: 'VERDICT' }
39
+ }
40
+ return {
41
+ ...base,
42
+ verdict: requirement.mandatory ? 'BLOCK' : 'FAIL',
43
+ reasonCode: 'UNRECOGNIZED_VERDICT',
44
+ }
45
+ }
46
+ return {
47
+ ...base,
48
+ verdict: requirement.mandatory ? 'BLOCK' : 'FAIL',
49
+ reasonCode: 'FAILED_TO_RESPOND',
50
+ }
51
+ }
@@ -0,0 +1,307 @@
1
+ /**
2
+ * In-process replacements for the three bash hooks the V2 tool guards used to
3
+ * spawn per tool call (`scan-secrets.sh`, `on-subagent-delegation-start.sh`,
4
+ * `on-subagent-delegation-stop.sh`).
5
+ *
6
+ * Why: the shell path cost one `bash` spawn per tool call plus two more per
7
+ * delegation (each of those also spawning `python3` to derive JSON fields), on
8
+ * the hot path of every tool execution. The logic is pure string processing —
9
+ * pattern matching and log-line formatting — so it runs in this process with
10
+ * identical observable behavior: same exit-code contract (0 allow / 1 advisory
11
+ * / 2 block), same masked `[SECRET SCAN]` trail, same `delegations.log`
12
+ * JSON lines, same LOG_DIR resolution order.
13
+ *
14
+ * What deliberately does NOT move here: `format-multi-language.sh` still
15
+ * spawns when it can actually format (it shells out to formatters itself);
16
+ * the in-process gate only skips the spawn for tool calls the script would
17
+ * no-op anyway. `HOOK_TIMEOUT_MS` does not apply — these functions are
18
+ * synchronous and bounded by the payload size, not by a child process.
19
+ *
20
+ * Fail-closed parity: an in-process scanner has no "missing script" failure,
21
+ * but an unexpected internal error still refuses to produce a trustworthy
22
+ * verdict — it returns exit-code 1 WITHOUT the `[SECRET SCAN]` marker, which
23
+ * the existing classifier (plugin-v2 `evaluateSecretScanResult`) reads as
24
+ * fail-closed, exactly as a broken child path always did.
25
+ *
26
+ * @module pantheon/v2-hook-engine
27
+ */
28
+ import { appendFileSync, mkdirSync } from 'node:fs'
29
+ import { join } from 'node:path'
30
+ import type { HookPayload, HookResult } from '../plugins/hook-runner.ts'
31
+
32
+ /** Mirrors the scanner trail marker the classifier keys the advisory on. */
33
+ export const SECRET_SCAN_MARKER = '[SECRET SCAN]'
34
+
35
+ // Provider-specific markers are assembled at runtime so this scanner is not
36
+ // self-matched by the repository secret scan (the shell script's own trick).
37
+ const BIFROST_TOKEN_PREFIX = `${'sk'}${'-bf-'}`
38
+ const BIFROST_HEADER_NAME = `${'x'}${'-bf-'}${'vk'}`
39
+
40
+ /**
41
+ * High-confidence token formats. MIRRORS `HIGH_CONFIDENCE_PATTERNS` in
42
+ * scripts/hooks/scan-secrets.sh and `SECRET_MASK_RE` in src/plugin-v2.ts
43
+ * (V2 log masking); the drift is asserted by tests.
44
+ */
45
+ const HIGH_CONFIDENCE_RES: readonly RegExp[] = Object.freeze([
46
+ /AKIA[0-9A-Z]{16}/i,
47
+ /gh[pousr]_[A-Za-z0-9_]{36,}/i,
48
+ /glpat-[A-Za-z0-9_-]{20}/i,
49
+ /sk-[a-zA-Z0-9]{20,}/i,
50
+ /sk_live_[a-zA-Z0-9]{20,}/i,
51
+ /sk_test_[a-zA-Z0-9]{20,}/i,
52
+ /xox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24}/i,
53
+ /bearer\s+[a-zA-Z0-9_.-]{20,}/i,
54
+ /eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]/,
55
+ ])
56
+ const BIFROST_TOKEN_RE = new RegExp(`${BIFROST_TOKEN_PREFIX}[A-Za-z0-9_-]{8,}`, 'i')
57
+
58
+ /**
59
+ * KEY/header names without a recognizable token value — advisory only, never
60
+ * blocks (the script's LOW_CONFIDENCE_PATTERNS, including the Bifrost header).
61
+ */
62
+ const LOW_CONFIDENCE_RES: readonly RegExp[] = Object.freeze([
63
+ /[a-zA-Z0-9_-]*api[_-]?key[a-zA-Z0-9_-]*\s*[:=]\s*["']?[a-zA-Z0-9_-]{16,}["']?/,
64
+ /[a-zA-Z0-9_-]*password[a-zA-Z0-9_-]*\s*[:=]\s*["'][^"']{8,}["']/,
65
+ /[a-zA-Z0-9_-]*secret[a-zA-Z0-9_-]*\s*[:=]\s*["'][^"']{8,}["']/,
66
+ ])
67
+ const BIFROST_HEADER_RE = new RegExp(BIFROST_HEADER_NAME, 'i')
68
+
69
+ /** First 4 + last 4 chars (len > 8), else '****' — mirrors `mask_secret`. */
70
+ export function maskSecretMatch(match: string): string {
71
+ return match.length <= 8 ? '****' : `${match.slice(0, 4)}****${match.slice(-4)}`
72
+ }
73
+
74
+ function firstMatch(input: string, pattern: RegExp): string | null {
75
+ const found = input.match(pattern)
76
+ return found === null ? null : found[0]
77
+ }
78
+
79
+ /**
80
+ * Known read-only tools: their INPUT cannot carry a secret out of the user's
81
+ * machine (paths, patterns, ids), so scanning them was pure latency. The gate
82
+ * is a DENYLIST — any tool this list has never heard of keeps getting scanned
83
+ * (fail-closed for unknown names).
84
+ */
85
+ const READ_ONLY_TOOLS = new Set([
86
+ 'read',
87
+ 'grep',
88
+ 'glob',
89
+ 'list',
90
+ 'question',
91
+ 'session_list',
92
+ 'session_read',
93
+ 'worktree_list',
94
+ 'subagent_list',
95
+ ])
96
+
97
+ export function secretScanApplies(tool: unknown): boolean {
98
+ if (typeof tool !== 'string') return true
99
+ const normalized = tool.trim().toLowerCase()
100
+ if (normalized === '') return true
101
+ return !READ_ONLY_TOOLS.has(normalized)
102
+ }
103
+
104
+ /** The serialized tool input the shell scanner received as `$1`/stdin. */
105
+ function scannerInput(payload: HookPayload): string {
106
+ if (typeof payload === 'string') return payload
107
+ if (payload === null || payload === undefined) return ''
108
+ const record = payload as Record<string, unknown>
109
+ const input = record.tool_input ?? record.input ?? payload
110
+ if (typeof input === 'string') return input
111
+ try {
112
+ return JSON.stringify(input)
113
+ } catch {
114
+ return ''
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Run the secret scan in-process and return the same {@link HookResult} shape
120
+ * the shell runner produced. Exit 0 → allow; 1 → advisory (marker present);
121
+ * 2 → block. An internal error returns exit 1 WITHOUT the marker, which the
122
+ * classifier maps to fail-closed.
123
+ */
124
+ export function runSecretScanInProcess(payload: HookPayload): HookResult {
125
+ try {
126
+ const input = scannerInput(payload)
127
+ if (input === '') return { code: 0, stdout: '', stderr: '', signal: null, timedOut: false }
128
+
129
+ const stderr: string[] = []
130
+ let high: string | null = null
131
+ for (const pattern of [...HIGH_CONFIDENCE_RES, BIFROST_TOKEN_RE]) {
132
+ const match = firstMatch(input, pattern)
133
+ if (match !== null) {
134
+ stderr.push(
135
+ `${SECRET_SCAN_MARKER} High-confidence secret detected: ${maskSecretMatch(match)} (pattern: ${pattern.source})`,
136
+ )
137
+ high ??= match
138
+ }
139
+ }
140
+ let low = false
141
+ for (const pattern of [...LOW_CONFIDENCE_RES, BIFROST_HEADER_RE]) {
142
+ const match = firstMatch(input, pattern)
143
+ if (match !== null) {
144
+ stderr.push(
145
+ `${SECRET_SCAN_MARKER} Potential secret detected (low confidence): ${maskSecretMatch(match)} (pattern: ${pattern.source})`,
146
+ )
147
+ low = true
148
+ }
149
+ }
150
+
151
+ if (high !== null) {
152
+ stderr.push(
153
+ `${SECRET_SCAN_MARKER} High-confidence hardcoded secret detected. Tool call will be BLOCKED.`,
154
+ )
155
+ return {
156
+ code: 2,
157
+ stdout: '',
158
+ stderr: `${stderr.join('\n')}\n`,
159
+ signal: null,
160
+ timedOut: false,
161
+ }
162
+ }
163
+ if (low) {
164
+ stderr.push(
165
+ `${SECRET_SCAN_MARKER} Possible secret detected. Remove it and use environment variables or a vault.`,
166
+ )
167
+ return {
168
+ code: 1,
169
+ stdout: '',
170
+ stderr: `${stderr.join('\n')}\n`,
171
+ signal: null,
172
+ timedOut: false,
173
+ }
174
+ }
175
+ return { code: 0, stdout: '', stderr: '', signal: null, timedOut: false }
176
+ } catch {
177
+ // Fail-closed: a verdict we cannot trust denies. Exit 1 with no marker.
178
+ return {
179
+ code: 1,
180
+ stdout: '',
181
+ stderr: 'in-process secret scan failed',
182
+ signal: null,
183
+ timedOut: false,
184
+ }
185
+ }
186
+ }
187
+
188
+ // ─── Delegation audit log ───────────────────────────────────────────────
189
+
190
+ /** Same resolution order as the shell scripts' LOG_DIR block. */
191
+ export function resolveDelegationLogDir(
192
+ env: Record<string, string | undefined> = process.env,
193
+ ): string {
194
+ if (env.LOG_DIR) return env.LOG_DIR
195
+ if (env.XDG_STATE_HOME) return join(env.XDG_STATE_HOME, 'pantheon', 'hooks')
196
+ if (env.PANTHEON_HOME) return join(env.PANTHEON_HOME, 'logs', 'agent-sessions')
197
+ if (env.PANTHEON_PROJECT) return join(env.PANTHEON_PROJECT, 'logs', 'agent-sessions')
198
+ return join('logs', 'agent-sessions')
199
+ }
200
+
201
+ function delegationTimestamp(now: number): string {
202
+ return `${new Date(now).toISOString().slice(0, 19)}Z`
203
+ }
204
+
205
+ /** Append one JSON audit line; best-effort, never throws. */
206
+ export function appendDelegationAuditLine(line: Record<string, unknown>): boolean {
207
+ try {
208
+ const dir = resolveDelegationLogDir()
209
+ mkdirSync(dir, { recursive: true })
210
+ appendFileSync(join(dir, 'delegations.log'), `${JSON.stringify(line)}\n`, 'utf8')
211
+ return true
212
+ } catch {
213
+ return false
214
+ }
215
+ }
216
+
217
+ /** Build the `SubagentStart` audit line (same fields as the shell script). */
218
+ export function delegationStartLine(fields: {
219
+ agent: string
220
+ task: string
221
+ sessionID: string
222
+ delegationID: string
223
+ now: number
224
+ }): Record<string, unknown> {
225
+ return {
226
+ event: 'SubagentStart',
227
+ timestamp: delegationTimestamp(fields.now),
228
+ agent: fields.agent,
229
+ task: fields.task === '' ? fields.agent : fields.task,
230
+ session_id: fields.sessionID,
231
+ delegation_id: fields.delegationID,
232
+ }
233
+ }
234
+
235
+ /** Build the `SubagentStop` audit line (same fields, duration as a number). */
236
+ export function delegationStopLine(fields: {
237
+ agent: string
238
+ status: string
239
+ reason: string
240
+ task: string
241
+ sessionID: string
242
+ result: unknown
243
+ delegationID: string
244
+ taskID: string
245
+ durationMs: number | null
246
+ now: number
247
+ }): Record<string, unknown> {
248
+ return {
249
+ event: 'SubagentStop',
250
+ timestamp: delegationTimestamp(fields.now),
251
+ agent: fields.agent,
252
+ status: fields.status,
253
+ reason: fields.reason,
254
+ task: fields.task === '' ? fields.agent : fields.task,
255
+ session_id: fields.sessionID,
256
+ result: fields.result ?? null,
257
+ delegation_id: fields.delegationID,
258
+ ...(fields.taskID === '' ? {} : { task_id: fields.taskID }),
259
+ ...(fields.durationMs === null ? {} : { duration_ms: fields.durationMs }),
260
+ }
261
+ }
262
+
263
+ // ─── Formatter applicability gate ───────────────────────────────────────
264
+
265
+ /** Extensions `format-multi-language.sh` actually formats; others no-op. */
266
+ const FORMATTABLE_EXTENSIONS = new Set([
267
+ '.py',
268
+ '.ts',
269
+ '.tsx',
270
+ '.js',
271
+ '.jsx',
272
+ '.mjs',
273
+ '.cjs',
274
+ '.json',
275
+ '.md',
276
+ '.yml',
277
+ '.yaml',
278
+ '.toml',
279
+ ])
280
+
281
+ function formattablePath(value: unknown): boolean {
282
+ if (typeof value !== 'string' || value.length === 0) return false
283
+ const dot = value.lastIndexOf('.')
284
+ if (dot <= value.lastIndexOf('/')) return false
285
+ return FORMATTABLE_EXTENSIONS.has(value.slice(dot).toLowerCase())
286
+ }
287
+
288
+ /**
289
+ * Whether `format-multi-language.sh` would do anything for this tool call.
290
+ * The script no-ops for every other tool; skipping the spawn for those is the
291
+ * whole point of this gate.
292
+ */
293
+ export function formatterApplies(tool: string, input: unknown): boolean {
294
+ const normalized = tool.trim().toLowerCase()
295
+ if (normalized === 'edit' || normalized === 'write' || normalized === 'hashline_edit') {
296
+ if (input !== null && typeof input === 'object') {
297
+ return formattablePath((input as Record<string, unknown>).file_path)
298
+ }
299
+ return false
300
+ }
301
+ if (normalized === 'bash') {
302
+ // The script scans the command for rewritten paths; the conservative gate
303
+ // lets bash through unchanged (rare, and correctness beats micro-gains).
304
+ return true
305
+ }
306
+ return false
307
+ }