pantheon-opencode 1.3.5-beta.60.efa533f → 1.3.6

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 (75) hide show
  1. package/README.md +38 -6
  2. package/package.json +4 -3
  3. package/scripts/_pantheon_paths.py +0 -1
  4. package/scripts/build-agents-md.mjs +4 -2
  5. package/scripts/code_mode_server.py +307 -21
  6. package/scripts/doctor.mjs +58 -15
  7. package/scripts/hooks/format-multi-language.sh +6 -3
  8. package/scripts/hooks/log-session-start.sh +6 -0
  9. package/scripts/hooks/on-subagent-delegation-start.sh +22 -6
  10. package/scripts/hooks/validate-post-conditions.sh +1 -1
  11. package/scripts/hooks/validate-tool-safety.sh +5 -2
  12. package/scripts/install/agents-md.mjs +3 -1
  13. package/scripts/install/cli-ui.mjs +24 -4
  14. package/scripts/install/interactive.mjs +18 -7
  15. package/scripts/install/migrate-config.mjs +13 -19
  16. package/scripts/install/migrate.mjs +8 -5
  17. package/scripts/install/model-picker.mjs +4 -1
  18. package/scripts/install/opencode.mjs +8 -2
  19. package/scripts/install/shared.mjs +8 -4
  20. package/scripts/install/state.mjs +9 -6
  21. package/scripts/mcp_persistence_server.py +23 -22
  22. package/scripts/mcp_resources_server.py +60 -1
  23. package/scripts/memory_mcp_server.py +80 -4
  24. package/scripts/postinstall.mjs +27 -25
  25. package/scripts/prune.mjs +1 -1
  26. package/scripts/redaction-gate.mjs +3 -1
  27. package/scripts/uninstall.mjs +0 -2
  28. package/scripts/validation-policy.mjs +6 -1
  29. package/scripts/version-check.mjs +9 -4
  30. package/src/agents/aphrodite.md +1 -1
  31. package/src/agents/apollo.md +3 -0
  32. package/src/agents/demeter.md +1 -1
  33. package/src/agents/gaia.md +3 -0
  34. package/src/agents/hephaestus.md +1 -1
  35. package/src/agents/hermes.md +1 -1
  36. package/src/agents/themis.md +4 -0
  37. package/src/agents/zeus.md +5 -1
  38. package/src/mcp/code_mode_server.py +304 -18
  39. package/src/mcp/eval_store.py +233 -0
  40. package/src/mcp/mcp_persistence_server.py +23 -22
  41. package/src/mcp/mcp_resources_server.py +58 -0
  42. package/src/mcp/memory_mcp_server.py +80 -3
  43. package/src/pantheon/auto-wake.ts +2 -4
  44. package/src/pantheon/background-job-board.ts +17 -4
  45. package/src/pantheon/comment-checker.ts +48 -0
  46. package/src/pantheon/delegation-classifier.ts +307 -0
  47. package/src/pantheon/delegation-enforce.ts +67 -3
  48. package/src/pantheon/delegation-finalize.ts +44 -4
  49. package/src/pantheon/delegation.ts +413 -30
  50. package/src/pantheon/dispatch-guard.ts +2 -0
  51. package/src/pantheon/file-persistence.ts +7 -3
  52. package/src/pantheon/goal-loop.ts +13 -2
  53. package/src/pantheon/permission-eval.ts +284 -0
  54. package/src/pantheon/permission-globs.ts +86 -0
  55. package/src/pantheon/presets.d.mts +41 -0
  56. package/src/pantheon/presets.mjs +135 -0
  57. package/src/pantheon/retry-policy.ts +212 -0
  58. package/src/pantheon/session-guard.ts +48 -0
  59. package/src/pantheon/step-cap.ts +110 -0
  60. package/src/pantheon/todo-enforcer.ts +31 -5
  61. package/src/pantheon/todo-preserve.ts +7 -1
  62. package/src/pantheon/vision.ts +7 -5
  63. package/src/pantheon/zeus-delegate-with-retry.ts +401 -0
  64. package/src/plugin.ts +72 -13
  65. package/src/plugins/hook-runner.ts +1 -1
  66. package/src/plugins/pantheon-hooks.ts +1 -1
  67. package/src/plugins/tui/dist/tui.d.ts +1 -1
  68. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  69. package/src/plugins/tui/dist/tui.js +36 -14
  70. package/src/plugins/tui/dist/tui.tsx +71 -16
  71. package/src/plugins/tui/package.json +1 -1
  72. package/src/plugins/tui/src/index.tsx +71 -16
  73. package/src/plugins/tui/tsdown.config.ts +1 -1
  74. package/src/routing.yml +47 -0
  75. package/src/agents/README.md +0 -26
