pantheon-opencode 1.3.5 → 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 (68) hide show
  1. package/README.md +33 -1
  2. package/package.json +3 -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 +26 -13
  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 +2 -0
  19. package/scripts/install/shared.mjs +6 -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/demeter.md +1 -1
  32. package/src/agents/hephaestus.md +1 -1
  33. package/src/agents/hermes.md +1 -1
  34. package/src/agents/themis.md +4 -0
  35. package/src/mcp/code_mode_server.py +304 -18
  36. package/src/mcp/eval_store.py +233 -0
  37. package/src/mcp/mcp_persistence_server.py +23 -22
  38. package/src/mcp/mcp_resources_server.py +58 -0
  39. package/src/mcp/memory_mcp_server.py +80 -3
  40. package/src/pantheon/auto-wake.ts +2 -4
  41. package/src/pantheon/background-job-board.ts +17 -4
  42. package/src/pantheon/comment-checker.ts +48 -0
  43. package/src/pantheon/delegation-classifier.ts +307 -0
  44. package/src/pantheon/delegation-enforce.ts +21 -21
  45. package/src/pantheon/delegation-finalize.ts +44 -4
  46. package/src/pantheon/delegation.ts +403 -23
  47. package/src/pantheon/dispatch-guard.ts +2 -0
  48. package/src/pantheon/file-persistence.ts +7 -3
  49. package/src/pantheon/permission-eval.ts +284 -0
  50. package/src/pantheon/permission-globs.ts +86 -0
  51. package/src/pantheon/presets.d.mts +41 -0
  52. package/src/pantheon/presets.mjs +134 -0
  53. package/src/pantheon/retry-policy.ts +212 -0
  54. package/src/pantheon/session-guard.ts +1 -3
  55. package/src/pantheon/step-cap.ts +110 -0
  56. package/src/pantheon/vision.ts +7 -5
  57. package/src/pantheon/zeus-delegate-with-retry.ts +81 -12
  58. package/src/plugin.ts +28 -3
  59. package/src/plugins/hook-runner.ts +1 -1
  60. package/src/plugins/pantheon-hooks.ts +1 -1
  61. package/src/plugins/tui/dist/tui.d.ts +1 -1
  62. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  63. package/src/plugins/tui/dist/tui.js +19 -14
  64. package/src/plugins/tui/dist/tui.tsx +52 -18
  65. package/src/plugins/tui/package.json +1 -1
  66. package/src/plugins/tui/src/index.tsx +52 -18
  67. package/src/plugins/tui/tsdown.config.ts +1 -1
  68. package/src/routing.yml +42 -0
