pantheon-opencode 1.3.5 → 1.3.7

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 (71) 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/sync-tui.mjs +148 -0
  28. package/scripts/uninstall.mjs +0 -2
  29. package/scripts/validation-policy.mjs +6 -1
  30. package/scripts/version-check.mjs +9 -4
  31. package/src/agents/aphrodite.md +1 -1
  32. package/src/agents/demeter.md +1 -1
  33. package/src/agents/hephaestus.md +1 -1
  34. package/src/agents/hermes.md +1 -1
  35. package/src/agents/themis.md +4 -0
  36. package/src/mcp/code_mode_server.py +304 -18
  37. package/src/mcp/eval_store.py +233 -0
  38. package/src/mcp/mcp_persistence_server.py +23 -22
  39. package/src/mcp/mcp_resources_server.py +58 -0
  40. package/src/mcp/memory_mcp_server.py +80 -3
  41. package/src/pantheon/auto-wake.ts +2 -4
  42. package/src/pantheon/background-job-board.ts +17 -4
  43. package/src/pantheon/comment-checker.ts +48 -0
  44. package/src/pantheon/delegation-classifier.ts +307 -0
  45. package/src/pantheon/delegation-enforce.ts +21 -21
  46. package/src/pantheon/delegation-finalize.ts +44 -4
  47. package/src/pantheon/delegation-notify.ts +97 -0
  48. package/src/pantheon/delegation.ts +413 -23
  49. package/src/pantheon/dispatch-guard.ts +2 -0
  50. package/src/pantheon/file-persistence.ts +7 -3
  51. package/src/pantheon/permission-eval.ts +284 -0
  52. package/src/pantheon/permission-globs.ts +86 -0
  53. package/src/pantheon/presets.d.mts +41 -0
  54. package/src/pantheon/presets.mjs +134 -0
  55. package/src/pantheon/retry-policy.ts +212 -0
  56. package/src/pantheon/session-guard.ts +1 -3
  57. package/src/pantheon/step-cap.ts +110 -0
  58. package/src/pantheon/tui-version-check.ts +72 -0
  59. package/src/pantheon/vision.ts +7 -5
  60. package/src/pantheon/zeus-delegate-with-retry.ts +81 -12
  61. package/src/plugin.ts +57 -3
  62. package/src/plugins/hook-runner.ts +1 -1
  63. package/src/plugins/pantheon-hooks.ts +1 -1
  64. package/src/plugins/tui/dist/tui.d.ts +1 -1
  65. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  66. package/src/plugins/tui/dist/tui.js +19 -14
  67. package/src/plugins/tui/dist/tui.tsx +52 -18
  68. package/src/plugins/tui/package.json +1 -1
  69. package/src/plugins/tui/src/index.tsx +106 -24
  70. package/src/plugins/tui/tsdown.config.ts +1 -1
  71. 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
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * tui-version-check.ts — Runtime staleness check for the TUI plugin copy
3
+ *
4
+ * Compares the version in the user's copied TUI plugin package.json against
5
+ * the version of the installed pantheon-opencode package. If mismatched,
6
+ * logs a one-time warning. Does NOT auto-sync (safety first).
7
+ */
8
+ import { existsSync, readFileSync } from 'node:fs'
9
+ import { homedir } from 'node:os'
10
+ import { join } from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+
13
+ const __dirname = fileURLToPath(new URL('.', import.meta.url))
14
+ const ROOT = join(__dirname, '..', '..')
15
+
16
+ /**
17
+ * Detect the user's OpenCode config directory (same logic as sync-tui.mjs).
18
+ * Priority: $XDG_CONFIG_HOME/opencode → ~/.opencode → null
19
+ */
20
+ function resolveConfigDir(): string | null {
21
+ const xdgConfig = process.env.XDG_CONFIG_HOME || join(homedir(), '.config')
22
+ const xdgDir = join(xdgConfig, 'opencode')
23
+ if (existsSync(xdgDir)) return xdgDir
24
+
25
+ const homeDir = join(homedir(), '.opencode')
26
+ if (existsSync(homeDir)) return homeDir
27
+
28
+ return null
29
+ }
30
+
31
+ /**
32
+ * Read the `version` field from a package.json, or null on failure.
33
+ */
34
+ function readVersion(pkgPath: string): string | null {
35
+ try {
36
+ return JSON.parse(readFileSync(pkgPath, 'utf8')).version || null
37
+ } catch {
38
+ return null
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Run the TUI version staleness check. Call once at plugin init.
44
+ *
45
+ * @param logger - Logging function (defaults to console.warn)
46
+ */
47
+ export function checkTuiVersionStaleness(
48
+ logger: (msg: string) => void = console.warn,
49
+ ): void {
50
+ try {
51
+ const configDir = resolveConfigDir()
52
+ if (!configDir) return // Not initialized — nothing to check
53
+
54
+ const tuiCopyDir = join(configDir, 'plugins', 'pantheon-tui')
55
+ if (!existsSync(tuiCopyDir)) return // TUI not installed
56
+
57
+ const copyVersion = readVersion(join(tuiCopyDir, 'package.json'))
58
+ if (!copyVersion) return // Can't read version — skip
59
+
60
+ // Read the installed package version from the repo root's package.json
61
+ const currentVersion = readVersion(join(ROOT, 'package.json'))
62
+ if (!currentVersion) return // Can't determine current version — skip
63
+
64
+ if (copyVersion !== currentVersion) {
65
+ logger(
66
+ `⚠️ TUI plugin v${copyVersion} is outdated. Current: v${currentVersion}. Run: npx pantheon-opencode init`,
67
+ )
68
+ }
69
+ } catch {
70
+ // Fail-open — version check must never block plugin initialization
71
+ }
72
+ }
@@ -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
@@ -1,5 +1,7 @@
1
1
  import type { Plugin, PluginInput } from '@opencode-ai/plugin'
2
2
  import type { PluginConfig } from 'opencode'
3
+ import { existsSync } from 'node:fs'
4
+ import { join } from 'node:path'
3
5
  import { BackgroundJobBoard } from './pantheon/background-job-board.ts'
4
6
  import { reassertAfterCompaction } from './pantheon/compaction-assert.ts'
5
7
  import { createCostCommand } from './pantheon/cost-command.ts'
@@ -9,6 +11,7 @@ import {
9
11
  type DelegationClient,
10
12
  resolveDelegationBudgets,
11
13
  resolveDelegationTimeoutMs,
14
+ startIdleChildScan,
12
15
  } from './pantheon/delegation.ts'
13
16
  import { buildCompactionContext } from './pantheon/delegation-compaction.ts'
14
17
  import {
@@ -24,9 +27,15 @@ import { createReadEnhancer } from './pantheon/hashline/read-enhancer.ts'
24
27
  import { createHashlineEditTool } from './pantheon/hashline/tool.ts'
25
28
  import { createIdleDispatcher } from './pantheon/idle-continuation.ts'
26
29
  import { createPantheonLogger } from './pantheon/logger.ts'
27
- import { safeSessionPath } from './pantheon/session-guard.ts'
28
30
  import { pantheonPluginOnce } from './pantheon/plugin-once.ts'
29
- import { applyActivePresetToConfig, loadRoutingAgentModels } from './pantheon/presets.mjs'
31
+ import {
32
+ applyActivePresetToConfig,
33
+ loadRoutingAgentModels,
34
+ loadRoutingMaxSteps,
35
+ loadRoutingPermissionTask,
36
+ } from './pantheon/presets.mjs'
37
+ import { safeSessionPath } from './pantheon/session-guard.ts'
38
+ import { StepCapTracker } from './pantheon/step-cap.ts'
30
39
  import {
31
40
  TODO_ENFORCER_DEFAULTS,
32
41
  TodoEnforcer,
@@ -34,6 +43,7 @@ import {
34
43
  todoEnforcerEnabledFromEnv,
35
44
  } from './pantheon/todo-enforcer.ts'
36
45
  import { TodoPreserver } from './pantheon/todo-preserve.ts'
46
+ import { checkTuiVersionStaleness } from './pantheon/tui-version-check.ts'
37
47
  import { activePresetCandidates, createVisionHandler } from './pantheon/vision.ts'
38
48
 
39
49
  // ─── Background Job Board Singleton ────────────────────────────────────
@@ -55,6 +65,17 @@ const log = createPantheonLogger({ module: 'pantheon-plugin' })
55
65
  // plugin never throws at startup.
56
66
  const routingAgentModels = loadRoutingAgentModels({ logger: log })
57
67
 
68
+ // R4: per-agent step caps from routing.yml `agents.<name>.max_steps`
69
+ // (fail-open → {} = no agent capped). R1 retry_policy/cooldown are NOT
70
+ // wired here — the plugin has no retry path (opencode cannot intercept task
71
+ // completion); zeus waves load them via presets.mjs loaders and pass them
72
+ // to zeusDelegateWithRetry explicitly.
73
+ const stepCapTracker = new StepCapTracker(loadRoutingMaxSteps({ logger: log }))
74
+
75
+ // O5: permission.task glob rules from routing.yml `permission.task`
76
+ // (fail-open → undefined = existing runtime matrix only).
77
+ const routingPermissionTask = loadRoutingPermissionTask({ logger: log })
78
+
58
79
  const board = new BackgroundJobBoard({
59
80
  maxConcurrentPerAgent: 3,
60
81
  signalDir: '.pantheon/deepwork/board-signals',
@@ -202,7 +223,13 @@ function adaptDelegationClient(client: PluginInput['client']): DelegationClient
202
223
  }
203
224
  const result = await client.session.promptAsync({
204
225
  path: path.path,
205
- body: { agent: input.body.agent, parts: input.body.parts },
226
+ body: {
227
+ agent: input.body.agent,
228
+ ...(input.body.model !== undefined
229
+ ? { model: { providerID: input.body.model.providerID, modelID: input.body.model.id } }
230
+ : {}),
231
+ parts: input.body.parts,
232
+ },
206
233
  })
207
234
  if (result.error) throw new Error(sdkErrorMessage(result.error))
208
235
  return result.data
@@ -311,6 +338,9 @@ const plugin: Plugin = async (input: PluginInput) => {
311
338
  if (pantheonPluginOnce('pantheon:plugin')) {
312
339
  return {}
313
340
  }
341
+ // Runtime TUI version staleness check — warns if the copied TUI plugin
342
+ // is older than the installed package. Runs once, fail-open, no auto-sync.
343
+ checkTuiVersionStaleness((msg) => log.warn(msg))
314
344
  const vision = createVisionHandler(input)
315
345
  // Phase 2/3: background delegation toolset + the bound finalize lifecycle
316
346
  // hook. Completion is observed through the event hook below
@@ -334,10 +364,34 @@ const plugin: Plugin = async (input: PluginInput) => {
334
364
  readOnlyAgents: new Set(['apollo', 'gaia']),
335
365
  agentModels: routingAgentModels,
336
366
  delegationBudgets,
367
+ stepCapTracker,
368
+ ...(routingPermissionTask != null ? { permissionTask: routingPermissionTask } : {}),
337
369
  ...(wallClockTimeoutMs !== undefined ? { wallClockTimeoutMs } : {}),
338
370
  },
339
371
  })
340
372
 
373
+ // Proactive idle-child scan (Fix 2): finalize children that are idle on the
374
+ // board but have no MD report on disk — eliminates the phantom "running"
375
+ // window. Runs every 30s (configurable via PANTHEON_IDLE_SCAN_INTERVAL_MS),
376
+ // unref'd so it never holds the process open. Fail-open by design.
377
+ const idleScanIntervalMs = Number(process.env.PANTHEON_IDLE_SCAN_INTERVAL_MS) || undefined
378
+ startIdleChildScan(
379
+ {
380
+ board,
381
+ finalize: (childSessionID, opts) => delegation.finalizeDelegation(childSessionID, opts),
382
+ hasReport: (job) => {
383
+ try {
384
+ const filePath = join('.pantheon/delegations', job.parentSessionID, `${job.alias}.md`)
385
+ return existsSync(filePath)
386
+ } catch {
387
+ return false
388
+ }
389
+ },
390
+ logger: log,
391
+ },
392
+ idleScanIntervalMs,
393
+ )
394
+
341
395
  // Wave 1 (PR #46): TODO continuation enforcer for root/non-board sessions.
342
396
  // Mirrors routing.yml `todo_enforcer` (plugin scope has no routing.yml
343
397
  // access — COMPACTION_MAX_ITEMS pattern). The event hook routes non-board