@@ -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,86 @@
1
+ /**
2
+ * O5 — Permission globs for delegation (permission.task model).
3
+ *
4
+ * Pure library. Glob patterns control which subagents an agent may invoke
5
+ * (routing.yml `permission.task`, e.g. `"*": "deny", "orchestrator-*":
6
+ * "allow"`). Last matching rule wins; a deny removes the agent from the
7
+ * delegate tool description entirely (not just blocks the call) — this
8
+ * prevents circular delegation at the permission layer.
9
+ *
10
+ * @module permission-globs
11
+ */
12
+
13
+ // ─── Types ─────────────────────────────────────────────────────────────
14
+
15
+ export type PermissionAction = 'allow' | 'deny'
16
+
17
+ /** Glob pattern → action map (insertion order = rule order). */
18
+ export type PermissionTaskConfig = Readonly<Record<string, PermissionAction>>
19
+
20
+ // ─── Glob matching ─────────────────────────────────────────────────────
21
+
22
+ /**
23
+ * Convert a glob pattern to an anchored RegExp. `*` matches any sequence
24
+ * (including empty), `?` matches exactly one character; everything else is
25
+ * literal. The pattern must match the WHOLE agent name.
26
+ */
27
+ export function globToRegExp(pattern: string): RegExp {
28
+ const escaped = pattern
29
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
30
+ .replace(/\*/g, '.*')
31
+ .replace(/\?/g, '.')
32
+ return new RegExp(`^${escaped}$`)
33
+ }
34
+
35
+ /**
36
+ * Evaluate a permission.task config against an agent name. Iterates rules
37
+ * in insertion order and keeps the LAST match — last matching rule wins.
38
+ * Returns undefined when no rule matches.
39
+ */
40
+ export function matchPermissionRule(
41
+ rules: PermissionTaskConfig,
42
+ agentName: string,
43
+ ): PermissionAction | undefined {
44
+ let matched: PermissionAction | undefined
45
+ for (const [pattern, action] of Object.entries(rules)) {
46
+ if (globToRegExp(pattern).test(agentName)) matched = action
47
+ }
48
+ return matched
49
+ }
50
+
51
+ /**
52
+ * Whether an agent may be invoked as a subagent. No rules (or empty) →
53
+ * allowed (the existing runtime matrix still applies). Otherwise the last
54
+ * matching rule decides; only an explicit 'allow' permits the agent.
55
+ */
56
+ export function isAgentAllowed(
57
+ rules: PermissionTaskConfig | undefined,
58
+ agentName: string,
59
+ ): boolean {
60
+ if (rules === undefined || Object.keys(rules).length === 0) return true
61
+ return matchPermissionRule(rules, agentName) === 'allow'
62
+ }
63
+
64
+ /**
65
+ * The allowed subset of a candidate agent list — denied agents are removed
66
+ * entirely (they never appear in the delegate tool description).
67
+ */
68
+ export function filterAllowedAgents(
69
+ rules: PermissionTaskConfig | undefined,
70
+ agentNames: readonly string[],
71
+ ): string[] {
72
+ return agentNames.filter((name) => isAgentAllowed(rules, name))
73
+ }
74
+
75
+ /**
76
+ * Render the delegate tool description's allowed-agent list. Denied agents
77
+ * are removed entirely (not just blocked at call time).
78
+ */
79
+ export function buildAgentListDescription(
80
+ rules: PermissionTaskConfig | undefined,
81
+ agentNames: readonly string[],
82
+ ): string {
83
+ const allowed = filterAllowedAgents(rules, agentNames)
84
+ if (allowed.length === 0) return 'no subagents available (all denied by permission.task)'
85
+ return allowed.join(', ')
86
+ }
@@ -98,6 +98,47 @@ export declare function loadRoutingAgentModels(
98
98
  options?: RoutingAgentModelsOptions,
99
99
  ): Record<string, string>
100
100
 
