pantheon-opencode 1.7.0 → 2.0.0-beta.1

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 (168) hide show
  1. package/AGENTS.global.md +2 -2
  2. package/AGENTS.md +3 -3
  3. package/CHANGELOG.md +64 -60
  4. package/README.md +52 -45
  5. package/README.pt-BR.md +19 -19
  6. package/bin/pantheon-init.mjs +11 -48
  7. package/package.json +9 -13
  8. package/plugin.json +2 -2
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +7 -6
  11. package/scripts/{check-plugin-v2-coverage.mjs → check-plugin-coverage.mjs} +7 -7
  12. package/scripts/{decision-router-v2-budget.mjs → decision-router-budget-gates.mjs} +1 -1
  13. package/scripts/{decision-router-v2-egress.mjs → decision-router-egress.mjs} +1 -1
  14. package/scripts/decision-router.mjs +2 -2
  15. package/scripts/docs-media.mjs +1 -1
  16. package/scripts/doctor.mjs +225 -136
  17. package/scripts/install/behavior-overrides.bundle.mjs +123 -0
  18. package/scripts/install/{v2-capabilities.mjs → capabilities.mjs} +7 -7
  19. package/scripts/install/config-migration.mjs +60 -253
  20. package/scripts/install/file-inventory.mjs +6 -4
  21. package/scripts/install/interactive.mjs +1 -1
  22. package/scripts/install/opencode-state.mjs +13 -12
  23. package/scripts/install/opencode-version.mjs +97 -162
  24. package/scripts/install/opencode.mjs +271 -428
  25. package/scripts/install/plan.mjs +1 -9
  26. package/scripts/install/plugin.mjs +19 -35
  27. package/scripts/install/shared.mjs +40 -1
  28. package/scripts/package-evidence.mjs +1 -4
  29. package/scripts/probe-pantheon-cost.mjs +1 -1
  30. package/scripts/reconcile.mjs +5 -7
  31. package/scripts/release-gates.mjs +22 -61
  32. package/scripts/setup-v2-config.mjs +10 -8
  33. package/scripts/setup.mjs +12 -22
  34. package/scripts/sync-tui.mjs +9 -17
  35. package/scripts/{test-opencode-v2-sandbox.sh → test-opencode-sandbox.sh} +9 -9
  36. package/scripts/update-skills-lock.mjs +24 -12
  37. package/scripts/update.mjs +17 -1
  38. package/scripts/validate-routing.mjs +79 -4
  39. package/scripts/validate-sandbox-install.mjs +3 -3
  40. package/skills-lock.json +25 -8
  41. package/src/agents/zeus.md +1 -0
  42. package/src/pantheon/behavior-overrides.ts +191 -0
  43. package/src/pantheon/{v2-bounded-read.ts → bounded-read.ts} +1 -1
  44. package/src/pantheon/cost-command.ts +1 -1
  45. package/src/pantheon/{v2-decision-contracts.ts → decision-contracts.ts} +3 -3
  46. package/src/pantheon/{v2-decision-points → decision-points}/p1-agent.ts +3 -3
  47. package/src/pantheon/{v2-decision-points → decision-points}/p10-claims.ts +2 -2
  48. package/src/pantheon/{v2-decision-points → decision-points}/p11-catalog.ts +2 -2
  49. package/src/pantheon/{v2-decision-points → decision-points}/p2-skill.ts +3 -3
  50. package/src/pantheon/{v2-decision-points → decision-points}/p3-complexity.ts +6 -6
  51. package/src/pantheon/{v2-decision-points → decision-points}/p4-memory.ts +2 -2
  52. package/src/pantheon/{v2-decision-points → decision-points}/p5-themis-verify.ts +2 -2
  53. package/src/pantheon/{v2-decision-points → decision-points}/p6-council.ts +3 -3
  54. package/src/pantheon/{v2-decision-points → decision-points}/p7-loop.ts +5 -5
  55. package/src/pantheon/{v2-decision-points → decision-points}/p8-guardrail.ts +2 -2
  56. package/src/pantheon/{v2-decision-points → decision-points}/p9-memory-compaction.ts +2 -2
  57. package/src/pantheon/{v2-decision-points.ts → decision-points.ts} +5 -5
  58. package/src/pantheon/{v2-decision-policy.ts → decision-policy.ts} +2 -2
  59. package/src/pantheon/{v2-decision-prompt-surface.ts → decision-prompt-surface.ts} +3 -3
  60. package/src/pantheon/{v2-decision-registry.ts → decision-registry.ts} +10 -13
  61. package/src/pantheon/{v2-decision-resource-ids.ts → decision-resource-ids.ts} +1 -1
  62. package/src/pantheon/{v2-decision-shadow.ts → decision-shadow.ts} +1 -1
  63. package/src/pantheon/{v2-decision-telemetry.ts → decision-telemetry.ts} +1 -1
  64. package/src/pantheon/{v2-execute-after.ts → execute-after.ts} +4 -4
  65. package/src/pantheon/goal-store.ts +7 -0
  66. package/src/pantheon/{v2-hook-engine.ts → hook-engine.ts} +3 -3
  67. package/src/pantheon/jev-decision-tool.ts +3 -3
  68. package/src/pantheon/jev-decisions.ts +12 -6
  69. package/src/pantheon/jev-escalation.ts +6 -6
  70. package/src/pantheon/jev-quality-score.ts +2 -2
  71. package/src/pantheon/jev-rank-verify.ts +2 -2
  72. package/src/pantheon/jev-risk-gate.ts +4 -4
  73. package/src/pantheon/local-decision-agents.ts +1 -1
  74. package/src/pantheon/local-decision-router.ts +1 -1
  75. package/src/pantheon/local-decision-tool.ts +2 -2
  76. package/src/pantheon/local-orchestration.ts +1 -1
  77. package/src/pantheon/model-command.ts +1 -1
  78. package/src/pantheon/{v2-vision.ts → native-vision.ts} +12 -15
  79. package/src/pantheon/pantheon-decision-catalog.ts +12 -0
  80. package/src/pantheon/{v2-shell-hooks.ts → shell-hooks.ts} +4 -4
  81. package/src/pantheon/{v2-tools.ts → tools.ts} +4 -4
  82. package/src/pantheon/{v2-unsupported.d.mts → unsupported.d.mts} +3 -3
  83. package/src/pantheon/{v2-unsupported.mjs → unsupported.mjs} +8 -8
  84. package/src/pantheon/update-notifier.ts +101 -0
  85. package/src/pantheon/vision-local.ts +12 -3
  86. package/src/pantheon/vision.ts +120 -2
  87. package/src/{plugin-v2 → plugin}/index.ts +7 -7
  88. package/src/plugin.ts +2875 -500
  89. package/src/plugins/hook-runner.ts +3 -3
  90. package/src/plugins/tui/dist/server.d.ts +23 -9
  91. package/src/plugins/tui/dist/server.d.ts.map +1 -1
  92. package/src/plugins/tui/dist/server.js +25 -12
  93. package/src/plugins/tui/dist/server.js.map +1 -1
  94. package/src/plugins/tui/dist/tui.d.ts +1023 -494
  95. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  96. package/src/plugins/tui/dist/tui.js +4841 -2066
  97. package/src/plugins/tui/dist/tui.js.map +1 -1
  98. package/src/plugins/tui/{index-v2.ts → index.ts} +1 -1
  99. package/src/plugins/tui/package-lock.json +2 -42
  100. package/src/plugins/tui/package.json +4 -10
  101. package/src/plugins/tui/src/cost-data.ts +1 -1
  102. package/src/plugins/tui/src/index.tsx +4222 -2822
  103. package/src/plugins/tui/src/pantheon-settings-state.ts +111 -0
  104. package/src/plugins/tui/src/pantheon-settings.tsx +236 -0
  105. package/src/plugins/tui/src/server.ts +23 -10
  106. package/src/plugins/tui/src/update-notice.ts +86 -0
  107. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  108. package/src/plugins/tui/tsdown.config.ts +3 -5
  109. package/src/plugins/tui/tui.ts +1 -2
  110. package/src/routing.yml +36 -0
  111. package/src/skills/README.md +16 -1
  112. package/src/skills/artifact-management/SKILL.md +10 -67
  113. package/src/skills/artifact-management/references/artifact-templates.md +71 -0
  114. package/src/skills/auto-continue/SKILL.md +10 -0
  115. package/src/skills/code-review-checklist/SKILL.md +11 -44
  116. package/src/skills/code-review-checklist/references/review-checklists.md +54 -0
  117. package/src/skills/instruction-forge/SKILL.md +57 -0
  118. package/src/skills/instruction-forge/references/agents-md-doctrine.md +50 -0
  119. package/src/skills/instruction-forge/references/eval-doctrine.md +37 -0
  120. package/src/skills/instruction-forge/references/skill-doctrine.md +62 -0
  121. package/src/skills/memory-bank/SKILL.md +11 -90
  122. package/src/skills/memory-bank/references/anti-patterns.md +33 -0
  123. package/src/skills/memory-bank/references/product-adoption.md +19 -0
  124. package/src/skills/memory-bank/references/storage-model.md +21 -0
  125. package/src/skills/memory-bank/references/structure-and-frequency.md +44 -0
  126. package/src/skills/reflect/SKILL.md +1 -0
  127. package/src/skills/session-goal/SKILL.md +7 -54
  128. package/src/skills/session-goal/references/goal-format.md +26 -0
  129. package/src/skills/session-goal/references/session-reuse.md +44 -0
  130. package/src/skills/tdd-with-agents/SKILL.md +11 -101
  131. package/src/skills/tdd-with-agents/references/advanced-testing-patterns.md +58 -0
  132. package/src/skills/tdd-with-agents/references/testing-by-layer.md +60 -0
  133. package/src/skills/visual-review-pipeline/SKILL.md +11 -120
  134. package/src/skills/visual-review-pipeline/references/findings-schema.md +49 -0
  135. package/src/skills/visual-review-pipeline/references/workflow-steps.md +111 -0
  136. package/scripts/hooks/log-session-start.sh +0 -48
  137. package/scripts/hooks/validate-post-conditions.sh +0 -21
  138. package/scripts/hooks/validate-talos-scope.sh +0 -50
  139. package/scripts/hooks/validate-tool-safety.sh +0 -49
  140. package/src/pantheon/goal-loop.ts +0 -314
  141. package/src/pantheon/idle-continuation.ts +0 -52
  142. package/src/pantheon/todo-preserve.ts +0 -301
  143. package/src/pantheon/tool-ceiling.ts +0 -159
  144. package/src/pantheon/v2-bridge.ts +0 -153
  145. package/src/plugin-v2.ts +0 -2954
  146. package/src/plugins/pantheon-hooks.ts +0 -1433
  147. package/src/plugins/tui/dist/server-v2.d.ts +0 -30
  148. package/src/plugins/tui/dist/server-v2.d.ts.map +0 -1
  149. package/src/plugins/tui/dist/server-v2.js +0 -33
  150. package/src/plugins/tui/dist/server-v2.js.map +0 -1
  151. package/src/plugins/tui/dist/tui-v2.d.ts +0 -1039
  152. package/src/plugins/tui/dist/tui-v2.d.ts.map +0 -1
  153. package/src/plugins/tui/dist/tui-v2.js +0 -4597
  154. package/src/plugins/tui/dist/tui-v2.js.map +0 -1
  155. package/src/plugins/tui/src/index-v2.tsx +0 -4496
  156. package/src/plugins/tui/src/server-v2.ts +0 -28
  157. package/src/plugins/tui/tui-v2.ts +0 -2
  158. /package/src/pantheon/{v2-decision-budget.ts → decision-budget.ts} +0 -0
  159. /package/src/pantheon/{v2-decision-egress.ts → decision-egress.ts} +0 -0
  160. /package/src/pantheon/{v2-decision-events.ts → decision-events.ts} +0 -0
  161. /package/src/pantheon/{v2-decision-heuristic.ts → decision-heuristic.ts} +0 -0
  162. /package/src/pantheon/{v2-decision-premises.ts → decision-premises.ts} +0 -0
  163. /package/src/pantheon/{v2-decision-rank.ts → decision-rank.ts} +0 -0
  164. /package/src/pantheon/{v2-decision-verify.ts → decision-verify.ts} +0 -0
  165. /package/src/pantheon/{v2-delegation-enforce.ts → delegation-policy.ts} +0 -0
  166. /package/src/pantheon/{v2-model-overrides.ts → model-overrides.ts} +0 -0
  167. /package/src/pantheon/{v2-native-decisions.ts → native-decisions.ts} +0 -0
  168. /package/src/plugins/tui/src/{opencode-v2.d.ts → opencode.d.ts} +0 -0
