pantheon-opencode 1.5.0-beta.9 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +14 -63
- package/CHANGELOG.md +304 -0
- package/README.md +14 -27
- package/README.pt-BR.md +5 -6
- package/commands/pantheon.md +1 -35
- package/package.json +1 -2
- package/plugin.json +1 -1
- package/pyproject.toml +2 -5
- package/scripts/doctor.mjs +32 -3
- package/scripts/install/plugin.mjs +9 -12
- package/scripts/mcp_persistence_server.py +1 -1
- package/scripts/sync-tui.mjs +8 -11
- package/src/agents/apollo.md +1 -0
- package/src/agents/gaia.md +1 -0
- package/src/agents/zeus.md +9 -52
- package/src/instructions/memory-protocol.instructions.md +6 -3
- package/src/instructions/zeus-anti-stall.instructions.md +2 -4
- package/src/instructions/zeus-council-synthesis.instructions.md +3 -28
- package/src/instructions/zeus-timeout-retry.instructions.md +3 -28
- package/src/mcp/mcp_persistence_server.py +1 -1
- package/src/mcp/toon_codec.py +2 -4
- package/src/pantheon/background-job-board.ts +4 -4
- package/src/pantheon/{delegation-compaction.ts → compaction-context.ts} +10 -100
- package/src/pantheon/cost-command.ts +1 -2
- package/src/pantheon/delegation-enforce.ts +59 -14
- package/src/pantheon/goal-loop.ts +1 -1
- package/src/pantheon/goal-store.ts +1 -1
- package/src/pantheon/idle-continuation.ts +4 -6
- package/src/pantheon/model-command.ts +1 -2
- package/src/pantheon/native-task-status.ts +2 -2
- package/src/pantheon/presets.d.mts +0 -20
- package/src/pantheon/presets.mjs +0 -64
- package/src/pantheon/session-guard.ts +2 -2
- package/src/pantheon/session-id.ts +30 -0
- package/src/pantheon/task-result-guard.ts +2 -3
- package/src/pantheon/todo-enforcer.ts +3 -3
- package/src/pantheon/tool-context.ts +23 -0
- package/src/pantheon/v2-bridge.ts +1 -4
- package/src/plugin-v2.ts +8 -21
- package/src/plugin.ts +61 -245
- package/src/plugins/pantheon-hooks.ts +1 -1
- package/src/plugins/tui/dist/tui.d.ts +212 -81
- package/src/plugins/tui/dist/tui.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui.js +475 -254
- package/src/plugins/tui/package-lock.json +2 -2
- package/src/plugins/tui/package.json +2 -2
- package/src/plugins/tui/src/index.tsx +667 -269
- package/src/routing.yml +0 -16
- package/src/skills/context-compression/SKILL.md +1 -1
- package/scripts/generate-preset-docs.mjs +0 -300
- package/scripts/generate-prompts.sh +0 -222
- package/scripts/hash_verify.py +0 -192
- package/scripts/install/component.mjs +0 -24
- package/scripts/install/migrate-config.mjs +0 -302
- package/scripts/test-context-compression.sh +0 -169
- package/src/pantheon/auto-wake.ts +0 -85
- package/src/pantheon/chat-reminders.ts +0 -9
- package/src/pantheon/comment-checker.ts +0 -48
- package/src/pantheon/compaction-assert.ts +0 -160
- package/src/pantheon/compaction-handoff.ts +0 -304
- package/src/pantheon/cost-tracker.ts +0 -108
- package/src/pantheon/delegate-manager.ts +0 -766
- package/src/pantheon/delegation-classifier.ts +0 -307
- package/src/pantheon/delegation-finalize.ts +0 -406
- package/src/pantheon/delegation-notify.ts +0 -212
- package/src/pantheon/delegation-toast.ts +0 -73
- package/src/pantheon/delegation.ts +0 -1337
- package/src/pantheon/dispatch-guard.ts +0 -109
- package/src/pantheon/native-probe.ts +0 -234
- package/src/pantheon/permission-eval.ts +0 -284
- package/src/pantheon/preemptive-compact.ts +0 -76
- package/src/pantheon/provider-capabilities.ts +0 -221
- package/src/pantheon/provider-stream-tracker.ts +0 -182
- package/src/pantheon/retry-policy.ts +0 -212
- package/src/pantheon/step-cap.ts +0 -110
- package/src/pantheon/token-opt.ts +0 -689
- package/src/pantheon/toon-codec.ts +0 -481
- package/src/pantheon/v2-events.ts +0 -148
- package/src/pantheon/v2-hooks.ts +0 -287
- package/src/pantheon/v2-tool-definitions.ts +0 -331
- package/src/pantheon/zeus-delegate-with-retry.ts +0 -406
- package/src/plugins/tui/dist/tui.tsx +0 -2853
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Dispatch Guard (Wave 4, PR #46) — auto-retry-on-empty for background
|
|
3
|
-
* delegations. Classifies a dispatch result and redispatch once when it
|
|
4
|
-
* came back empty.
|
|
5
|
-
*
|
|
6
|
-
* Failure signature classification:
|
|
7
|
-
* - 'content' — text content present, nothing to do.
|
|
8
|
-
* - 'empty-mode1' — NO content AND NO tokens: the dispatch returned
|
|
9
|
-
* nothing at all (no reply / early abort).
|
|
10
|
-
* - 'empty-mode2' — no text part but tokens present: reasoning happened
|
|
11
|
-
* but the text part was lost — the themis Wave-2
|
|
12
|
-
* failure signature that triggered this guard.
|
|
13
|
-
*
|
|
14
|
-
* Retry cap is HARD at 1 (never 2x). The guard is stateful per instance:
|
|
15
|
-
* one retry budget total. It is a PURE library — it does NOT intercept
|
|
16
|
-
* task() (opencode 1.18.x cannot intercept task completion via hooks, so
|
|
17
|
-
* integration is manual-orchestration; see zeus.md "Empty-Result Retry").
|
|
18
|
-
*
|
|
19
|
-
* @module dispatch-guard
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
import { createPantheonLogger } from './logger.ts'
|
|
23
|
-
|
|
24
|
-
// Silence-by-default TUI policy (pantheon-hooks L42-58): the default warn
|
|
25
|
-
// fallback logs to .pantheon/logs/hooks.log; console echo is opt-in via
|
|
26
|
-
// PANTHEON_HOOKS_LOG=1. `logger` injection stays for tests.
|
|
27
|
-
const log = createPantheonLogger({ module: 'pantheon-dispatch-guard' })
|
|
28
|
-
|
|
29
|
-
/** A dispatch result — the minimal shape needed to classify emptiness. */
|
|
30
|
-
export interface DispatchResultLike {
|
|
31
|
-
/** Text content of the result (task_result / report markdown). */
|
|
32
|
-
content?: string | null
|
|
33
|
-
/** Input tokens (present when the model actually reasoned). */
|
|
34
|
-
tokensInput?: number
|
|
35
|
-
/** Output tokens (present when the model actually reasoned). */
|
|
36
|
-
tokensOutput?: number
|
|
37
|
-
/** R1: the failure that produced this result (classified by retry-policy). */
|
|
38
|
-
error?: unknown
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** Classification of a dispatch result. */
|
|
42
|
-
export type DispatchClassification = 'content' | 'empty-mode1' | 'empty-mode2'
|
|
43
|
-
|
|
44
|
-
export interface DispatchGuardOptions {
|
|
45
|
-
/** Enable auto-retry on empty results. Default: true. */
|
|
46
|
-
retryOnEmpty?: boolean
|
|
47
|
-
/** Injectable logger (defaults to the Pantheon file log, env-gated echo). */
|
|
48
|
-
logger?: { warn: (message: string) => void }
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export interface DispatchGuard {
|
|
52
|
-
/** Classify a result: content, empty-mode1 (nothing), empty-mode2 (reasoning, no text). */
|
|
53
|
-
classifyResult(result: DispatchResultLike): DispatchClassification
|
|
54
|
-
/**
|
|
55
|
-
* Redispatch ONCE when the result is empty and retryOnEmpty is enabled.
|
|
56
|
-
* A retried result that is STILL empty is returned as-is — the cap of 1
|
|
57
|
-
* is never exceeded. Never throws.
|
|
58
|
-
*/
|
|
59
|
-
maybeRetry(
|
|
60
|
-
result: DispatchResultLike,
|
|
61
|
-
redispatch: () => Promise<DispatchResultLike>,
|
|
62
|
-
): Promise<{
|
|
63
|
-
classification: DispatchClassification
|
|
64
|
-
retried: boolean
|
|
65
|
-
result: DispatchResultLike
|
|
66
|
-
}>
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/** 1-based retry budget — the hard cap. Never 2x. */
|
|
70
|
-
const MAX_RETRIES = 1
|
|
71
|
-
|
|
72
|
-
/** Whether a result carries any text content (whitespace-only counts as empty). */
|
|
73
|
-
function hasContent(result: DispatchResultLike): boolean {
|
|
74
|
-
return typeof result.content === 'string' && result.content.trim() !== ''
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/** Whether the result carries any token counts (i.e. the model actually ran). */
|
|
78
|
-
function hasTokens(result: DispatchResultLike): boolean {
|
|
79
|
-
return (result.tokensInput ?? 0) > 0 || (result.tokensOutput ?? 0) > 0
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export function createDispatchGuard(options?: DispatchGuardOptions): DispatchGuard {
|
|
83
|
-
const retryOnEmpty = options?.retryOnEmpty ?? true
|
|
84
|
-
const warn = options?.logger?.warn ?? ((message: string) => log.warn(message))
|
|
85
|
-
// Per-instance retry budget — the "cap 1" enforcement point.
|
|
86
|
-
let retriesUsed = 0
|
|
87
|
-
|
|
88
|
-
return {
|
|
89
|
-
classifyResult(result: DispatchResultLike): DispatchClassification {
|
|
90
|
-
if (hasContent(result)) return 'content'
|
|
91
|
-
return hasTokens(result) ? 'empty-mode2' : 'empty-mode1'
|
|
92
|
-
},
|
|
93
|
-
|
|
94
|
-
async maybeRetry(result, redispatch) {
|
|
95
|
-
const classification = this.classifyResult(result)
|
|
96
|
-
if (!retryOnEmpty || classification === 'content' || retriesUsed >= MAX_RETRIES) {
|
|
97
|
-
return { classification, retried: false, result }
|
|
98
|
-
}
|
|
99
|
-
retriesUsed += 1
|
|
100
|
-
warn(`dispatch returned ${classification}; retrying once (cap ${MAX_RETRIES})`)
|
|
101
|
-
const retriedResult = await redispatch()
|
|
102
|
-
return {
|
|
103
|
-
classification: this.classifyResult(retriedResult),
|
|
104
|
-
retried: true,
|
|
105
|
-
result: retriedResult,
|
|
106
|
-
}
|
|
107
|
-
},
|
|
108
|
-
}
|
|
109
|
-
}
|
|
@@ -1,234 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Native Probe — lazy capability detection for native task() delegation.
|
|
3
|
-
*
|
|
4
|
-
* The probe is invoked on the FIRST native delegation of a session (not at
|
|
5
|
-
* startup). It creates a child session with a minimal "ping" prompt, waits
|
|
6
|
-
* for idle, and classifies the output.
|
|
7
|
-
*
|
|
8
|
-
* Results are cached per probe instance (singleton guard):
|
|
9
|
-
* - UNAVAILABLE is TERMINAL — no retry.
|
|
10
|
-
* - AVAILABLE is also cached — no re-probe.
|
|
11
|
-
*
|
|
12
|
-
* Uses the OpenCode V1 session API (session.create + promptAsync) injected via
|
|
13
|
-
* the parent context.
|
|
14
|
-
*
|
|
15
|
-
* @module native-probe
|
|
16
|
-
*/
|
|
17
|
-
|
|
18
|
-
import { createPantheonLogger } from './logger.ts'
|
|
19
|
-
|
|
20
|
-
const log = createPantheonLogger({ module: 'native-probe' })
|
|
21
|
-
|
|
22
|
-
// ─── Types ─────────────────────────────────────────────────────────────
|
|
23
|
-
|
|
24
|
-
/** Possible outcomes of a native capability probe. */
|
|
25
|
-
export type NativeProbeResult = {
|
|
26
|
-
status: 'AVAILABLE' | 'UNAVAILABLE' | 'UNSUPPORTED'
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/** Minimal V1 client shape needed by the probe (session.create + promptAsync). */
|
|
30
|
-
export interface ProbeClient {
|
|
31
|
-
session: {
|
|
32
|
-
create: (input: { body: { parentID: string } }) => Promise<{ id: string }>
|
|
33
|
-
promptAsync: (input: {
|
|
34
|
-
path: { id: string }
|
|
35
|
-
body: { agent: string; parts: Array<{ type: 'text'; text: string }> }
|
|
36
|
-
}) => Promise<unknown>
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** Context injected into the probe function. */
|
|
41
|
-
export interface NativeProbeContext {
|
|
42
|
-
client: ProbeClient
|
|
43
|
-
parentSessionID: string
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** Options for a single probe invocation. */
|
|
47
|
-
export interface NativeProbeOptions {
|
|
48
|
-
/** Timeout in milliseconds. Default: 30000. */
|
|
49
|
-
timeoutMs?: number
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/** The probe function signature. */
|
|
53
|
-
export type NativeProbeFn = (
|
|
54
|
-
ctx: NativeProbeContext,
|
|
55
|
-
options?: NativeProbeOptions,
|
|
56
|
-
) => Promise<NativeProbeResult>
|
|
57
|
-
|
|
58
|
-
// ─── Helpers ───────────────────────────────────────────────────────────
|
|
59
|
-
|
|
60
|
-
/** Default timeout for the probe. */
|
|
61
|
-
const DEFAULT_TIMEOUT_MS = 30_000
|
|
62
|
-
|
|
63
|
-
/** Sentinel value indicating a timeout occurred. */
|
|
64
|
-
const TIMEOUT_SENTINEL = Symbol('timeout')
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Wrap a promise with a timeout.
|
|
68
|
-
* Returns the value on success, throws the original error on rejection,
|
|
69
|
-
* or returns TIMEOUT_SENTINEL if the timeout fires first.
|
|
70
|
-
*/
|
|
71
|
-
async function withTimeout<T>(
|
|
72
|
-
promise: Promise<T>,
|
|
73
|
-
ms: number,
|
|
74
|
-
): Promise<T | typeof TIMEOUT_SENTINEL> {
|
|
75
|
-
return new Promise<T | typeof TIMEOUT_SENTINEL>((resolve, reject) => {
|
|
76
|
-
const timer = setTimeout(() => resolve(TIMEOUT_SENTINEL), ms)
|
|
77
|
-
void promise.then(
|
|
78
|
-
(value) => {
|
|
79
|
-
clearTimeout(timer)
|
|
80
|
-
resolve(value)
|
|
81
|
-
},
|
|
82
|
-
(err: unknown) => {
|
|
83
|
-
clearTimeout(timer)
|
|
84
|
-
reject(err)
|
|
85
|
-
},
|
|
86
|
-
)
|
|
87
|
-
})
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Extract text content from a promptAsync response.
|
|
92
|
-
* Returns empty string if no recognizable content found.
|
|
93
|
-
*/
|
|
94
|
-
function extractOutput(result: unknown): string {
|
|
95
|
-
if (result == null) return ''
|
|
96
|
-
if (typeof result === 'string') return result
|
|
97
|
-
if (typeof result === 'object') {
|
|
98
|
-
const obj = result as Record<string, unknown>
|
|
99
|
-
// Check common shapes: { output }, { content }, { text }
|
|
100
|
-
if (typeof obj.output === 'string') return obj.output
|
|
101
|
-
if (typeof obj.content === 'string') return obj.content
|
|
102
|
-
if (typeof obj.text === 'string') return obj.text
|
|
103
|
-
}
|
|
104
|
-
// Non-empty object → treat as content (accepted message, etc.)
|
|
105
|
-
if (typeof result === 'object' && result !== null) {
|
|
106
|
-
return 'acknowledged'
|
|
107
|
-
}
|
|
108
|
-
return ''
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function isUnsupportedError(message: string): boolean {
|
|
112
|
-
const lower = message.toLowerCase()
|
|
113
|
-
return (
|
|
114
|
-
lower.includes('not available') ||
|
|
115
|
-
lower.includes('not supported') ||
|
|
116
|
-
lower.includes('unsupported') ||
|
|
117
|
-
lower.includes('method not found')
|
|
118
|
-
)
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// ─── Implementation ────────────────────────────────────────────────────
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* Create a native probe function with per-instance caching.
|
|
125
|
-
*
|
|
126
|
-
* The probe is LAZY: it does not run at startup. Call it on the first
|
|
127
|
-
* native delegation of the session. The result is cached — subsequent
|
|
128
|
-
* calls return the cached value without re-probing.
|
|
129
|
-
*
|
|
130
|
-
* @returns A probe function that caches results per instance.
|
|
131
|
-
*/
|
|
132
|
-
export function createNativeProbe(): NativeProbeFn {
|
|
133
|
-
let cachedResult: NativeProbeResult | null = null
|
|
134
|
-
let inFlight: Promise<NativeProbeResult> | null = null
|
|
135
|
-
|
|
136
|
-
return async (
|
|
137
|
-
ctx: NativeProbeContext,
|
|
138
|
-
options?: NativeProbeOptions,
|
|
139
|
-
): Promise<NativeProbeResult> => {
|
|
140
|
-
// Return cached result if available (singleton guard)
|
|
141
|
-
if (cachedResult !== null) {
|
|
142
|
-
return cachedResult
|
|
143
|
-
}
|
|
144
|
-
// Concurrent first dispatches share one probe instead of creating multiple
|
|
145
|
-
// child sessions. The promise is cleared only after a terminal result.
|
|
146
|
-
if (inFlight !== null) return inFlight
|
|
147
|
-
|
|
148
|
-
inFlight = probe(ctx, options)
|
|
149
|
-
try {
|
|
150
|
-
return await inFlight
|
|
151
|
-
} finally {
|
|
152
|
-
inFlight = null
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
async function probe(
|
|
157
|
-
ctx: NativeProbeContext,
|
|
158
|
-
options?: NativeProbeOptions,
|
|
159
|
-
): Promise<NativeProbeResult> {
|
|
160
|
-
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
161
|
-
|
|
162
|
-
// ── Phase 1: create child session ──────────────────────────────
|
|
163
|
-
let childID: string
|
|
164
|
-
try {
|
|
165
|
-
const createResult = await withTimeout(
|
|
166
|
-
ctx.client.session.create({ body: { parentID: ctx.parentSessionID } }),
|
|
167
|
-
timeoutMs,
|
|
168
|
-
)
|
|
169
|
-
if (createResult === TIMEOUT_SENTINEL) {
|
|
170
|
-
// Timeout during session.create → UNAVAILABLE
|
|
171
|
-
log.warn('[Native Probe] session.create timed out after', timeoutMs, 'ms')
|
|
172
|
-
const result: NativeProbeResult = { status: 'UNAVAILABLE' }
|
|
173
|
-
cachedResult = result
|
|
174
|
-
return result
|
|
175
|
-
}
|
|
176
|
-
childID = createResult.id
|
|
177
|
-
} catch (err: unknown) {
|
|
178
|
-
const msg = err instanceof Error ? err.message : String(err)
|
|
179
|
-
log.error('[Native Probe] session.create failed:', msg)
|
|
180
|
-
// Check for unsupported API patterns
|
|
181
|
-
if (isUnsupportedError(msg)) {
|
|
182
|
-
const result: NativeProbeResult = { status: 'UNSUPPORTED' }
|
|
183
|
-
cachedResult = result
|
|
184
|
-
return result
|
|
185
|
-
}
|
|
186
|
-
// Other creation failures → UNAVAILABLE
|
|
187
|
-
const result: NativeProbeResult = { status: 'UNAVAILABLE' }
|
|
188
|
-
cachedResult = result
|
|
189
|
-
return result
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
// ── Phase 2: send probe prompt ─────────────────────────────────
|
|
193
|
-
let promptResult: unknown
|
|
194
|
-
try {
|
|
195
|
-
const raw = await withTimeout(
|
|
196
|
-
ctx.client.session.promptAsync({
|
|
197
|
-
path: { id: childID },
|
|
198
|
-
body: { agent: 'probe', parts: [{ type: 'text', text: 'Reply with PONG.' }] },
|
|
199
|
-
}),
|
|
200
|
-
timeoutMs,
|
|
201
|
-
)
|
|
202
|
-
if (raw === TIMEOUT_SENTINEL) {
|
|
203
|
-
// Timeout during promptAsync → UNAVAILABLE
|
|
204
|
-
log.warn('[Native Probe] promptAsync timed out after', timeoutMs, 'ms')
|
|
205
|
-
const result: NativeProbeResult = { status: 'UNAVAILABLE' }
|
|
206
|
-
cachedResult = result
|
|
207
|
-
return result
|
|
208
|
-
}
|
|
209
|
-
promptResult = raw
|
|
210
|
-
} catch (err: unknown) {
|
|
211
|
-
const msg = err instanceof Error ? err.message : String(err)
|
|
212
|
-
log.error('[Native Probe] promptAsync failed:', msg)
|
|
213
|
-
if (isUnsupportedError(msg)) {
|
|
214
|
-
const result: NativeProbeResult = { status: 'UNSUPPORTED' }
|
|
215
|
-
cachedResult = result
|
|
216
|
-
return result
|
|
217
|
-
}
|
|
218
|
-
// promptAsync error → UNAVAILABLE
|
|
219
|
-
const result: NativeProbeResult = { status: 'UNAVAILABLE' }
|
|
220
|
-
cachedResult = result
|
|
221
|
-
return result
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// ── Phase 3: classify output ───────────────────────────────────
|
|
225
|
-
const output = extractOutput(promptResult)
|
|
226
|
-
const hasContent = output.trim() !== ''
|
|
227
|
-
|
|
228
|
-
const result: NativeProbeResult = {
|
|
229
|
-
status: hasContent ? 'AVAILABLE' : 'UNAVAILABLE',
|
|
230
|
-
}
|
|
231
|
-
cachedResult = result
|
|
232
|
-
return result
|
|
233
|
-
}
|
|
234
|
-
}
|
|
@@ -1,284 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* S1 — Deny-first permission evaluation + PreToolUse-style hooks.
|
|
3
|
-
*
|
|
4
|
-
* Deny rules checked BEFORE allow rules. User-level denies cannot be
|
|
5
|
-
* overridden by project config. Hook exit-code semantics:
|
|
6
|
-
* exit 0 → allow, exit 2 → hard deny, missing/throw → fail-open.
|
|
7
|
-
*
|
|
8
|
-
* @module permission-eval
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
// ─── Types ─────────────────────────────────────────────────────────────
|
|
12
|
-
|
|
13
|
-
/** Result of a permission evaluation. */
|
|
14
|
-
export interface PermissionResult {
|
|
15
|
-
allowed: boolean
|
|
16
|
-
reason: 'allow' | 'deny' | 'hook_deny' | 'no_match'
|
|
17
|
-
message?: string
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/** Hook script result (mirrors hook-runner.ts HookResult). */
|
|
21
|
-
export interface HookResult {
|
|
22
|
-
code: number
|
|
23
|
-
stdout: string
|
|
24
|
-
stderr: string
|
|
25
|
-
/** When true, the hook script was not found — treat as fail-open. */
|
|
26
|
-
missing?: boolean
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* PreToolUse hook function signature.
|
|
31
|
-
* exit 0 → allow, exit 2 → hard deny, exit 1 → soft deny.
|
|
32
|
-
* Throw = fail-open.
|
|
33
|
-
*/
|
|
34
|
-
export type PreToolUseHook = (tool: string, args: unknown) => Promise<HookResult> | HookResult
|
|
35
|
-
|
|
36
|
-
/** Permission configuration. */
|
|
37
|
-
export interface PermissionConfig {
|
|
38
|
-
/** Deny rules — evaluated first. User-level denies override project allows. */
|
|
39
|
-
deny: readonly string[]
|
|
40
|
-
/** Allow rules — evaluated after deny. */
|
|
41
|
-
allow: readonly string[]
|
|
42
|
-
/** Optional hooks configuration. */
|
|
43
|
-
hooks?: {
|
|
44
|
-
/** PreToolUse hook function (in-process, not script path). */
|
|
45
|
-
preToolUse?: PreToolUseHook
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
// ─── Pattern matching ──────────────────────────────────────────────────
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Parse a permission rule pattern into { tool, argPattern }.
|
|
53
|
-
*
|
|
54
|
-
* Supported formats:
|
|
55
|
-
* - "tool" → tool="tool", argPattern="*"
|
|
56
|
-
* - "tool:*" → tool="tool", argPattern="*"
|
|
57
|
-
* - "tool:subcommand" → tool="tool", argPattern="subcommand"
|
|
58
|
-
* - "tool(pattern)" → tool="tool", argPattern="pattern" (full match)
|
|
59
|
-
* - "*:*" → tool="*", argPattern="*"
|
|
60
|
-
* - "git push:*" → tool="git push", argPattern="*" (subcommand prefix)
|
|
61
|
-
*/
|
|
62
|
-
function parsePattern(pattern: string): { tool: string; argPattern: string } {
|
|
63
|
-
// Handle "tool(pattern)" format — the content inside parens is the full
|
|
64
|
-
// arg pattern. Colons inside parens are literal, not separators.
|
|
65
|
-
const parenMatch = /^([^(]+)\(([^)]+)\)$/.exec(pattern)
|
|
66
|
-
if (parenMatch) {
|
|
67
|
-
const tool = parenMatch[1] ?? ''
|
|
68
|
-
const argPattern = parenMatch[2] ?? ''
|
|
69
|
-
return { tool, argPattern }
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
// Handle "tool:argPattern" or just "tool"
|
|
73
|
-
const colonIdx = pattern.indexOf(':')
|
|
74
|
-
if (colonIdx === -1) {
|
|
75
|
-
return { tool: pattern, argPattern: '*' }
|
|
76
|
-
}
|
|
77
|
-
const argPattern = pattern.slice(colonIdx + 1)
|
|
78
|
-
return {
|
|
79
|
-
tool: pattern.slice(0, colonIdx),
|
|
80
|
-
// Empty argPattern after colon = wildcard (e.g. "*:" matches any args)
|
|
81
|
-
argPattern: argPattern === '' ? '*' : argPattern,
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* Convert a glob-like pattern to a regex. `*` matches any sequence.
|
|
87
|
-
* Anchored to full match.
|
|
88
|
-
*/
|
|
89
|
-
function globToRegex(pattern: string): RegExp {
|
|
90
|
-
const escaped = pattern
|
|
91
|
-
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
92
|
-
.replace(/\*/g, '.*')
|
|
93
|
-
.replace(/\?/g, '.')
|
|
94
|
-
return new RegExp(`^${escaped}$`)
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** Extract a string representation from tool args for pattern matching. */
|
|
98
|
-
function argsToString(args: unknown): string {
|
|
99
|
-
if (args === null || args === undefined) return ''
|
|
100
|
-
if (typeof args === 'string') return args
|
|
101
|
-
if (typeof args === 'object') {
|
|
102
|
-
const record = args as Record<string, unknown>
|
|
103
|
-
// Try common field names
|
|
104
|
-
for (const key of ['command', 'cmd', 'query', 'pattern', 'filePath', 'path', 'url']) {
|
|
105
|
-
if (typeof record[key] === 'string') return record[key]
|
|
106
|
-
}
|
|
107
|
-
return JSON.stringify(args)
|
|
108
|
-
}
|
|
109
|
-
return String(args)
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Build a combined string for matching: "toolName argString".
|
|
114
|
-
* This allows patterns like "git push:*" to match tool="git" with args
|
|
115
|
-
* containing "push".
|
|
116
|
-
*/
|
|
117
|
-
function combinedString(tool: string, args: unknown): string {
|
|
118
|
-
const argsStr = argsToString(args)
|
|
119
|
-
return argsStr !== '' ? `${tool} ${argsStr}` : tool
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Check if a tool+args matches a permission rule pattern.
|
|
124
|
-
* Returns true when the pattern matches.
|
|
125
|
-
*
|
|
126
|
-
* Matching strategy:
|
|
127
|
-
* 1. Wildcard tool ("*") → match any tool with argPattern
|
|
128
|
-
* 2. Direct tool match → check argPattern against args
|
|
129
|
-
* 3. Combined match (for "git push:*" style patterns) → prefix match
|
|
130
|
-
*/
|
|
131
|
-
function matchesRule(pattern: string, tool: string, args: unknown): boolean {
|
|
132
|
-
const { tool: patternTool, argPattern } = parsePattern(pattern)
|
|
133
|
-
|
|
134
|
-
// Wildcard tool: match any tool
|
|
135
|
-
if (patternTool === '*') {
|
|
136
|
-
if (argPattern === '*') return true
|
|
137
|
-
const argsStr = argsToString(args)
|
|
138
|
-
return globToRegex(argPattern).test(argsStr)
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
// Check direct tool match
|
|
142
|
-
if (globToRegex(patternTool).test(tool)) {
|
|
143
|
-
if (argPattern === '*') return true
|
|
144
|
-
const argsStr = argsToString(args)
|
|
145
|
-
return globToRegex(argPattern).test(argsStr)
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
// Combined match for patterns with spaces (e.g. "git push:*")
|
|
149
|
-
// The pattern tool includes a subcommand that appears in args.
|
|
150
|
-
// Use prefix matching: "git push" matches "git push origin main"
|
|
151
|
-
if (patternTool.includes(' ')) {
|
|
152
|
-
const combined = combinedString(tool, args)
|
|
153
|
-
// Prefix match: combined starts with pattern tool
|
|
154
|
-
if (combined.startsWith(patternTool)) {
|
|
155
|
-
return true
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
return false
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// ─── Evaluation ────────────────────────────────────────────────────────
|
|
163
|
-
|
|
164
|
-
/**
|
|
165
|
-
* Evaluate a permission config against a tool+args invocation.
|
|
166
|
-
*
|
|
167
|
-
* Evaluation order:
|
|
168
|
-
* 1. Check deny rules (user-level first, then project-level)
|
|
169
|
-
* 2. If no deny matched, run the PreToolUse hook
|
|
170
|
-
* 3. If hook exits 0 (or missing), check allow rules
|
|
171
|
-
* 4. If no allow matched → deny (implicit deny)
|
|
172
|
-
*
|
|
173
|
-
* User-level denies override project-level allows: a deny in the user config
|
|
174
|
-
* cannot be cancelled by an allow in the project config.
|
|
175
|
-
*/
|
|
176
|
-
export function evaluatePermission(
|
|
177
|
-
config: PermissionConfig,
|
|
178
|
-
invocation: { tool: string; args?: unknown },
|
|
179
|
-
): PermissionResult {
|
|
180
|
-
const { tool, args } = invocation
|
|
181
|
-
|
|
182
|
-
// ── Step 1: Deny-first check ────────────────────────────────────────
|
|
183
|
-
for (const pattern of config.deny) {
|
|
184
|
-
if (matchesRule(pattern, tool, args)) {
|
|
185
|
-
return { allowed: false, reason: 'deny', message: `denied by rule: ${pattern}` }
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// ── Step 2: PreToolUse hook ─────────────────────────────────────────
|
|
190
|
-
if (config.hooks?.preToolUse !== undefined) {
|
|
191
|
-
try {
|
|
192
|
-
const hookResult = config.hooks.preToolUse(tool, args)
|
|
193
|
-
// Support both sync and async hooks
|
|
194
|
-
// For sync hooks (non-Promise), check immediately
|
|
195
|
-
if (!(hookResult instanceof Promise)) {
|
|
196
|
-
// missing flag: hook script not found → fail-open
|
|
197
|
-
if (hookResult.missing === true) {
|
|
198
|
-
// Fall through to config evaluation (fail-open)
|
|
199
|
-
} else if (hookResult.code === 2) {
|
|
200
|
-
return {
|
|
201
|
-
allowed: false,
|
|
202
|
-
reason: 'hook_deny',
|
|
203
|
-
message: `hook hard deny (exit 2): ${hookResult.stderr}`,
|
|
204
|
-
}
|
|
205
|
-
} else if (hookResult.code !== 0) {
|
|
206
|
-
return {
|
|
207
|
-
allowed: false,
|
|
208
|
-
reason: 'hook_deny',
|
|
209
|
-
message: `hook deny (exit ${hookResult.code}): ${hookResult.stderr}`,
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
// Hook exited 0 (or missing) → fall through to allow check
|
|
213
|
-
}
|
|
214
|
-
// For async hooks, we cannot await in a sync function.
|
|
215
|
-
// Use evaluatePermissionAsync for async hooks.
|
|
216
|
-
} catch {
|
|
217
|
-
// Hook throw → fail-open: fall through to config evaluation
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
// ── Step 3: Allow check ─────────────────────────────────────────────
|
|
222
|
-
for (const pattern of config.allow) {
|
|
223
|
-
if (matchesRule(pattern, tool, args)) {
|
|
224
|
-
return { allowed: true, reason: 'allow', message: `allowed by rule: ${pattern}` }
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
// ── Step 4: No match → implicit deny ────────────────────────────────
|
|
229
|
-
return { allowed: false, reason: 'no_match', message: 'no matching allow rule' }
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
/**
|
|
233
|
-
* Async version of evaluatePermission that properly awaits hooks.
|
|
234
|
-
* Use this when hooks may be async (e.g., shell scripts).
|
|
235
|
-
*/
|
|
236
|
-
export async function evaluatePermissionAsync(
|
|
237
|
-
config: PermissionConfig,
|
|
238
|
-
invocation: { tool: string; args?: unknown },
|
|
239
|
-
): Promise<PermissionResult> {
|
|
240
|
-
const { tool, args } = invocation
|
|
241
|
-
|
|
242
|
-
// ── Step 1: Deny-first check ────────────────────────────────────────
|
|
243
|
-
for (const pattern of config.deny) {
|
|
244
|
-
if (matchesRule(pattern, tool, args)) {
|
|
245
|
-
return { allowed: false, reason: 'deny', message: `denied by rule: ${pattern}` }
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
// ── Step 2: PreToolUse hook ─────────────────────────────────────────
|
|
250
|
-
if (config.hooks?.preToolUse !== undefined) {
|
|
251
|
-
try {
|
|
252
|
-
const hookResult = await config.hooks.preToolUse(tool, args)
|
|
253
|
-
// missing flag: hook script not found → fail-open
|
|
254
|
-
if (hookResult.missing === true) {
|
|
255
|
-
// Fall through to config evaluation (fail-open)
|
|
256
|
-
} else if (hookResult.code === 2) {
|
|
257
|
-
return {
|
|
258
|
-
allowed: false,
|
|
259
|
-
reason: 'hook_deny',
|
|
260
|
-
message: `hook hard deny (exit 2): ${hookResult.stderr}`,
|
|
261
|
-
}
|
|
262
|
-
} else if (hookResult.code !== 0) {
|
|
263
|
-
return {
|
|
264
|
-
allowed: false,
|
|
265
|
-
reason: 'hook_deny',
|
|
266
|
-
message: `hook deny (exit ${hookResult.code}): ${hookResult.stderr}`,
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
// Hook exited 0 (or missing) → fall through to allow check
|
|
270
|
-
} catch {
|
|
271
|
-
// Hook throw → fail-open: fall through to config evaluation
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
// ── Step 3: Allow check ─────────────────────────────────────────────
|
|
276
|
-
for (const pattern of config.allow) {
|
|
277
|
-
if (matchesRule(pattern, tool, args)) {
|
|
278
|
-
return { allowed: true, reason: 'allow', message: `allowed by rule: ${pattern}` }
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
// ── Step 4: No match → implicit deny ────────────────────────────────
|
|
283
|
-
return { allowed: false, reason: 'no_match', message: 'no matching allow rule' }
|
|
284
|
-
}
|