pantheon-opencode 1.4.3 → 1.5.0-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.
- package/.pantheon/code-mode/README.md +93 -0
- package/.pantheon/code-mode/checkpoint-session.py +7 -0
- package/.pantheon/code-mode/checkpoint-session.sh +11 -0
- package/.pantheon/code-mode/checkpoint_session.py +481 -0
- package/.pantheon/code-mode/compress-inline.py +450 -0
- package/.pantheon/code-mode/eval-llm-judge.py +255 -0
- package/.pantheon/code-mode/eval-monte-carlo.py +368 -0
- package/.pantheon/code-mode/eval-run.py +197 -0
- package/.pantheon/code-mode/eval-static.py +321 -0
- package/.pantheon/code-mode/example-sync.sh +5 -0
- package/.pantheon/code-mode/manifest.json +21 -0
- package/.pantheon/code-mode/session-end-save.py +186 -0
- package/.pantheon/code-mode/session-end-save.sh +18 -0
- package/.pantheon/code-mode/test-allowed.sh +5 -0
- package/.pantheon/code-mode/test-auto-continue-checkpoint.sh +179 -0
- package/.pantheon/code-mode/test-env.sh +7 -0
- package/.pantheon/code-mode/test-prlimit.sh +9 -0
- package/.pantheon/code-mode/test-timeout.sh +6 -0
- package/CHANGELOG.md +1026 -0
- package/README.md +292 -1080
- package/README.pt-BR.md +308 -0
- package/bin/pantheon-init.mjs +207 -31
- package/opencode.json +1 -0
- package/package.json +34 -14
- package/plugin.json +15 -0
- package/pyproject.toml +65 -0
- package/scripts/_pantheon_paths.py +48 -7
- package/scripts/ci-validate-yaml.py +7 -2
- package/scripts/code_mode_server.py +451 -44
- package/scripts/cost.mjs +30 -14
- package/scripts/doctor.mjs +306 -129
- package/scripts/generate-preset-docs.mjs +127 -66
- package/scripts/generate-prompts.sh +2 -2
- package/scripts/install/cli-ui.mjs +23 -10
- package/scripts/install/config-migration.mjs +399 -0
- package/scripts/install/health-check.mjs +3 -3
- package/scripts/install/model-picker.mjs +72 -23
- package/scripts/install/opencode-version.mjs +47 -0
- package/scripts/install/opencode.mjs +396 -121
- package/scripts/install/plugin.mjs +89 -49
- package/scripts/install/shared.mjs +55 -159
- package/scripts/install/strings.mjs +129 -0
- package/scripts/install-mcp.mjs +45 -232
- package/scripts/manifest-inventory.mjs +410 -0
- package/scripts/mcp_persistence_server.py +798 -60
- package/scripts/mcp_resources_server.py +144 -40
- package/scripts/memory_mcp_server.py +2 -2
- package/scripts/package-evidence.mjs +242 -0
- package/scripts/probe-context-rehydrate.mjs +240 -0
- package/scripts/probe-pantheon-cost.mjs +313 -0
- package/scripts/recover-zenodo-deposition.mjs +146 -0
- package/scripts/release-beta-version.mjs +56 -60
- package/scripts/sync-artifacts.mjs +169 -0
- package/scripts/sync-tui.mjs +135 -42
- package/scripts/test-opencode-v1-v2-sandbox.sh +862 -0
- package/scripts/uninstall.mjs +298 -954
- package/scripts/validate-zenodo-release.mjs +154 -0
- package/scripts/validation-policy.mjs +7 -7
- package/scripts/version-check.mjs +113 -108
- package/scripts/versioning.mjs +230 -86
- package/scripts/zenodo-artifact.mjs +21 -0
- package/scripts/zenodo-release-state.mjs +53 -0
- package/src/agents/mnemosyne.md +1 -1
- package/src/agents/zeus.md +27 -16
- package/src/mcp/_pantheon_paths.py +48 -7
- package/src/mcp/code_mode_server.py +451 -44
- package/src/mcp/eval_store.py +1 -1
- package/src/mcp/mcp_persistence_server.py +798 -60
- package/src/mcp/mcp_resources_server.py +144 -40
- package/src/mcp/pantheon_vision_server.py +1 -1
- package/src/mcp/toon_codec.py +491 -0
- package/src/pantheon/auto-wake.ts +1 -5
- package/src/pantheon/background-job-board.ts +110 -2
- package/src/pantheon/compaction-handoff.ts +304 -0
- package/src/pantheon/cost-command.ts +356 -69
- package/src/pantheon/delegate-manager.ts +766 -0
- package/src/pantheon/delegation-classifier.ts +307 -0
- package/src/pantheon/delegation-enforce.ts +13 -12
- package/src/pantheon/delegation-finalize.ts +406 -0
- package/src/pantheon/delegation-notify.ts +212 -0
- package/src/pantheon/delegation-toast.ts +73 -0
- package/src/pantheon/delegation.ts +1337 -0
- package/src/pantheon/file-persistence-salvage.ts +64 -0
- package/src/pantheon/file-persistence.ts +194 -45
- package/src/pantheon/goal-loop.ts +2 -2
- package/src/pantheon/goal-store.ts +1 -1
- package/src/pantheon/hashline/tool.ts +2 -2
- package/src/pantheon/model-command.ts +2 -1
- package/src/pantheon/native-probe.ts +234 -0
- package/src/pantheon/native-task-status.ts +139 -0
- package/src/pantheon/permission-eval.ts +284 -0
- package/src/pantheon/provider-capabilities.ts +221 -0
- package/src/pantheon/provider-stream-tracker.ts +182 -0
- package/src/pantheon/shared-board.ts +37 -0
- package/src/pantheon/step-cap.ts +110 -0
- package/src/pantheon/task-result-guard.ts +107 -0
- package/src/pantheon/token-opt.ts +689 -0
- package/src/pantheon/tool-ceiling.ts +159 -0
- package/src/pantheon/toon-codec.ts +481 -0
- package/src/pantheon/tui-version-check.ts +1 -3
- package/src/pantheon/v2-bridge.ts +129 -0
- package/src/pantheon/v2-events.ts +148 -0
- package/src/pantheon/v2-hooks.ts +287 -0
- package/src/pantheon/v2-tool-definitions.ts +331 -0
- package/src/pantheon/zeus-delegate-with-retry.ts +406 -0
- package/src/plugin-v2/index.ts +21 -0
- package/src/plugin-v2.ts +824 -0
- package/src/plugin.ts +261 -51
- package/src/plugins/pantheon-hooks.ts +51 -0
- package/src/plugins/tui/dist/tui.d.ts +116 -24
- package/src/plugins/tui/dist/tui.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui.js +416 -149
- package/src/plugins/tui/dist/tui.tsx +456 -87
- package/src/plugins/tui/package-lock.json +51 -51
- package/src/plugins/tui/package.json +7 -7
- package/src/plugins/tui/src/index.tsx +462 -95
- package/src/skills/README.md +0 -2
- package/src/pantheon/tool-context.ts +0 -41
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Native Task Status — classifies BackgroundJobRecord results from native
|
|
3
|
+
* task() delegation into actionable status codes.
|
|
4
|
+
*
|
|
5
|
+
* Pure module — zero external dependencies. Consumed by native-probe.ts
|
|
6
|
+
* and the delegation manager to decide retry/skip/escalate strategy.
|
|
7
|
+
*
|
|
8
|
+
* @module native-task-status
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { BackgroundJobRecord } from './background-job-board.ts'
|
|
12
|
+
|
|
13
|
+
// ─── Types ─────────────────────────────────────────────────────────────
|
|
14
|
+
|
|
15
|
+
/** Actionable status for a native task() delegation result. */
|
|
16
|
+
export type NativeTaskStatus =
|
|
17
|
+
| 'OK'
|
|
18
|
+
| 'UNSUPPORTED'
|
|
19
|
+
| 'UNAVAILABLE'
|
|
20
|
+
| 'INVALID_INPUT'
|
|
21
|
+
| 'INVALID_STATE'
|
|
22
|
+
| 'CONFLICT'
|
|
23
|
+
| 'CORRUPT_DATA'
|
|
24
|
+
| 'TIMEOUT'
|
|
25
|
+
| 'ESCALATE'
|
|
26
|
+
|
|
27
|
+
// ─── Helpers ───────────────────────────────────────────────────────────
|
|
28
|
+
|
|
29
|
+
/** Check if a string contains any of the given substrings (case-insensitive). */
|
|
30
|
+
function containsAny(text: string | undefined, patterns: readonly string[]): boolean {
|
|
31
|
+
if (text == null) return false
|
|
32
|
+
const lower = text.toLowerCase()
|
|
33
|
+
return patterns.some((p) => lower.includes(p.toLowerCase()))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Check if a job's output is empty or whitespace-only. */
|
|
37
|
+
function isOutputEmpty(job: BackgroundJobRecord): boolean {
|
|
38
|
+
const summary = job.resultSummary
|
|
39
|
+
if (summary == null) return true
|
|
40
|
+
if (typeof summary !== 'string') return true
|
|
41
|
+
return summary.trim() === ''
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ─── Implementation ────────────────────────────────────────────────────
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Classify a BackgroundJobRecord result into a NativeTaskStatus.
|
|
48
|
+
*
|
|
49
|
+
* Priority order (first match wins):
|
|
50
|
+
* 1. verifyError and lastStatusError patterns → UNSUPPORTED, CONFLICT,
|
|
51
|
+
* INVALID_INPUT, INVALID_STATE, CORRUPT_DATA, ESCALATE
|
|
52
|
+
* 2. state === startup_failed or timedOut → TIMEOUT
|
|
53
|
+
* 3. state === completed + non-empty output → OK
|
|
54
|
+
* 4. state === completed + empty output → UNAVAILABLE (silent failure / admission rejection)
|
|
55
|
+
* 5. state === error → UNAVAILABLE (safe default for provider/infra errors)
|
|
56
|
+
* 6. Fallback → UNAVAILABLE
|
|
57
|
+
*/
|
|
58
|
+
export function classifyNativeResult(
|
|
59
|
+
job: BackgroundJobRecord,
|
|
60
|
+
verifyError?: string,
|
|
61
|
+
): NativeTaskStatus {
|
|
62
|
+
const statusError = [verifyError, job.lastStatusError]
|
|
63
|
+
.filter((value): value is string => value != null && value.length > 0)
|
|
64
|
+
.join(' ')
|
|
65
|
+
|
|
66
|
+
// A missing native task API is terminal and must not be retried or sent
|
|
67
|
+
// through a fallback model. Provider/transport failures remain unavailable.
|
|
68
|
+
if (
|
|
69
|
+
containsAny(statusError, [
|
|
70
|
+
'api unavailable',
|
|
71
|
+
'api not available',
|
|
72
|
+
'api missing',
|
|
73
|
+
'method not found',
|
|
74
|
+
'unknown method',
|
|
75
|
+
'not supported',
|
|
76
|
+
'unsupported',
|
|
77
|
+
'does not support',
|
|
78
|
+
'task() is not available',
|
|
79
|
+
])
|
|
80
|
+
) {
|
|
81
|
+
return 'UNSUPPORTED'
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// ── Phase 1: verifyError explicit signals (highest priority) ───────
|
|
85
|
+
|
|
86
|
+
if (verifyError != null && verifyError.length > 0) {
|
|
87
|
+
// CONFLICT: canDispatch=false or concurrency exceeded
|
|
88
|
+
if (containsAny(verifyError, ['canDispatch', 'concurrency', 'conflict'])) {
|
|
89
|
+
return 'CONFLICT'
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// INVALID_INPUT: agent not recognized / invalid
|
|
93
|
+
if (containsAny(verifyError, ['invalid agent', 'agent not found', 'unknown agent'])) {
|
|
94
|
+
return 'INVALID_INPUT'
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// INVALID_STATE: child already in terminal state
|
|
98
|
+
if (containsAny(verifyError, ['already terminal', 'already in terminal', 'invalid state'])) {
|
|
99
|
+
return 'INVALID_STATE'
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// CORRUPT_DATA: output can't be parsed / corrupted
|
|
103
|
+
if (containsAny(verifyError, ['corrupt', 'parse failed', 'malformed', 'invalid format'])) {
|
|
104
|
+
return 'CORRUPT_DATA'
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ESCALATE: unrecoverable failure
|
|
108
|
+
if (containsAny(verifyError, ['unrecoverable', 'fatal', 'max retries exceeded'])) {
|
|
109
|
+
return 'ESCALATE'
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ── Phase 2: state-based classification ────────────────────────────
|
|
114
|
+
|
|
115
|
+
// TIMEOUT: startup failure or timed out
|
|
116
|
+
if (job.state === 'startup_failed' || job.state === 'startup_unknown' || job.timedOut) {
|
|
117
|
+
return 'TIMEOUT'
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ── Phase 3: output-based classification ───────────────────────────
|
|
121
|
+
|
|
122
|
+
if (job.state === 'completed') {
|
|
123
|
+
if (!isOutputEmpty(job)) {
|
|
124
|
+
return 'OK'
|
|
125
|
+
}
|
|
126
|
+
// completed but empty → silent failure (BackendAdmissionRejected pattern)
|
|
127
|
+
return 'UNAVAILABLE'
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ── Phase 4: error state fallback ──────────────────────────────────
|
|
131
|
+
|
|
132
|
+
if (job.state === 'error') {
|
|
133
|
+
return 'UNAVAILABLE'
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// ── Fallback ───────────────────────────────────────────────────────
|
|
137
|
+
|
|
138
|
+
return 'UNAVAILABLE'
|
|
139
|
+
}
|
|
@@ -0,0 +1,284 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exact provider usage contract and the independent V1/V2 capability probes.
|
|
3
|
+
*
|
|
4
|
+
* This module deliberately does not inspect credentials, call a provider, read
|
|
5
|
+
* the TUI, calculate percentages, or derive token counts from text. A provider
|
|
6
|
+
* is supported only when it supplies the complete numeric contract below.
|
|
7
|
+
*
|
|
8
|
+
* @module provider-capabilities
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** The only capability statuses exposed by the usage contract. */
|
|
12
|
+
export const USAGE_STATUS = {
|
|
13
|
+
SUPPORTED: 'SUPPORTED',
|
|
14
|
+
UNSUPPORTED: 'UNSUPPORTED',
|
|
15
|
+
} as const
|
|
16
|
+
|
|
17
|
+
export type UsageStatus = (typeof USAGE_STATUS)[keyof typeof USAGE_STATUS]
|
|
18
|
+
|
|
19
|
+
/** Exact token counters supplied by the provider. No totals are inferred. */
|
|
20
|
+
export interface ExactProviderUsage {
|
|
21
|
+
inputTokens: number
|
|
22
|
+
outputTokens: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Exact context limit supplied by the provider. */
|
|
26
|
+
export interface ExactProviderLimit {
|
|
27
|
+
contextTokens: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Minimum complete provider payload accepted by either capability probe.
|
|
32
|
+
* `resetAt`, when present, is an exact non-negative numeric provider value;
|
|
33
|
+
* date strings and other reset representations are unsupported.
|
|
34
|
+
*/
|
|
35
|
+
export interface ExactProviderUsageData {
|
|
36
|
+
sessionId: string
|
|
37
|
+
providerId: string
|
|
38
|
+
modelId: string
|
|
39
|
+
usage: ExactProviderUsage
|
|
40
|
+
limit: ExactProviderLimit
|
|
41
|
+
resetAt?: number
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Stream event metadata required for de-duplication and freshness ordering. */
|
|
45
|
+
export interface ProviderUsageEvent extends ExactProviderUsageData {
|
|
46
|
+
eventId: string
|
|
47
|
+
partId: string
|
|
48
|
+
/** Optional provider sequence. When supplied, it must be an integer. */
|
|
49
|
+
sequence?: number
|
|
50
|
+
/** Optional provider observation time in milliseconds or another numeric scale. */
|
|
51
|
+
observedAt?: number
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A complete snapshot that has passed the exact contract validation. */
|
|
55
|
+
export interface ProviderUsageSnapshot extends ProviderUsageEvent {}
|
|
56
|
+
|
|
57
|
+
export type CapabilityProbeVersion = 'v1' | 'v2'
|
|
58
|
+
|
|
59
|
+
export type CapabilityProbeReason =
|
|
60
|
+
| 'MISSING_SESSION_ID'
|
|
61
|
+
| 'MISSING_PROVIDER_ID'
|
|
62
|
+
| 'MISSING_MODEL_ID'
|
|
63
|
+
| 'MISSING_USAGE'
|
|
64
|
+
| 'MISSING_LIMIT'
|
|
65
|
+
| 'INVALID_USAGE'
|
|
66
|
+
| 'INVALID_LIMIT'
|
|
67
|
+
| 'INVALID_RESET'
|
|
68
|
+
|
|
69
|
+
export type ProviderCapabilityResult =
|
|
70
|
+
| {
|
|
71
|
+
apiVersion: CapabilityProbeVersion
|
|
72
|
+
status: typeof USAGE_STATUS.SUPPORTED
|
|
73
|
+
data: ExactProviderUsageData
|
|
74
|
+
}
|
|
75
|
+
| {
|
|
76
|
+
apiVersion: CapabilityProbeVersion
|
|
77
|
+
status: typeof USAGE_STATUS.UNSUPPORTED
|
|
78
|
+
reason: CapabilityProbeReason
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
type UnknownRecord = Record<string, unknown>
|
|
82
|
+
|
|
83
|
+
function isRecord(value: unknown): value is UnknownRecord {
|
|
84
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function isNonEmptyString(value: unknown): value is string {
|
|
88
|
+
return typeof value === 'string' && value.trim().length > 0
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function isFiniteNonNegativeNumber(value: unknown): value is number {
|
|
92
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function hasOnlyKeys(value: UnknownRecord, allowed: readonly string[]): boolean {
|
|
96
|
+
return Object.keys(value).every((key) => allowed.includes(key))
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function unsupported(
|
|
100
|
+
apiVersion: CapabilityProbeVersion,
|
|
101
|
+
reason: CapabilityProbeReason,
|
|
102
|
+
): ProviderCapabilityResult {
|
|
103
|
+
return { apiVersion, status: USAGE_STATUS.UNSUPPORTED, reason }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Validate the complete exact payload without coercion or estimation.
|
|
108
|
+
*
|
|
109
|
+
* This is intentionally shared only as a validator. V1 and V2 entry points
|
|
110
|
+
* below remain separate capability probes and do not fall back to one another.
|
|
111
|
+
*/
|
|
112
|
+
function probeExactData(
|
|
113
|
+
apiVersion: CapabilityProbeVersion,
|
|
114
|
+
input: unknown,
|
|
115
|
+
): ProviderCapabilityResult {
|
|
116
|
+
if (!isRecord(input)) return unsupported(apiVersion, 'MISSING_SESSION_ID')
|
|
117
|
+
|
|
118
|
+
if (!isNonEmptyString(input.sessionId)) {
|
|
119
|
+
return unsupported(apiVersion, 'MISSING_SESSION_ID')
|
|
120
|
+
}
|
|
121
|
+
if (!isNonEmptyString(input.providerId)) {
|
|
122
|
+
return unsupported(apiVersion, 'MISSING_PROVIDER_ID')
|
|
123
|
+
}
|
|
124
|
+
if (!isNonEmptyString(input.modelId)) {
|
|
125
|
+
return unsupported(apiVersion, 'MISSING_MODEL_ID')
|
|
126
|
+
}
|
|
127
|
+
if (!isRecord(input.usage)) return unsupported(apiVersion, 'MISSING_USAGE')
|
|
128
|
+
if (!isRecord(input.limit)) return unsupported(apiVersion, 'MISSING_LIMIT')
|
|
129
|
+
if (!hasOnlyKeys(input.usage, ['inputTokens', 'outputTokens'])) {
|
|
130
|
+
return unsupported(apiVersion, 'INVALID_USAGE')
|
|
131
|
+
}
|
|
132
|
+
if (!hasOnlyKeys(input.limit, ['contextTokens'])) {
|
|
133
|
+
return unsupported(apiVersion, 'INVALID_LIMIT')
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const usage = input.usage
|
|
137
|
+
if (!isFiniteNonNegativeNumber(usage.inputTokens)) {
|
|
138
|
+
return unsupported(apiVersion, 'INVALID_USAGE')
|
|
139
|
+
}
|
|
140
|
+
if (!isFiniteNonNegativeNumber(usage.outputTokens)) {
|
|
141
|
+
return unsupported(apiVersion, 'INVALID_USAGE')
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const limit = input.limit
|
|
145
|
+
if (!isFiniteNonNegativeNumber(limit.contextTokens)) {
|
|
146
|
+
return unsupported(apiVersion, 'INVALID_LIMIT')
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
let resetAt: number | undefined
|
|
150
|
+
if ('reset' in input) return unsupported(apiVersion, 'INVALID_RESET')
|
|
151
|
+
if ('resetAt' in input) {
|
|
152
|
+
const value = input.resetAt
|
|
153
|
+
if (!isFiniteNonNegativeNumber(value)) return unsupported(apiVersion, 'INVALID_RESET')
|
|
154
|
+
resetAt = value
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const data: ExactProviderUsageData = {
|
|
158
|
+
sessionId: input.sessionId,
|
|
159
|
+
providerId: input.providerId,
|
|
160
|
+
modelId: input.modelId,
|
|
161
|
+
usage: {
|
|
162
|
+
inputTokens: usage.inputTokens,
|
|
163
|
+
outputTokens: usage.outputTokens,
|
|
164
|
+
},
|
|
165
|
+
limit: { contextTokens: limit.contextTokens },
|
|
166
|
+
}
|
|
167
|
+
if (resetAt !== undefined) data.resetAt = resetAt
|
|
168
|
+
|
|
169
|
+
return { apiVersion, status: USAGE_STATUS.SUPPORTED, data }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Probe the V1 exact payload shape supplied by a caller.
|
|
174
|
+
*
|
|
175
|
+
* V1 does not inherit V2 capability, credentials, cache, or lifecycle data.
|
|
176
|
+
* The caller must pass the exact payload after its host-specific extraction.
|
|
177
|
+
*/
|
|
178
|
+
export function probeV1Capability(input: unknown): ProviderCapabilityResult {
|
|
179
|
+
return probeExactData('v1', input)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Probe the V2 exact payload shape supplied by a caller.
|
|
184
|
+
*
|
|
185
|
+
* V2 is intentionally independent from V1: no V1 event, retry, cache, or
|
|
186
|
+
* fallback value is consulted when the exact payload is absent.
|
|
187
|
+
*/
|
|
188
|
+
export function probeV2Capability(input: unknown): ProviderCapabilityResult {
|
|
189
|
+
return probeExactData('v2', input)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Validate one complete stream event using the same exact data contract. */
|
|
193
|
+
export function validateProviderUsageEvent(input: unknown): ProviderUsageEvent | null {
|
|
194
|
+
if (!isRecord(input)) return null
|
|
195
|
+
if (!isNonEmptyString(input.eventId) || !isNonEmptyString(input.partId)) return null
|
|
196
|
+
|
|
197
|
+
const data = probeExactData('v1', input)
|
|
198
|
+
if (data.status !== USAGE_STATUS.SUPPORTED) return null
|
|
199
|
+
|
|
200
|
+
let sequence: number | undefined
|
|
201
|
+
if ('sequence' in input) {
|
|
202
|
+
const value = input.sequence
|
|
203
|
+
if (!isFiniteNonNegativeNumber(value) || !Number.isInteger(value)) return null
|
|
204
|
+
sequence = value
|
|
205
|
+
}
|
|
206
|
+
let observedAt: number | undefined
|
|
207
|
+
if ('observedAt' in input) {
|
|
208
|
+
const value = input.observedAt
|
|
209
|
+
if (!isFiniteNonNegativeNumber(value)) return null
|
|
210
|
+
observedAt = value
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const event: ProviderUsageEvent = {
|
|
214
|
+
...data.data,
|
|
215
|
+
eventId: input.eventId,
|
|
216
|
+
partId: input.partId,
|
|
217
|
+
}
|
|
218
|
+
if (sequence !== undefined) event.sequence = sequence
|
|
219
|
+
if (observedAt !== undefined) event.observedAt = observedAt
|
|
220
|
+
return event
|
|
221
|
+
}
|