101
+ export interface RoutingRetryPolicyOptions {
102
+ routingPath?: string
103
+ logger?: { warn?: (msg: string) => void }
104
+ }
105
+
106
+ /**
107
+ * R1: per-error-type retry policy from routing.yml `retry_policy`
108
+ * (auth/rate_limit/timeout/other → max retries). Fail-open → null.
109
+ */
110
+ export declare function loadRoutingRetryPolicy(
111
+ options?: RoutingRetryPolicyOptions,
112
+ ): Record<string, number> | null
113
+
114
+ export interface RoutingCooldownResult {
115
+ allowed_fails: number
116
+ cooldown_time_seconds: number
117
+ }
118
+
119
+ /**
120
+ * R1: provider cooldown config from routing.yml `cooldown`. Fail-open → null.
121
+ */
122
+ export declare function loadRoutingCooldown(
123
+ options?: RoutingRetryPolicyOptions,
124
+ ): RoutingCooldownResult | null
125
+
126
+ /**
127
+ * R4: per-agent step caps from routing.yml `agents.<name>.max_steps`.
128
+ * Fail-open → {} (no agent capped).
129
+ */
130
+ export declare function loadRoutingMaxSteps(
131
+ options?: RoutingRetryPolicyOptions,
132
+ ): Record<string, number>
133
+
134
+ /**
135
+ * O5: permission.task glob rules from routing.yml `permission.task`
136
+ * (glob pattern → 'allow' | 'deny'). Fail-open → null.
137
+ */
138
+ export declare function loadRoutingPermissionTask(
139
+ options?: RoutingRetryPolicyOptions,
140
+ ): Record<string, 'allow' | 'deny'> | null
141
+
101
142
  export declare function resolveActivePreset(options?: ResolveOptions): ResolvedPreset | null
102
143
 