@@ -1,52 +0,0 @@
1
- /**
2
- * Idle Continuation Dispatcher (Wave 3, PR #46) — routes `session.idle`
3
- * events to the subsystem that owns the idle.
4
- *
5
- * Priority: an ACTIVE GOAL owns the idle — `GoalLoop.onIdle` continues the
6
- * goal. Without an active goal, the TODO enforcer gets the idle (it
7
- * self-guards on its own enabled flag + guards). Board-child sessions never
8
- * reach the dispatcher — the plugin's event hook owns board transitions and
9
- * only calls the dispatcher for non-board sessions.
10
- *
11
- * Independently testable — the loop and enforcer are structural interfaces;
12
- * the real GoalLoop/TodoEnforcer satisfy them.
13
- *
14
- * Pure TypeScript — zero runtime dependencies.
15
- *
16
- * @module idle-continuation
17
- */
18
-
19
- /** Structural goal-loop surface the dispatcher needs. */
20
- export interface GoalLoopLike {
21
- hasActiveGoal(sessionID: string): Promise<boolean>
22
- onIdle(sessionID: string): Promise<void>
23
- }
24
-
25
- /** Structural todo-enforcer surface the dispatcher needs. */
26
- export interface TodoEnforcerLike {
27
- onIdle(sessionID: string): Promise<void>
28
- }
29
-
30
- /** The dispatcher's onIdle surface (used by the plugin event hook). */
31
- export interface IdleDispatcher {
32
- onIdle(sessionID: string): Promise<void>
33
- }
34
-
35
- /**
36
- * Build the idle router. The plugin event hook calls this only for non-board
37
- * sessions, so board children never arrive here.
38
- */
39
- export function createIdleDispatcher(deps: {
40
- goalLoop: GoalLoopLike
41
- todoEnforcer: TodoEnforcerLike
42
- }): IdleDispatcher {
43
- return {
44
- onIdle: async (sessionID: string): Promise<void> => {
45
- if (await deps.goalLoop.hasActiveGoal(sessionID)) {
46
- await deps.goalLoop.onIdle(sessionID)
47
- return
48
- }
49
- await deps.todoEnforcer.onIdle(sessionID)
50
- },
51
- }
52
- }
@@ -1,301 +0,0 @@
1
- /**
2
- * Todo Preserver (release-134 Phase 3) — post-compaction todo restore.
3
- *
4
- * WHY: opencode 1.18.11 exposes NO todo write API (SessionTodoData.body?:
5
- * never — the `/session/{id}/todo` route is GET-only), so a session's todo
6
- * list cannot be restored by a direct SDK call after compaction. The model's
7
- * `todowrite` tool performs a FULL replace server-side (todos.update
8
- * delete+insert), so a model that re-emits a partial list right after
9
- * compaction silently clobbers the pre-compaction list.
10
- *
11
- * HOW: three phases, all additive to the existing plugin hooks:
12
- * 1. CAPTURE — `experimental.session.compacting` calls `capture(sessionID)`
13
- * (a GET of the todo list) alongside the existing context build.
14
- * 2. RESTORE — the `event` hook routes `session.compacted` to
15
- * `onCompacted(sessionID)`, activating the pending snapshot. The FIRST
16
- * `todowrite` of that session within `restoreWindowMs` has its
17
- * `output.args.todos` rewritten with the EXACT captured list — no model
18
- * cooperation, zero transcript noise. Subsequent writes inside the
19
- * window are denied with a clear "retry in a moment" message so the
20
- * restored list stays stable.
21
- * 3. GUARD — `beforeTodoWrite` chains with the read-only enforcement guard
22
- * on `tool.execute.before` (enforcement first, restore second).
23
- *
24
- * FAIL-OPEN: every step is wrapped — a capture GET failure, a missing event,
25
- * a malformed hook output, or an expired snapshot degrades to a logged warn
26
- * and pass-through. The ONLY deliberate throw is the restore-window denial
27
- * (TodoRestoreInProgressError), and only for the exact session being
28
- * restored.
29
- *
30
- * STATE: transient in-memory Map<sessionID, {todos, capturedAt, restored}>
31
- * (no files, no KV). `snapshotTtlMs` (60s) bounds how old a snapshot may be;
32
- * `restoreWindowMs` (5s) bounds interception after capture. An empty captured
33
- * list stores nothing → no restore, zero noise. Snapshots are anchored on
34
- * `capturedAt`: capture and the compacted event are adjacent (the session is
35
- * paused mid-compaction), so one timestamp covers both the TTL and the
36
- * window — a second timestamp would be YAGNI.
37
- *
38
- * VERSION-SENSITIVE WRITE HOOK: `tryWriteApi` attempts a direct todo write
39
- * when an adapter is injected (options.tryWriteApi). SDK 1.18.11 ships no
40
- * adapter (the route is GET-only) → restore goes through interception. If a
41
- * future SDK exposes a write, inject an adapter built on a dynamic
42
- * `await import('@opencode-ai/sdk')` probe and the preserver prefers it: a
43
- * successful direct write drops the snapshot and skips interception entirely.
44
- *
45
- * Pure TypeScript — zero runtime deps beyond the structural client type.
46
- *
47
- * @module todo-preserve
48
- */
49
-
50
- import { createPantheonLogger } from './logger.ts'
51
- import { safeSessionPath } from './session-guard.ts'
52
- import type { TodoLike } from './todo-enforcer.ts'
53
-
54
- // Silence-by-default TUI policy (pantheon-hooks L42-58): console echo is
55
- // opt-in via PANTHEON_HOOKS_LOG=1. `deps.logger` injection stays for tests.
56
- const log = createPantheonLogger({ module: 'pantheon-todo-preserve' })
57
-
58
- // ─── Constants ─────────────────────────────────────────────────────────
59
-
60
- /** How long a captured snapshot stays valid (bounds staleness). */
61
- export const SNAPSHOT_TTL_MS = 60_000
62
-
63
- /** Interception window after capture: only the FIRST todowrite is restored. */
64
- export const RESTORE_WINDOW_MS = 5_000
65
-
66
- // ─── Types ─────────────────────────────────────────────────────────────
67
-
68
- /**
69
- * Structural client surface — the subset of the SDK the preserver uses
70
- * (mirrors TodoEnforcerClient; only the GET is needed for capture).
71
- */
72
- export interface TodoPreserverClient {
73
- session: {
74
- todo(input: { path: { id: string } }): Promise<TodoLike[]>
75
- }
76
- }
77
-
78
- /** Tunables (all optional — see the constants). */
79
- export interface TodoPreserverOptions {
80
- snapshotTtlMs?: number
81
- restoreWindowMs?: number
82
- /** Injectable clock (testable), defaults to `Date.now`. */
83
- now?: () => number
84
- /**
85
- * Version-sensitive direct-write adapter. SDK 1.18.11 exposes no todo
86
- * write (SessionTodoData.body?: never) — restore happens via
87
- * `tool.execute.before` interception (beforeTodoWrite). If a future SDK
88
- * adds a write endpoint, inject an adapter here (e.g. built on a dynamic
89
- * `await import('@opencode-ai/sdk')` probe) and the preserver prefers the
90
- * direct API restore: onCompacted calls this first and, when it resolves
91
- * true, drops the snapshot so interception is skipped entirely. Absence
92
- * or failure falls back to interception. Never throws (wrapped).
93
- */
94
- tryWriteApi?: (sessionID: string, todos: TodoLike[]) => Promise<boolean>
95
- }
96
-
97
- /** Dependencies threaded to the preserver. */
98
- export interface TodoPreserverDeps {
99
- client: TodoPreserverClient
100
- options?: TodoPreserverOptions
101
- logger?: { warn: (message: string) => void }
102
- }
103
-
104
- /** Input the opencode `tool.execute.before` hook passes. */
105
- export interface TodoWriteBeforeInput {
106
- tool: string
107
- sessionID: string
108
- callID: string
109
- }
110
-
111
- /** The `tool.execute.before` output — args mutated to restore the list. */
112
- export interface TodoWriteBeforeOutput {
113
- args?: { todos?: unknown }
114
- }
115
-
116
- /** A captured (full) todo list awaiting post-compaction restore. */
117
- interface SnapshotEntry {
118
- todos: TodoLike[]
119
- /** Epoch ms of the capture — anchor for both the TTL and the window. */
120
- capturedAt: number
121
- /** True once the FIRST todowrite was intercepted (rewrite done). */
122
- restored: boolean
123
- }
124
-
125
- /**
126
- * Thrown to deny a `todowrite` while the post-compaction restore is settling
127
- * (the list was just rewritten; a competing model write would clobber it).
128
- */
129
- export class TodoRestoreInProgressError extends Error {
130
- constructor(sessionID: string) {
131
- super(`todo list being restored after compaction — retry in a moment (session ${sessionID})`)
132
- this.name = 'TodoRestoreInProgressError'
133
- }
134
- }
135
-
136
- /** Resolved tunables — tryWriteApi stays `| undefined` (optional adapter). */
137
- interface ResolvedTodoPreserverOptions {
138
- snapshotTtlMs: number
139
- restoreWindowMs: number
140
- now: () => number
141
- tryWriteApi: TodoPreserverOptions['tryWriteApi']
142
- }
143
-
144
- // ─── TodoPreserver ─────────────────────────────────────────────────────
145
-
146
- /**
147
- * Preserve a session's todo list across compaction by intercepting the first
148
- * post-compaction `todowrite`. All public methods are best-effort — the
149
- * hooks can never break the session; failures are logged and swallowed.
150
- */
151
- export class TodoPreserver {
152
- private readonly client: TodoPreserverClient
153
- private readonly options: ResolvedTodoPreserverOptions
154
- private readonly warn: (message: string) => void
155
- private readonly snapshots = new Map<string, SnapshotEntry>()
156
-
157
- constructor(deps: TodoPreserverDeps) {
158
- this.client = deps.client
159
- const opts = deps.options ?? {}
160
- this.options = {
161
- snapshotTtlMs: opts.snapshotTtlMs ?? SNAPSHOT_TTL_MS,
162
- restoreWindowMs: opts.restoreWindowMs ?? RESTORE_WINDOW_MS,
163
- now: opts.now ?? Date.now,
164
- tryWriteApi: opts.tryWriteApi,
165
- }
166
- this.warn = deps.logger?.warn ?? ((message: string) => log.warn(message))
167
- }
168
-
169
- /**
170
- * CAPTURE (wired from `experimental.session.compacting`): GET the session's
171
- * full todo list and store it as the restore snapshot. An empty list
172
- * stores nothing (zero noise). Never throws — a GET failure is logged and
173
- * the session compacts normally.
174
- */
175
- async capture(sessionID: string): Promise<void> {
176
- this.pruneExpired()
177
- const path = safeSessionPath(sessionID)
178
- if (!path) {
179
- this.warn(`todo snapshot capture skipped: invalid sessionID "${sessionID}"`)
180
- return
181
- }
182
- try {
183
- const todos = await this.client.session.todo(path)
184
- if (todos.length === 0) {
185
- // Nothing to preserve → drop any stale entry so no restore happens.
186
- this.snapshots.delete(sessionID)
187
- return
188
- }
189
- this.snapshots.set(sessionID, {
190
- todos,
191
- capturedAt: this.now(),
192
- restored: false,
193
- })
194
- } catch (err: unknown) {
195
- const reason = err instanceof Error ? err.message : String(err)
196
- this.warn(`todo snapshot capture failed for session ${sessionID}: ${reason}`)
197
- }
198
- }
199
-
200
- /**
201
- * RESTORE activation (wired from the `event` hook on `session.compacted`):
202
- * mark the captured snapshot as restore-pending. Without a fresh snapshot
203
- * (no capture, empty list, or expired TTL) this is a no-op — fail-open.
204
- * When a direct-write adapter is injected and succeeds, the snapshot is
205
- * dropped so interception never runs. Never throws.
206
- */
207
- async onCompacted(sessionID: string): Promise<void> {
208
- try {
209
- const entry = this.snapshots.get(sessionID)
210
- if (entry === undefined) return
211
- if (this.expired(entry)) {
212
- this.snapshots.delete(sessionID)
213
- return
214
- }
215
- if (await this.tryWriteApi(sessionID, entry.todos)) {
216
- this.snapshots.delete(sessionID)
217
- }
218
- // Otherwise the entry stays pending: the first todowrite within the
219
- // restore window is rewritten with the snapshot (beforeTodoWrite).
220
- } catch (err: unknown) {
221
- const reason = err instanceof Error ? err.message : String(err)
222
- this.warn(`todo restore activation failed for session ${sessionID}: ${reason}`)
223
- }
224
- }
225
-
226
- /**
227
- * GUARD (wired on `tool.execute.before`, chained after the read-only
228
- * enforcement guard): intercept `todowrite` calls for a session whose
229
- * snapshot is pending. The FIRST call inside the restore window has
230
- * `output.args.todos` rewritten with the exact captured list; subsequent
231
- * calls inside the window throw TodoRestoreInProgressError; calls outside
232
- * the window, for other sessions, or for other tools pass through
233
- * untouched. Fail-open: the only throw is the intentional denial.
234
- */
235
- async beforeTodoWrite(input: TodoWriteBeforeInput, output: TodoWriteBeforeOutput): Promise<void> {
236
- if (input.tool !== 'todowrite') return
237
- const entry = this.snapshots.get(input.sessionID)
238
- if (entry === undefined) return
239
- try {
240
- const now = this.now()
241
- if (now - entry.capturedAt >= this.options.snapshotTtlMs) {
242
- this.snapshots.delete(input.sessionID)
243
- return
244
- }
245
- if (now - entry.capturedAt >= this.options.restoreWindowMs) {
246
- this.snapshots.delete(input.sessionID)
247
- return
248
- }
249
- if (entry.restored) {
250
- throw new TodoRestoreInProgressError(input.sessionID)
251
- }
252
- if (output.args === undefined) {
253
- this.warn(
254
- `todo restore: hook output.args missing for session ${input.sessionID} — passing through`,
255
- )
256
- return
257
- }
258
- output.args.todos = entry.todos
259
- entry.restored = true
260
- } catch (err: unknown) {
261
- // Rethrow ONLY the intentional denial; everything else is fail-open.
262
- if (err instanceof TodoRestoreInProgressError) throw err
263
- const reason = err instanceof Error ? err.message : String(err)
264
- this.warn(`todo restore interception failed for session ${input.sessionID}: ${reason}`)
265
- }
266
- }
267
-
268
- /**
269
- * Version-sensitive direct-write attempt. Returns false (fast) when no
270
- * adapter is injected — the SDK 1.18.11 reality — so restore proceeds via
271
- * interception. With an adapter, a resolved true means the list is already
272
- * restored server-side; a throw or false falls back to interception.
273
- * Never throws.
274
- */
275
- async tryWriteApi(sessionID: string, todos: TodoLike[]): Promise<boolean> {
276
- const write = this.options.tryWriteApi
277
- if (write === undefined) return false
278
- try {
279
- return await write(sessionID, todos)
280
- } catch (err: unknown) {
281
- const reason = err instanceof Error ? err.message : String(err)
282
- this.warn(`todo write API attempt failed for session ${sessionID}: ${reason}`)
283
- return false
284
- }
285
- }
286
-
287
- private now(): number {
288
- return this.options.now()
289
- }
290
-
291
- private expired(entry: SnapshotEntry): boolean {
292
- return this.now() - entry.capturedAt >= this.options.snapshotTtlMs
293
- }
294
-
295
- /** Drop expired snapshots (bounded by capture frequency — no timers). */
296
- private pruneExpired(): void {
297
- for (const [sessionID, entry] of this.snapshots) {
298
- if (this.expired(entry)) this.snapshots.delete(sessionID)
299
- }
300
- }
301
- }
@@ -1,159 +0,0 @@
1
- /** Host-real context ceiling probe for C9/tool filtering. */
2
-
3
- import type { PluginInput } from '@opencode-ai/plugin'
4
- import { createPantheonLogger, type PantheonLogger } from './logger.ts'
5
- import type { NativeTaskStatus } from './native-task-status.ts'
6
-
7
- export interface ToolCeilingSnapshot {
8
- usage: { inputTokens: number; outputTokens: number }
9
- limit: { contextTokens: number }
10
- supportsToolFiltering: boolean
11
- }
12
-
13
- export type ToolCeilingResult =
14
- | {
15
- status: 'OK'
16
- ceiling: number
17
- usage: ToolCeilingSnapshot['usage']
18
- limit: ToolCeilingSnapshot['limit']
19
- }
20
- | { status: Exclude<NativeTaskStatus, 'OK'>; detail: string }
21
-
22
- export type HostToolCeilingSource = () => unknown | Promise<unknown>
23
-
24
- function isRecord(value: unknown): value is Record<string, unknown> {
25
- return typeof value === 'object' && value !== null && !Array.isArray(value)
26
- }
27
-
28
- function isFiniteNonNegative(value: unknown): value is number {
29
- return typeof value === 'number' && Number.isFinite(value) && value >= 0
30
- }
31
-
32
- function isSnapshot(value: unknown): value is ToolCeilingSnapshot {
33
- if (!isRecord(value) || !isRecord(value.usage) || !isRecord(value.limit)) return false
34
- return (
35
- isFiniteNonNegative(value.usage.inputTokens) &&
36
- isFiniteNonNegative(value.usage.outputTokens) &&
37
- isFiniteNonNegative(value.limit.contextTokens) &&
38
- typeof value.supportsToolFiltering === 'boolean'
39
- )
40
- }
41
-
42
- /** Probe exact host usage/limit without estimation, fallback, or retry. */
43
- export async function probeToolCeiling(source?: HostToolCeilingSource): Promise<ToolCeilingResult> {
44
- if (source === undefined)
45
- return { status: 'UNSUPPORTED', detail: 'host SDK exposes no context probe' }
46
-
47
- let raw: unknown
48
- try {
49
- raw = await source()
50
- } catch (error: unknown) {
51
- return { status: 'UNAVAILABLE', detail: error instanceof Error ? error.message : String(error) }
52
- }
53
- if (!isSnapshot(raw))
54
- return { status: 'CORRUPT_DATA', detail: 'host context probe returned malformed data' }
55
- if (raw.supportsToolFiltering === false) {
56
- return { status: 'UNSUPPORTED', detail: 'host SDK does not filter tools' }
57
- }
58
- const used = raw.usage.inputTokens + raw.usage.outputTokens
59
- if (used > raw.limit.contextTokens) {
60
- return { status: 'CORRUPT_DATA', detail: 'host usage exceeds context limit' }
61
- }
62
- return {
63
- status: 'OK',
64
- ceiling: raw.limit.contextTokens - used,
65
- usage: raw.usage,
66
- limit: raw.limit,
67
- }
68
- }
69
-
70
- /**
71
- * Read a ceiling from the actual OpenCode SDK event and provider catalogue.
72
- *
73
- * `message.updated` is the SDK's runtime usage source (`info.tokens`). The
74
- * provider catalogue supplies the selected model's context limit and its
75
- * `capabilities.toolcall` flag. This adapter intentionally does not accept a
76
- * caller-provided snapshot/callback, so tests cannot accidentally turn a
77
- * fixture into a claimed host probe.
78
- */
79
- export async function probeToolCeilingFromHost(
80
- client: PluginInput['client'],
81
- event: unknown,
82
- ): Promise<ToolCeilingResult> {
83
- if (!isRecord(event) || event.type !== 'message.updated' || !isRecord(event.properties)) {
84
- return { status: 'UNSUPPORTED', detail: 'host SDK event has no message usage' }
85
- }
86
- const info = event.properties.info
87
- if (
88
- !isRecord(info) ||
89
- typeof info.providerID !== 'string' ||
90
- typeof info.modelID !== 'string' ||
91
- !isRecord(info.tokens)
92
- ) {
93
- return { status: 'UNSUPPORTED', detail: 'host SDK message has no token usage' }
94
- }
95
- const providerID = info.providerID as string
96
- const modelID = info.modelID as string
97
- const tokens = info.tokens as Record<string, unknown>
98
-
99
- let providersResult: unknown
100
- try {
101
- providersResult = await client.config.providers()
102
- } catch (error: unknown) {
103
- return { status: 'UNAVAILABLE', detail: error instanceof Error ? error.message : String(error) }
104
- }
105
- if (!isRecord(providersResult) || providersResult.error !== undefined) {
106
- return { status: 'UNAVAILABLE', detail: 'host SDK provider catalogue unavailable' }
107
- }
108
- const data = providersResult.data
109
- if (!isRecord(data) || !Array.isArray(data.providers)) {
110
- return { status: 'CORRUPT_DATA', detail: 'host SDK provider catalogue malformed' }
111
- }
112
-
113
- const provider = data.providers.find(
114
- (candidate) =>
115
- isRecord(candidate) &&
116
- candidate.id === providerID &&
117
- isRecord(candidate.models) &&
118
- isRecord(candidate.models[modelID]),
119
- )
120
- if (!isRecord(provider) || !isRecord(provider.models)) {
121
- return { status: 'UNSUPPORTED', detail: 'host SDK model metadata unavailable' }
122
- }
123
- const model = provider.models[modelID]
124
- if (!isRecord(model) || !isRecord(model.limit) || !isRecord(model.capabilities)) {
125
- return { status: 'UNSUPPORTED', detail: 'host SDK model ceiling capability unavailable' }
126
- }
127
-
128
- return probeToolCeiling(() => ({
129
- usage: { inputTokens: tokens.input, outputTokens: tokens.output },
130
- limit: { contextTokens: (model.limit as Record<string, unknown>).context },
131
- supportsToolFiltering: (model.capabilities as Record<string, unknown>).toolcall,
132
- }))
133
- }
134
-
135
- const log = createPantheonLogger({ module: 'pantheon-tool-ceiling' })
136
-
137
- /**
138
- * Handle the host usage event and retain the result for the compaction hook.
139
- * Malformed SDK events are diagnostic-only: they must never break the event
140
- * pipeline or create an entry under an invalid session identifier.
141
- */
142
- export async function handleToolCeilingEvent(
143
- client: PluginInput['client'],
144
- event: unknown,
145
- ceilings: Map<string, ToolCeilingResult>,
146
- logger: Pick<PantheonLogger, 'warn'> = log,
147
- ): Promise<ToolCeilingResult> {
148
- const sessionID = (
149
- event as { properties?: { info?: { sessionID?: unknown } } } | null | undefined
150
- )?.properties?.info?.sessionID
151
- if (typeof sessionID !== 'string' || sessionID.trim() === '') {
152
- logger.warn('[Pantheon Plugin] message.updated event has no valid sessionID')
153
- return { status: 'UNSUPPORTED', detail: 'host SDK event has no valid sessionID' }
154
- }
155
-
156
- const result = await probeToolCeilingFromHost(client, event)
157
- ceilings.set(sessionID, result)
158
- return result
159
- }
@@ -1,153 +0,0 @@
1
- /**
2
- * V1→V2 Bridge — passes V1 infrastructure singletons through V2 context options.
3
- *
4
- * The V2 plugin (`plugin-v2.ts`) registers tools via `ctx.tool.transform()` but
5
- * lacks the runtime singletons (BackgroundJobBoard, delegation client, goal store,
6
- * todo enforcer, vision handler) that live in the V1 plugin. This bridge:
7
- *
8
- * 1. Wraps V1 singletons into a portable `PantheonV2Bridge` interface.
9
- * 2. Attaches the bridge to V2 `ctx.options` so V2 tool handlers can access it.
10
- * 3. Provides `getV2BridgeFromContext()` for V2 tools to retrieve the bridge.
11
- *
12
- * Design: the bridge is **optional** — V2 plugin works without it (graceful
13
- * fallback with limited functionality). V1 and V2 are never directly coupled;
14
- * communication is via the `PantheonV2Bridge` interface only.
15
- *
16
- * @module v2-bridge
17
- */
18
-
19
- import type { BackgroundJobBoard } from './background-job-board.ts'
20
- import type { GoalStore } from './goal-store.ts'
21
- import type { TodoEnforcer } from './todo-enforcer.ts'
22
-
23
- // ─── Types ─────────────────────────────────────────────────────────────
24
-
25
- /**
26
- * Minimal structural view of the V2 PluginContext — we only need `options`
27
- * to inject/retrieve the bridge. Avoids importing V2 SDK types directly.
28
- */
29
- export interface V2ContextLike {
30
- options: Record<string, unknown>
31
- }
32
-
33
- /** Structural view of the V1 PluginInput — the fields the bridge needs. */
34
- export interface V1PluginInput {
35
- client: unknown
36
- directory: string
37
- }
38
-
39
- /**
40
- * Vision handler surface — the subset of the V1 vision handler the bridge
41
- * exposes. Full type is the return of `createVisionHandler(input)`, but we
42
- * only need the hook functions for V2 event delegation.
43
- */
44
- export interface VisionHandler {
45
- chatMessage: (...args: unknown[]) => Promise<void>
46
- messagesTransform: (...args: unknown[]) => Promise<void>
47
- event: (...args: unknown[]) => Promise<void>
48
- }
49
-
50
- /**
51
- * Full bridge interface — all V1 infrastructure V2 tools need.
52
- *
53
- * Every field is optional to support partial initialization and graceful
54
- * degradation when V1 infrastructure is not available.
55
- */
56
- export interface PantheonV2Bridge {
57
- /** Background job board — tracks running/completed/cancelled delegated jobs. */
58
- board?: BackgroundJobBoard
59
- /** Goal store — file-based persistence for full-auto goal loop. */
60
- goalStore?: GoalStore
61
- /** Todo enforcer — idle continuation when todos are incomplete. */
62
- todoEnforcer?: TodoEnforcer
63
- /** Vision handler — image analysis, chat message enrichment, event handling. */
64
- visionHandler?: VisionHandler
65
- }
66
-
67
- /**
68
- * Extended V2 context options that carry the bridge.
69
- * The bridge is attached under the `__pantheonV1Bridge` key to avoid
70
- * collisions with user-defined options.
71
- */
72
- export const BRIDGE_OPTIONS_KEY = '__pantheonV1Bridge' as const
73
-
74
- // ─── Bridge Factory ────────────────────────────────────────────────────
75
-
76
- /**
77
- * Create a bridge from V1 singletons.
78
- *
79
- * Call this inside the V1 plugin's `setup()` AFTER the singletons are
80
- * initialized, then pass the result to V2 via `ctx.options`.
81
- *
82
- * @example
83
- * ```ts
84
- * // In V1 plugin setup (plugin.ts):
85
- * const bridge = createV2Bridge({ board, goalStore, ... })
86
- * // Then pass bridge to V2 context via options
87
- * ```
88
- */
89
- export function createV2Bridge(singletons: PantheonV2Bridge): PantheonV2Bridge {
90
- // Return a frozen copy — bridge consumers must not mutate singletons.
91
- return Object.freeze({ ...singletons })
92
- }
93
-
94
- /**
95
- * Retrieve the bridge from a V2 PluginContext.
96
- *
97
- * Returns `null` when the bridge was not injected (V2 running standalone
98
- * or V1 not yet initialized). V2 tools should check for null and
99
- * degrade gracefully.
100
- *
101
- * @example
102
- * ```ts
103
- * // In a V2 tool handler:
104
- * const bridge = getV2BridgeFromContext(ctx)
105
- * if (!bridge?.board) {
106
- * return { text: 'Background job board unavailable — delegation disabled.' }
107
- * }
108
- * ```
109
- */
110
- export function getV2BridgeFromContext(ctx: V2ContextLike): PantheonV2Bridge | null {
111
- const bridge = ctx.options[BRIDGE_OPTIONS_KEY]
112
- if (bridge != null && typeof bridge === 'object') {
113
- return bridge as PantheonV2Bridge
114
- }
115
- return null
116
- }
117
-
118
- /**
119
- * Inject the bridge into a V2 PluginContext's options.
120
- *
121
- * Call this in the V1 plugin to make the bridge available to V2 tools.
122
- * Safe to call multiple times — subsequent calls overwrite the previous bridge.
123
- */
124
- export function injectBridge(ctx: V2ContextLike, bridge: PantheonV2Bridge): void {
125
- ctx.options[BRIDGE_OPTIONS_KEY] = bridge
126
- }
127
-
128
- // ─── Process-wide registration (cross-generation) ──────────────────────
129
-
130
- /**
131
- * The bridge registered by whichever plugin loaded first in this process.
132
- *
133
- * The module-level handle lives HERE rather than in `plugin-v2.ts` because V1
134
- * must be able to publish its singletons WITHOUT importing the V2 plugin: a
135
- * V1-only install never loads `plugin-v2.ts`, and importing it just to hand
136
- * over a bridge would pull the V2 `define()` into that process.
137
- *
138
- * Why registration matters: in a process that loads both generations (npm +
139
- * repo double load, or a mixed config), V1's idle dispatcher and the V2 entry
140
- * would otherwise each build a TodoEnforcer and answer the same `session.idle`
141
- * twice — two continuation prompts for one idle. V1 registers; V2 reuses.
142
- */
143
- let registeredBridge: PantheonV2Bridge | null = null
144
-
145
- /** Publish (or, with `null`, clear) the process-wide bridge. */
146
- export function registerV2Bridge(bridge: PantheonV2Bridge | null): void {
147
- registeredBridge = bridge
148
- }
149
-
150
- /** The bridge published by this process, or null. */
151
- export function getRegisteredV2Bridge(): PantheonV2Bridge | null {
152
- return registeredBridge
153
- }