@@ -0,0 +1,212 @@
1
+ /**
2
+ * R1 — Per-error-type retry + provider cooldown (LiteLLM pattern).
3
+ *
4
+ * Pure library (no SDK, no I/O). When a delegation fails, the error is
5
+ * classified (auth | rate_limit | timeout | other), the per-error-type
6
+ * retry policy from routing.yml `retry_policy` is applied with exponential
7
+ * backoff, and provider cooldown state (routing.yml `cooldown`) is tracked
8
+ * in-memory: after `allowed_fails` consecutive failures a provider is
9
+ * skipped for `cooldown_time_seconds`; a success resets the counter.
10
+ *
11
+ * YAGNI: no usage-based routing, no Redis — a simple in-memory cooldown
12
+ * map plus config.
13
+ *
14
+ * @module retry-policy
15
+ */
16
+
17
+ // ─── Types ─────────────────────────────────────────────────────────────
18
+
19
+ /** Error classes a delegation failure can be classified into. */
20
+ export type ErrorType = 'auth' | 'rate_limit' | 'timeout' | 'other'
21
+
22
+ /** Max retries per error class (routing.yml `retry_policy`). */
23
+ export interface RetryPolicy {
24
+ auth: number
25
+ rate_limit: number
26
+ timeout: number
27
+ other: number
28
+ }
29
+
30
+ /** Provider cooldown config (routing.yml `cooldown`). */
31
+ export interface CooldownConfig {
32
+ /** Consecutive failures before the provider is skipped. */
33
+ allowedFails: number
34
+ /** How long the provider stays skipped, in seconds. */
35
+ cooldownTimeSeconds: number
36
+ }
37
+
38
+ /** Defaults matching routing.yml `retry_policy`. */
39
+ export const DEFAULT_RETRY_POLICY: RetryPolicy = {
40
+ auth: 0,
41
+ rate_limit: 3,
42
+ timeout: 2,
43
+ other: 1,
44
+ }
45
+
46
+ /** Defaults matching routing.yml `cooldown`. */
47
+ export const DEFAULT_COOLDOWN: CooldownConfig = {
48
+ allowedFails: 3,
49
+ cooldownTimeSeconds: 60,
50
+ }
51
+
52
+ // ─── Error classification ──────────────────────────────────────────────
53
+
54
+ const AUTH_RE = /(auth|unauthorized|401|403|api[ _-]?key|invalid credential|permission denied)/i
55
+ const RATE_LIMIT_RE = /(rate[ _-]?limit|429|too many requests|quota|throttl)/i
56
+ const TIMEOUT_RE = /(timeout|timed out|deadline|504|408|etimedout)/i
57
+
58
+ /**
59
+ * Classify a thrown error into one of the four retry-policy buckets.
60
+ * Message-based matching (LiteLLM pattern); unknown errors → 'other'.
61
+ */
62
+ export function classifyError(err: unknown): ErrorType {
63
+ const message = err instanceof Error ? err.message : String(err ?? '')
64
+ if (AUTH_RE.test(message)) return 'auth'
65
+ if (RATE_LIMIT_RE.test(message)) return 'rate_limit'
66
+ if (TIMEOUT_RE.test(message)) return 'timeout'
67
+ return 'other'
68
+ }
69
+
70
+ // ─── Exponential backoff ───────────────────────────────────────────────
71
+
72
+ /**
73
+ * Exponential backoff delay for a retry attempt (0-based): base * 2^attempt,
74
+ * capped at maxMs. attempt 0 → base, attempt 1 → 2x base, etc.
75
+ */
76
+ export function computeBackoffMs(attempt: number, baseMs = 1000, maxMs = 30_000): number {
77
+ const delay = baseMs * 2 ** attempt
78
+ return Math.min(delay, maxMs)
79
+ }
80
+
81
+ // ─── Provider cooldown tracker ─────────────────────────────────────────
82
+
83
+ interface CooldownEntry {
84
+ fails: number
85
+ cooldownUntil: number
86
+ }
87
+
88
+ /**
89
+ * In-memory provider cooldown state. After `allowedFails` consecutive
90
+ * failures a provider is skipped until `cooldownUntil`; a success resets
91
+ * the counter. The clock is injectable for tests.
92
+ */
93
+ export class ProviderCooldownTracker {
94
+ private readonly state = new Map<string, CooldownEntry>()
95
+ readonly config: CooldownConfig
96
+
97
+ constructor(config: CooldownConfig = DEFAULT_COOLDOWN) {
98
+ this.config = config
99
+ }
100
+
101
+ /** Record one failure for a provider; trips cooldown at allowedFails. */
102
+ recordFailure(provider: string): void {
103
+ const entry = this.state.get(provider) ?? { fails: 0, cooldownUntil: 0 }
104
+ entry.fails += 1
105
+ if (entry.fails >= this.config.allowedFails) {
106
+ entry.cooldownUntil = Date.now() + this.config.cooldownTimeSeconds * 1000
107
+ }
108
+ this.state.set(provider, entry)
109
+ }
110
+
111
+ /** Record a success — resets the failure counter (no spurious cooldown). */
112
+ recordSuccess(provider: string): void {
113
+ this.state.delete(provider)
114
+ }
115
+
116
+ /**
117
+ * Whether the provider is currently skipped. Expired cooldowns are
118
+ * cleared; entries that never tripped (cooldownUntil 0) are kept so the
119
+ * consecutive-failure counter survives the check.
120
+ */
121
+ isInCooldown(provider: string, now = Date.now()): boolean {
122
+ const entry = this.state.get(provider)
123
+ if (entry === undefined) return false
124
+ if (entry.cooldownUntil > now) return true
125
+ if (entry.cooldownUntil > 0) this.state.delete(provider)
126
+ return false
127
+ }
128
+
129
+ /** Remaining cooldown time in ms (0 when not in cooldown). */
130
+ remainingCooldownMs(provider: string, now = Date.now()): number {
131
+ const entry = this.state.get(provider)
132
+ if (entry === undefined) return 0
133
+ return Math.max(0, entry.cooldownUntil - now)
134
+ }
135
+
136
+ /** Current consecutive failure count for a provider. */
137
+ failCount(provider: string): number {
138
+ return this.state.get(provider)?.fails ?? 0
139
+ }
140
+ }
141
+
142
+ // ─── Retry policy engine ───────────────────────────────────────────────
143
+
144
+ export type RetryDecisionReason = 'policy' | 'cooldown'
145
+
146
+ export interface RetryDecision {
147
+ shouldRetry: boolean
148
+ /** Retries still available for this error class (0 when exhausted). */
149
+ retriesRemaining: number
150
+ /** Backoff delay to wait before the next attempt (ms). */
151
+ delayMs: number
152
+ /** Why the decision was made: policy budget or provider cooldown. */
153
+ reason: RetryDecisionReason
154
+ }
155
+
156
+ /**
157
+ * Combines error classification, the per-error-type retry policy, and the
158
+ * provider cooldown tracker into one decision point. Enforcement: when a
159
+ * delegation fails, call `decide(provider, err, attemptsUsed)`; when the
160
+ * result is content, call `recordSuccess`; when the budget is exhausted,
161
+ * call `recordFailure` so the cooldown can trip.
162
+ */
163
+ export class RetryPolicyEngine {
164
+ private readonly cooldown: ProviderCooldownTracker
165
+ readonly policy: RetryPolicy
166
+ readonly backoffBaseMs: number
167
+
168
+ constructor(
169
+ policy: RetryPolicy = DEFAULT_RETRY_POLICY,
170
+ cooldown?: ProviderCooldownTracker,
171
+ backoffBaseMs = 1000,
172
+ ) {
173
+ this.policy = policy
174
+ this.backoffBaseMs = backoffBaseMs
175
+ this.cooldown = cooldown ?? new ProviderCooldownTracker()
176
+ }
177
+
178
+ /**
179
+ * Decide whether a failed dispatch should be retried.
180
+ *
181
+ * @param provider provider name (cooldown key, e.g. "opencode")
182
+ * @param err the failure (classified into auth/rate_limit/timeout/other)
183
+ * @param attemptsUsed retries already consumed for this dispatch
184
+ * @param now injectable clock (tests)
185
+ */
186
+ decide(provider: string, err: unknown, attemptsUsed: number, now = Date.now()): RetryDecision {
187
+ if (this.cooldown.isInCooldown(provider, now)) {
188
+ return { shouldRetry: false, retriesRemaining: 0, delayMs: 0, reason: 'cooldown' }
189
+ }
190
+ const type = classifyError(err)
191
+ const retriesRemaining = Math.max(0, this.policy[type] - attemptsUsed)
192
+ if (retriesRemaining <= 0) {
193
+ return { shouldRetry: false, retriesRemaining: 0, delayMs: 0, reason: 'policy' }
194
+ }
195
+ return {
196
+ shouldRetry: true,
197
+ retriesRemaining,
198
+ delayMs: computeBackoffMs(attemptsUsed, this.backoffBaseMs),
199
+ reason: 'policy',
200
+ }
201
+ }
202
+
203
+ /** Record a failure (feeds the cooldown tracker). */
204
+ recordFailure(provider: string, _err: unknown): void {
205
+ this.cooldown.recordFailure(provider)
206
+ }
207
+
208
+ /** Record a success (resets the provider's failure counter). */
209
+ recordSuccess(provider: string): void {
210
+ this.cooldown.recordSuccess(provider)
211
+ }
212
+ }
@@ -43,8 +43,6 @@ export function safeSessionPath(id: unknown): { path: { id: string } } | null {
43
43
  * Delegates to {@link safeSessionPath} — the single choke point. Returns
44
44
  * null for null/invalid ids so the caller skips the fetch.
45
45
  */
46
- export function buildChildrenPath(
47
- id: string | null | undefined,
48
- ): { path: { id: string } } | null {
46
+ export function buildChildrenPath(id: string | null | undefined): { path: { id: string } } | null {
49
47
  return safeSessionPath(id)
50
48
  }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * R4 — Per-agent step caps (max_steps).
3
+ *
4
+ * Pure library. routing.yml `agents.<name>.max_steps` gives each agent a
5
+ * step budget (e.g. explore: 25, reviewer: 25, oracle: 15). When an agent's
6
+ * step count reaches max_steps it is forced to summarize-and-stop: the
7
+ * delegation is either skipped with a capped summary (already at cap) or
8
+ * the prompt is appended with a stop instruction (cap hit mid-dispatch).
9
+ *
10
+ * The tracker is PERMANENT-PER-PROCESS: counters accumulate for the process
11
+ * lifetime and are intentionally NOT reset on successful delegations or
12
+ * session end — a per-session reset would let an agent exceed its process
13
+ * budget over a long session. `reset()` exists as a tested utility for
14
+ * tests and future explicit reset points; no production caller wires it.
15
+ *
16
+ * @module step-cap
17
+ */
18
+
19
+ // ─── Types ─────────────────────────────────────────────────────────────
20
+
21
+ /** Default step budget when routing.yml omits max_steps for an agent. */
22
+ export const DEFAULT_MAX_STEPS = 25
23
+
24
+ // ─── Stop instruction ──────────────────────────────────────────────────
25
+
26
+ /**
27
+ * The forced summarize-and-stop instruction injected into a prompt when an
28
+ * agent's step count reaches max_steps.
29
+ */
30
+ export function buildStopInstruction(agent: string, maxSteps: number): string {
31
+ return (
32
+ `\n\n[STEP CAP REACHED — ${agent} at ${maxSteps} steps] ` +
33
+ `You have reached the maximum step budget for this delegation. ` +
34
+ `STOP working immediately and summarize what was accomplished (and ` +
35
+ `what remains, if any) as your final message. Do not start new work.`
36
+ )
37
+ }
38
+
39
+ /**
40
+ * The text returned when a delegation is skipped because the agent is
41
+ * already at its step cap — marks the delegation as capped and asks for a
42
+ * summary of prior results instead of starting new work.
43
+ */
44
+ export function cappedSummary(agent: string, maxSteps: number): string {
45
+ return (
46
+ `[STEP CAP REACHED] ${agent} has reached its max_steps budget (${maxSteps}). ` +
47
+ `Delegation skipped — no new work was started. ` +
48
+ `Summarize prior results and stop.`
49
+ )
50
+ }
51
+
52
+ // ─── Tracker ───────────────────────────────────────────────────────────
53
+
54
+ /**
55
+ * Per-agent step counters with a max_steps budget. Keyed by lowercase agent
56
+ * name (matching is case-insensitive). Agents without a configured budget
57
+ * are never capped.
58
+ */
59
+ export class StepCapTracker {
60
+ private readonly steps = new Map<string, number>()
61
+ readonly maxStepsByAgent: Readonly<Record<string, number>>
62
+
63
+ constructor(maxStepsByAgent: Readonly<Record<string, number>> = {}) {
64
+ this.maxStepsByAgent = maxStepsByAgent
65
+ }
66
+
67
+ /** The configured budget for an agent, or undefined when uncapped. */
68
+ maxStepsFor(agent: string): number | undefined {
69
+ return this.maxStepsByAgent[agent.toLowerCase()]
70
+ }
71
+
72
+ /** Current step count for an agent. */
73
+ stepCount(agent: string): number {
74
+ return this.steps.get(agent.toLowerCase()) ?? 0
75
+ }
76
+
77
+ /** Whether the agent has reached (or exceeded) its max_steps budget. */
78
+ isCapped(agent: string): boolean {
79
+ const max = this.maxStepsFor(agent)
80
+ if (max === undefined) return false
81
+ return this.stepCount(agent) >= max
82
+ }
83
+
84
+ /**
85
+ * Record one step for an agent. Returns the new count and whether this
86
+ * step hit the cap (capped === true exactly when steps >= maxSteps).
87
+ */
88
+ recordStep(agent: string): {
89
+ steps: number
90
+ capped: boolean
91
+ maxSteps: number | undefined
92
+ } {
93
+ const key = agent.toLowerCase()
94
+ const max = this.maxStepsFor(agent)
95
+ const steps = (this.steps.get(key) ?? 0) + 1
96
+ this.steps.set(key, steps)
97
+ return { steps, capped: max !== undefined && steps >= max, maxSteps: max }
98
+ }
99
+
100
+ /**
101
+ * Reset an agent's step count.
102
+ *
103
+ * Intentionally NOT wired in production: the tracker is permanent-per-
104
+ * process (see module docstring) so agents cannot exceed their process
105
+ * budget via resets. Exists for tests and future explicit reset points.
106
+ */
107
+ reset(agent: string): void {
108
+ this.steps.delete(agent.toLowerCase())
109
+ }
110
+ }
@@ -7,7 +7,12 @@ import { fileURLToPath } from 'node:url'
7
7
  import type { Hooks, PluginInput } from '@opencode-ai/plugin'
8
8
  import type { FilePart, Part, TextPart, UserMessage } from '@opencode-ai/sdk'
9
9
  import type { ResolvedPreset } from './presets.mjs'
10
- import { CAPABILITY_TABLE, hasVision, resolveActivePreset, visionBrokenOnGateway } from './presets.mjs'
10
+ import {
11
+ CAPABILITY_TABLE,
12
+ hasVision,
13
+ resolveActivePreset,
14
+ visionBrokenOnGateway,
15
+ } from './presets.mjs'
11
16
 
12
17
  // ─── Constants ────────────────────────────────────────────────────────────
13
18
 
@@ -136,10 +141,7 @@ export function providerIsTextOnly(providerID: string): boolean {
136
141
  }
137
142
 
138
143
  /** Return whether OpenCode's current model is known to accept image input. */
139
- export function modelAcceptsImages(
140
- model: ModelInfo | undefined,
141
- providerID?: string,
142
- ): boolean {
144
+ export function modelAcceptsImages(model: ModelInfo | undefined, providerID?: string): boolean {
143
145
  if (!model) {
144
146
  // Fail-closed for known text-only providers
145
147
  if (providerID && providerIsTextOnly(providerID)) return false
@@ -39,8 +39,7 @@
39
39
 
40
40
  import type { BackgroundJobBoard } from './background-job-board.ts'
41
41
  import type { DelegationClient } from './delegation-finalize.ts'
42
- import { readDelegationReport } from './delegation-finalize.ts'
43
- import { DELEGATION_DEFAULTS } from './delegation-finalize.ts'
42
+ import { DELEGATION_DEFAULTS, readDelegationReport } from './delegation-finalize.ts'
44
43
  import {
45
44
  createDispatchGuard,
46
45
  type DispatchClassification,
@@ -49,6 +48,11 @@ import {
49
48
  type DispatchResultLike,
50
49
  } from './dispatch-guard.ts'
51
50
  import { createPantheonLogger } from './logger.ts'
51
+ import {
52
+ type ProviderCooldownTracker,
53
+ type RetryPolicy,
54
+ RetryPolicyEngine,
55
+ } from './retry-policy.ts'
52
56
  import { safeSessionPath } from './session-guard.ts'
53
57
 
54
58
  const log = createPantheonLogger({ module: 'pantheon-zeus-retry' })
@@ -74,6 +78,12 @@ export interface ZeusDelegateWithRetryOptions {
74
78
  readTimeoutMs?: number
75
79
  /** Retry on empty results. Default: true */
76
80
  retryOnEmpty?: boolean
81
+ /** R1: per-error-type retry policy (routing.yml `retry_policy`). */
82
+ retryPolicy?: RetryPolicy
83
+ /** R1: provider cooldown tracker (routing.yml `cooldown`). */
84
+ cooldown?: ProviderCooldownTracker
85
+ /** R1: provider name for cooldown tracking (default "default"). */
86
+ provider?: string
77
87
  /** Injectable logger. Default: file log (PANTHEON_HOOKS_LOG gate). */
78
88
  logger?: { warn: (message: string) => void; info?: (message: string) => void }
79
89
  /** Output dir for delegation reports. Default: DELEGATION_DEFAULTS.outputDir */
@@ -143,20 +153,76 @@ export interface ZeusRetryHelper {
143
153
  }>
144
154
  }
145
155
 
146
- export function createZeusRetryHelper(
147
- options?: DispatchGuardOptions,
148
- ): ZeusRetryHelper {
156
+ export interface ZeusRetryHelperOptions extends DispatchGuardOptions {
157
+ /**
158
+ * R1: per-error-type retry policy. When provided, error-type retries with
159
+ * exponential backoff apply (auth → 0, rate_limit → N, ...); when absent
160
+ * the legacy hard-cap-1 empty-result retry applies.
161
+ */
162
+ retryPolicy?: RetryPolicy
163
+ /** R1: provider cooldown tracker (shared across helpers for global cooldown). */
164
+ cooldown?: ProviderCooldownTracker
165
+ /** R1: provider name for cooldown tracking (default "default"). */
166
+ provider?: string
167
+ /** R1: injectable sleep for tests (default: setTimeout promise). */
168
+ sleep?: (ms: number) => Promise<void>
169
+ }
170
+
171
+ export function createZeusRetryHelper(options?: ZeusRetryHelperOptions): ZeusRetryHelper {
149
172
  const guard = createDispatchGuard(options)
173
+ const engine =
174
+ options?.retryPolicy !== undefined
175
+ ? new RetryPolicyEngine(options.retryPolicy, options.cooldown)
176
+ : undefined
177
+ const provider = options?.provider ?? 'default'
178
+ const sleep =
179
+ options?.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
150
180
  return {
151
181
  guard,
152
182
  async executeWithRetry(first, redispatch) {
153
- const out = await guard.maybeRetry(first, redispatch)
154
- const escalate = out.classification !== 'content'
155
- return {
156
- result: out.result,
157
- classification: out.classification,
158
- retried: out.retried,
159
- escalate,
183
+ if (engine === undefined) {
184
+ // Legacy path (unchanged): hard cap 1 on empty results.
185
+ const out = await guard.maybeRetry(first, redispatch)
186
+ const escalate = out.classification !== 'content'
187
+ return {
188
+ result: out.result,
189
+ classification: out.classification,
190
+ retried: out.retried,
191
+ escalate,
192
+ }
193
+ }
194
+ // R1 path: classify the failure, apply the per-error-type policy with
195
+ // exponential backoff, and track provider cooldown. A content result
196
+ // records success (resets the provider's failure counter); an
197
+ // exhausted budget records failure (feeds the cooldown tracker).
198
+ let result = first
199
+ let attemptsUsed = 0
200
+ let retried = false
201
+ let classification = guard.classifyResult(result)
202
+ let lastError: unknown =
203
+ result.error ??
204
+ (classification === 'content' ? undefined : new Error('empty dispatch result'))
205
+ for (;;) {
206
+ if (classification === 'content') {
207
+ engine.recordSuccess(provider)
208
+ return { result, classification, retried, escalate: false }
209
+ }
210
+ lastError = result.error ?? lastError
211
+ const decision = engine.decide(provider, lastError, attemptsUsed)
212
+ if (!decision.shouldRetry) {
213
+ engine.recordFailure(provider, lastError)
214
+ return { result, classification, retried, escalate: true }
215
+ }
216
+ retried = true
217
+ attemptsUsed += 1
218
+ await sleep(decision.delayMs)
219
+ try {
220
+ result = await redispatch()
221
+ lastError = undefined
222
+ } catch (err: unknown) {
223
+ lastError = err
224
+ }
225
+ classification = guard.classifyResult(result)
160
226
  }
161
227
  },
162
228
  }
@@ -193,6 +259,9 @@ export async function zeusDelegateWithRetry(
193
259
  const retryHelper = createZeusRetryHelper({
194
260
  retryOnEmpty: opts.retryOnEmpty ?? true,
195
261
  logger,
262
+ ...(opts.retryPolicy !== undefined ? { retryPolicy: opts.retryPolicy } : {}),
263
+ ...(opts.cooldown !== undefined ? { cooldown: opts.cooldown } : {}),
264
+ ...(opts.provider !== undefined ? { provider: opts.provider } : {}),
196
265
  })
197
266
 
198
267
  // One delegate+read attempt. Factored so maybeRetry can invoke a second
package/src/plugin.ts CHANGED
@@ -24,9 +24,15 @@ import { createReadEnhancer } from './pantheon/hashline/read-enhancer.ts'
24
24
  import { createHashlineEditTool } from './pantheon/hashline/tool.ts'
25
25
  import { createIdleDispatcher } from './pantheon/idle-continuation.ts'
26
26
  import { createPantheonLogger } from './pantheon/logger.ts'
27
- import { safeSessionPath } from './pantheon/session-guard.ts'
28
27
  import { pantheonPluginOnce } from './pantheon/plugin-once.ts'
29
- import { applyActivePresetToConfig, loadRoutingAgentModels } from './pantheon/presets.mjs'
28
+ import {
29
+ applyActivePresetToConfig,
30
+ loadRoutingAgentModels,
31
+ loadRoutingMaxSteps,
32
+ loadRoutingPermissionTask,
33
+ } from './pantheon/presets.mjs'
34
+ import { safeSessionPath } from './pantheon/session-guard.ts'
35
+ import { StepCapTracker } from './pantheon/step-cap.ts'
30
36
  import {
31
37
  TODO_ENFORCER_DEFAULTS,
32
38
  TodoEnforcer,
@@ -55,6 +61,17 @@ const log = createPantheonLogger({ module: 'pantheon-plugin' })
55
61
  // plugin never throws at startup.
56
62
  const routingAgentModels = loadRoutingAgentModels({ logger: log })
57
63
 
64
+ // R4: per-agent step caps from routing.yml `agents.<name>.max_steps`
65
+ // (fail-open → {} = no agent capped). R1 retry_policy/cooldown are NOT
66
+ // wired here — the plugin has no retry path (opencode cannot intercept task
67
+ // completion); zeus waves load them via presets.mjs loaders and pass them
68
+ // to zeusDelegateWithRetry explicitly.
69
+ const stepCapTracker = new StepCapTracker(loadRoutingMaxSteps({ logger: log }))
70
+
71
+ // O5: permission.task glob rules from routing.yml `permission.task`
72
+ // (fail-open → undefined = existing runtime matrix only).
73
+ const routingPermissionTask = loadRoutingPermissionTask({ logger: log })
74
+
58
75
  const board = new BackgroundJobBoard({
59
76
  maxConcurrentPerAgent: 3,
60
77
  signalDir: '.pantheon/deepwork/board-signals',
@@ -202,7 +219,13 @@ function adaptDelegationClient(client: PluginInput['client']): DelegationClient
202
219
  }
203
220
  const result = await client.session.promptAsync({
204
221
  path: path.path,
205
- body: { agent: input.body.agent, parts: input.body.parts },
222
+ body: {
223
+ agent: input.body.agent,
224
+ ...(input.body.model !== undefined
225
+ ? { model: { providerID: input.body.model.providerID, modelID: input.body.model.id } }
226
+ : {}),
227
+ parts: input.body.parts,
228
+ },
206
229
  })
207
230
  if (result.error) throw new Error(sdkErrorMessage(result.error))
208
231
  return result.data
@@ -334,6 +357,8 @@ const plugin: Plugin = async (input: PluginInput) => {
334
357
  readOnlyAgents: new Set(['apollo', 'gaia']),
335
358
  agentModels: routingAgentModels,
336
359
  delegationBudgets,
360
+ stepCapTracker,
361
+ ...(routingPermissionTask != null ? { permissionTask: routingPermissionTask } : {}),
337
362
  ...(wallClockTimeoutMs !== undefined ? { wallClockTimeoutMs } : {}),
338
363
  },
339
364
  })
@@ -22,7 +22,7 @@
22
22
  * is returned as a structured HookResult so the opencode session can never be
23
23
  * taken down by the security layer.
24
24
  */
25
- import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
25
+ import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'
26
26
  import path from 'node:path'
27
27
  import type { Readable } from 'node:stream'
28
28
  import { fileURLToPath } from 'node:url'
@@ -192,8 +192,8 @@ import {
192
192
  enqueueChatReminder,
193
193
  pendingChatReminders,
194
194
  } from '../pantheon/chat-reminders.ts'
195
- import { type HookPayload, type HookResult, runHook } from './hook-runner.ts'
196
195
  import { pantheonPluginOnce } from '../pantheon/plugin-once.ts'
196
+ import { type HookPayload, type HookResult, runHook } from './hook-runner.ts'
197
197
 
198
198
  /** Tools that represent a subagent delegation (opencode `task` tool etc.). */
199
199
  const DELEGATION_TOOL_RE = /^(task|.*delegate.*|.*subagent.*)$/i
@@ -11,7 +11,7 @@ type DelegationEntry = {
11
11
  taskID?: string;
12
12
  /** Agent name, e.g. "apollo". */
13
13
  agent: string;
14
- state: 'running' | 'completed' | 'error' | 'cancelled';
14
+ state: 'running' | 'completed' | 'error' | 'startup_failed' | 'startup_unknown' | 'cancelled';
15
15
  /** Epoch ms of the `Started` header. */
16
16
  startedAt: number;
17
17
  /** Epoch ms of the `Finalized` header — null while still running. */
@@ -1 +1 @@
1
- {"version":3,"file":"tui.d.ts","names":[],"sources":["../src/index.tsx"],"mappings":";;KAq6BY;;EAEV;;EAEA;;;;EAIA;;EAEA;EACA;;EAEA;;EAEA;EACA;EACA;;EAEA;;;;EAIA;;;;;;;;;;;iBAsBc,wBACd,aACA,oBACA,qBACC;;;;;;iBA8GmB,sBAAsB,cAAc,QAAQ;;;;;;;;iBAwC5C,yBAAyB,eAAe,QAAQ;;;;;;;;iBAWtD,sBACd;EAAS;EAAoB;eAC7B;;;;;;iBAYc,YAAY;;;iBAMZ,WAAW;;;;iBAOX,yBAAyB,GAAG,iBAAiB,GAAG;;;;;iBAWhD,s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;QAAY;QAAe,SAAS;;;;;;;;;;iBASlC,wBAAwB,SAAS;;;;;;;;iBAmBjC,gBAAgB;EAAgB;IAAQ;;;;;;;iBASxC,kBAAkB;EAAkC;IAAQ;;;;KAKhE;;EAEV;;EAEA;;;EAGA;;;EAGA;EACA;IACE;IACA;;;;;;;iBAQY,mBAAmB;;;;;iBASnB,cAAc,OAAO;;;;;;;;;;;;;;iBAiBrB,4BACd,mBAAmB,mCACnB,aAAa,mBACb,eACC;;;;;;iBAwCa,4BACd;EAAS,YAAY,cAAc,SAAS;eAC5C;;;;;KA8KU;EACV,KAAK,YAAY;;EAEjB;;EAEA;;cAucI,QAAQ;EAAoB"}
@@ -455,10 +455,10 @@ function parseConfig(raw) {
455
455
  if (!toml?.parse) return defaultConfig();
456
456
  const root = asTable(toml.parse(raw));
457
457
  const cfg = defaultConfig();
458
- const ui = asTable(root["ui"]);
459
- cfg.showBars = bool(ui["show_bars"], cfg.showBars);
460
- cfg.showStatus = bool(ui["show_status"], cfg.showStatus);
461
- const rawWidth = ui["bar_width"];
458
+ const ui = asTable(root.ui);
459
+ cfg.showBars = bool(ui.show_bars, cfg.showBars);
460
+ cfg.showStatus = bool(ui.show_status, cfg.showStatus);
461
+ const rawWidth = ui.bar_width;
462
462
  if (typeof rawWidth === "number" && Number.isFinite(rawWidth) && rawWidth >= 1) cfg.barWidth = Math.min(40, Math.floor(rawWidth));
463
463
  for (const id of [
464
464
  "anthropic",
@@ -467,14 +467,14 @@ function parseConfig(raw) {
467
467
  ]) {
468
468
  const t = asTable(root[id]);
469
469
  const p = cfg.providers[id];
470
- p.enabled = bool(t["enabled"], p.enabled);
471
- p.show["5h"] = bool(t["show_5h"], p.show["5h"]);
472
- p.show["7d"] = bool(t["show_7d"], p.show["7d"]);
473
- p.show["1m"] = bool(t["show_1m"], p.show["1m"]);
474
- p.show.model = bool(t["show_model"], p.show.model);
475
- const credentialsPath = str(t["credentials_path"]);
470
+ p.enabled = bool(t.enabled, p.enabled);
471
+ p.show["5h"] = bool(t.show_5h, p.show["5h"]);
472
+ p.show["7d"] = bool(t.show_7d, p.show["7d"]);
473
+ p.show["1m"] = bool(t.show_1m, p.show["1m"]);
474
+ p.show.model = bool(t.show_model, p.show.model);
475
+ const credentialsPath = str(t.credentials_path);
476
476
  if (credentialsPath !== void 0) p.credentialsPath = credentialsPath;
477
- const codexAuthPath = str(t["codex_auth_path"]);
477
+ const codexAuthPath = str(t.codex_auth_path);
478
478
  if (codexAuthPath !== void 0) p.codexAuthPath = codexAuthPath;
479
479
  }
480
480
  return cfg;
@@ -765,7 +765,7 @@ function parseDelegationMarkdown(raw, fileAlias, sessionID = "") {
765
765
  const startedAt = started !== void 0 ? Date.parse(started) : NaN;
766
766
  if (agent === void 0 || state === void 0 || Number.isNaN(startedAt)) return null;
767
767
  const normalized = state.toLowerCase();
768
- if (normalized !== "running" && normalized !== "completed" && normalized !== "error" && normalized !== "cancelled") return null;
768
+ if (normalized !== "running" && normalized !== "completed" && normalized !== "error" && normalized !== "startup_failed" && normalized !== "startup_unknown" && normalized !== "cancelled") return null;
769
769
  const finalizedAt = finalized !== void 0 ? Date.parse(finalized) : NaN;
770
770
  return {
771
771
  alias: title ?? (fileAlias !== void 0 ? stripMdSuffix(fileAlias) : "unknown"),
@@ -898,7 +898,7 @@ function delegationElapsed(entry, now) {
898
898
  * state machine testable without booting OpenCode's renderer. */
899
899
  function delegationActivity(entry) {
900
900
  if (entry.state === "completed") return "completed";
901
- if (entry.state === "error") return "error";
901
+ if (entry.state === "error" || entry.state === "startup_failed" || entry.state === "startup_unknown") return "error";
902
902
  if (entry.state === "cancelled") return "cancelled";
903
903
  if (entry.read) return "reading";
904
904
  if (entry.alias.startsWith("live-") && entry.taskID === void 0) return "delegating";
@@ -959,7 +959,12 @@ function mergeChildDelegationSources(children, live) {
959
959
  }
960
960
  const existing = result[index];
961
961
  if (existing === void 0) continue;
962
- if (existing.source === "md" && existing.state !== "running") continue;
962
+ if (existing.state !== "running") {
963
+ if (liveEntry.alias !== null && existing.alias !== incoming.alias) existing.alias = incoming.alias;
964
+ if (incoming.agent !== "agent" && existing.agent !== incoming.agent) existing.agent = incoming.agent;
965
+ if (incoming.read && !existing.read) existing.read = true;
966
+ continue;
967
+ }
963
968
  result[index] = {
964
969
  ...existing,
965
970
  alias: liveEntry.alias !== null ? incoming.alias : existing.alias,