103
144
  export declare function applyActivePresetToConfig<C extends object>(
@@ -210,6 +210,140 @@ export function loadPresetDefs(routingPath) {
210
210
  return (routing && typeof routing === 'object' && routing.presets) || {}
211
211
  }
212
212
 
213
+ /**
214
+ * Load and parse the full routing.yml document (fail-open helper for the
215
+ * R1/R4/O5 config loaders below).
216
+ *
217
+ * @param {string} [routingPath] defaults to src/routing.yml
218
+ * @returns {object|null} parsed routing.yml, or null when unreadable
219
+ */
220
+ function loadRoutingYaml(routingPath) {
221
+ const path = routingPath ?? fileURLToPath(new URL('../routing.yml', import.meta.url))
222
+ const raw = readFileSync(path, 'utf8')
223
+ const routing = yaml.load(raw)
224
+ return routing && typeof routing === 'object' ? routing : null
225
+ }
226
+
227
+ const RETRY_ERROR_TYPES = new Set(['auth', 'rate_limit', 'timeout', 'other'])
228
+
229
+ /**
230
+ * Load the R1 per-error-type retry policy from routing.yml (`retry_policy:`).
231
+ * Fail-open: missing/unparseable config yields null (the caller falls back
232
+ * to DEFAULT_RETRY_POLICY) and warns via the optional logger.
233
+ *
234
+ * @param {object} [opts]
235
+ * @param {string} [opts.routingPath]
236
+ * @param {{warn?: Function}} [opts.logger]
237
+ * @returns {Record<string, number>|null} error-type → max retries
238
+ */
239
+ export function loadRoutingRetryPolicy({ routingPath, logger = console } = {}) {
240
+ try {
241
+ const routing = loadRoutingYaml(routingPath)
242
+ const policy = routing?.retry_policy
243
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy)) return null
244
+ const out = {}
245
+ for (const [type, max] of Object.entries(policy)) {
246
+ if (RETRY_ERROR_TYPES.has(type) && Number.isSafeInteger(max) && max >= 0) {
247
+ out[type] = max
248
+ }
249
+ }
250
+ return Object.keys(out).length > 0 ? out : null
251
+ } catch (err) {
252
+ const reason = err instanceof Error ? err.message : String(err)
253
+ logger.warn?.(`presets: routing.yml retry_policy unavailable (${reason})`)
254
+ return null
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Load the R1 provider cooldown config from routing.yml (`cooldown:`).
260
+ * Fail-open: missing/unparseable config yields null (caller falls back to
261
+ * DEFAULT_COOLDOWN).
262
+ *
263
+ * @param {object} [opts]
264
+ * @param {string} [opts.routingPath]
265
+ * @param {{warn?: Function}} [opts.logger]
266
+ * @returns {{allowed_fails: number, cooldown_time_seconds: number}|null}
267
+ */
268
+ export function loadRoutingCooldown({ routingPath, logger = console } = {}) {
269
+ try {
270
+ const routing = loadRoutingYaml(routingPath)
271
+ const cooldown = routing?.cooldown
272
+ if (!cooldown || typeof cooldown !== 'object' || Array.isArray(cooldown)) return null
273
+ const allowedFails = cooldown.allowed_fails
274
+ const cooldownTimeSeconds = cooldown.cooldown_time_seconds
275
+ if (
276
+ !Number.isSafeInteger(allowedFails) ||
277
+ allowedFails < 1 ||
278
+ !Number.isSafeInteger(cooldownTimeSeconds) ||
279
+ cooldownTimeSeconds < 1
280
+ ) {
281
+ return null
282
+ }
283
+ return { allowed_fails: allowedFails, cooldown_time_seconds: cooldownTimeSeconds }
284
+ } catch (err) {
285
+ const reason = err instanceof Error ? err.message : String(err)
286
+ logger.warn?.(`presets: routing.yml cooldown unavailable (${reason})`)
287
+ return null
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Load the R4 per-agent step caps from routing.yml
293
+ * (`agents.<name>.max_steps`). Fail-open: missing config yields {}.
294
+ *
295
+ * @param {object} [opts]
296
+ * @param {string} [opts.routingPath]
297
+ * @param {{warn?: Function}} [opts.logger]
298
+ * @returns {Record<string, number>} lowercase agent → max_steps
299
+ */
300
+ export function loadRoutingMaxSteps({ routingPath, logger = console } = {}) {
301
+ try {
302
+ const routing = loadRoutingYaml(routingPath)
303
+ const agents = routing?.agents
304
+ if (!agents || typeof agents !== 'object') return {}
305
+ const out = {}
306
+ for (const [agent, spec] of Object.entries(agents)) {
307
+ const maxSteps = spec && typeof spec === 'object' ? spec.max_steps : undefined
308
+ if (Number.isSafeInteger(maxSteps) && maxSteps > 0) {
309
+ out[agent.toLowerCase()] = maxSteps
310
+ }
311
+ }
312
+ return out
313
+ } catch (err) {
314
+ const reason = err instanceof Error ? err.message : String(err)
315
+ logger.warn?.(`presets: routing.yml max_steps unavailable (${reason})`)
316
+ return {}
317
+ }
318
+ }
319
+
320
+ /**
321
+ * Load the O5 permission.task glob rules from routing.yml
322
+ * (`permission.task:`). Fail-open: missing config yields null (caller keeps
323
+ * the existing runtime matrix, everything allowed).
324
+ *
325
+ * @param {object} [opts]
326
+ * @param {string} [opts.routingPath]
327
+ * @param {{warn?: Function}} [opts.logger]
328
+ * @returns {Record<string, 'allow'|'deny'>|null} glob pattern → action
329
+ */
330
+ export function loadRoutingPermissionTask({ routingPath, logger = console } = {}) {
331
+ try {
332
+ const routing = loadRoutingYaml(routingPath)
333
+ const task = routing?.permission?.task
334
+ if (!task || typeof task !== 'object' || Array.isArray(task)) return null
335
+ const out = {}
336
+ for (const [pattern, action] of Object.entries(task)) {
337
+ if (action === 'allow' || action === 'deny') out[pattern] = action
338
+ }
339
+ return Object.keys(out).length > 0 ? out : null
340
+ } catch (err) {
341
+ const reason = err instanceof Error ? err.message : String(err)
342
+ logger.warn?.(`presets: routing.yml permission.task unavailable (${reason})`)
343
+ return null
344
+ }
345
+ }
346
+
213
347
  /**
214
348
  * Load the DEFAULT agent → model mapping from routing.yml for the delegation
215
349
  * toolset (Fase 6 — wiring agentModels).
@@ -402,6 +536,7 @@ function providerDefKeyConfigured(provider, env) {
402
536
  * @returns {string|undefined} missing env var name, or undefined when usable
403
537
  */
404
538
  export function missingProviderKeyEnv(providerID, { env = process.env, routingPath } = {}) {
539
+ if (providerID === 'opencode-go') return undefined
405
540
  const defs = loadPresetDefs(routingPath)
406
541
  for (const def of Object.values(defs)) {
407
542
  const provider = def?.providers?.[providerID]