pantheon-opencode 1.6.2-beta.1 → 1.6.2-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +163 -0
  2. package/README.md +236 -60
  3. package/README.pt-BR.md +19 -1
  4. package/bin/pantheon-init.mjs +195 -13
  5. package/package.json +11 -3
  6. package/plugin.json +1 -1
  7. package/prompts/README.md +58 -0
  8. package/prompts/debug-issue.prompt.md +46 -0
  9. package/prompts/dynamic/agora-generated.txt +38 -0
  10. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  11. package/prompts/focus.prompt.md +42 -0
  12. package/prompts/implement-feature.prompt.md +39 -0
  13. package/prompts/optimize-database.prompt.md +58 -0
  14. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  15. package/prompts/plan-architecture.prompt.md +59 -0
  16. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  17. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  18. package/prompts/semantic-summarize.md +50 -0
  19. package/prompts/sketch.prompt.md +91 -0
  20. package/prompts/subtask.prompt.md +131 -0
  21. package/pyproject.toml +1 -1
  22. package/scripts/decision-router-budget.mjs +780 -0
  23. package/scripts/decision-router-v2-budget.mjs +218 -0
  24. package/scripts/decision-router-v2-egress.mjs +272 -0
  25. package/scripts/decision-router.mjs +758 -0
  26. package/scripts/docs-check-changelog.mjs +5 -3
  27. package/scripts/install/component-selection.mjs +9 -4
  28. package/scripts/install/decision-layer-preview.mjs +376 -0
  29. package/scripts/install/decision-router-config.mjs +560 -0
  30. package/scripts/install/health-check.mjs +20 -11
  31. package/scripts/install/interactive.mjs +103 -14
  32. package/scripts/install/interrupt.mjs +4 -3
  33. package/scripts/install/migrate.mjs +123 -72
  34. package/scripts/install/opencode.mjs +178 -122
  35. package/scripts/install/plan.mjs +8 -1
  36. package/scripts/install/plugin.mjs +4 -3
  37. package/scripts/install/state.mjs +12 -0
  38. package/scripts/install/strings.mjs +22 -0
  39. package/scripts/install/venv.mjs +34 -17
  40. package/scripts/mcp_resources.py +11 -9
  41. package/scripts/release-notes.mjs +30 -7
  42. package/scripts/restore.mjs +22 -10
  43. package/scripts/sync-tui.mjs +3 -3
  44. package/scripts/test-opencode-v2-sandbox.sh +10 -6
  45. package/scripts/versioning.mjs +41 -5
  46. package/src/agents/aphrodite.md +6 -1
  47. package/src/agents/apollo.md +1 -0
  48. package/src/agents/athena.md +1 -0
  49. package/src/agents/demeter.md +1 -1
  50. package/src/agents/gaia.md +1 -0
  51. package/src/agents/hephaestus.md +1 -1
  52. package/src/agents/hermes.md +8 -10
  53. package/src/agents/iris.md +1 -1
  54. package/src/agents/mnemosyne.md +1 -0
  55. package/src/agents/nyx.md +1 -1
  56. package/src/agents/prometheus.md +1 -1
  57. package/src/agents/talos.md +6 -1
  58. package/src/agents/themis.md +1 -1
  59. package/src/agents/zeus.md +52 -62
  60. package/src/mcp/eval_store.py +11 -4
  61. package/src/mcp/mcp_resources.py +11 -9
  62. package/src/mcp/memory_mcp.py +293 -150
  63. package/src/pantheon/cost-command.ts +30 -133
  64. package/src/pantheon/jev-decision-tool.ts +347 -0
  65. package/src/pantheon/jev-decisions.ts +625 -0
  66. package/src/pantheon/local-decision-agents.ts +170 -0
  67. package/src/pantheon/local-decision-budget.ts +1046 -0
  68. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  69. package/src/pantheon/local-decision-prompt.ts +256 -0
  70. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  71. package/src/pantheon/local-decision-router.ts +225 -0
  72. package/src/pantheon/local-decision-skills.ts +281 -0
  73. package/src/pantheon/local-decision-tool.ts +160 -0
  74. package/src/pantheon/local-decision-turn.ts +101 -0
  75. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  76. package/src/pantheon/local-orchestration.ts +322 -0
  77. package/src/pantheon/model-pricing.ts +1 -536
  78. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  79. package/src/pantheon/v2-decision-budget.ts +456 -0
  80. package/src/pantheon/v2-decision-contracts.ts +300 -0
  81. package/src/pantheon/v2-decision-egress.ts +203 -0
  82. package/src/pantheon/v2-decision-events.ts +180 -0
  83. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  84. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  85. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  86. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  87. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  88. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  89. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  90. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  91. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  92. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  93. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  94. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  95. package/src/pantheon/v2-decision-points.ts +242 -0
  96. package/src/pantheon/v2-decision-policy.ts +166 -0
  97. package/src/pantheon/v2-decision-premises.ts +146 -0
  98. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  99. package/src/pantheon/v2-decision-rank.ts +91 -0
  100. package/src/pantheon/v2-decision-registry.ts +391 -0
  101. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  102. package/src/pantheon/v2-decision-shadow.ts +123 -0
  103. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  104. package/src/pantheon/v2-decision-verify.ts +51 -0
  105. package/src/pantheon/v2-hook-engine.ts +307 -0
  106. package/src/pantheon/v2-native-decisions.ts +365 -0
  107. package/src/pantheon/v2-shell-hooks.ts +66 -2
  108. package/src/pantheon/v2-tools.ts +38 -15
  109. package/src/plugin-v2.ts +419 -26
  110. package/src/plugin.ts +4 -0
  111. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  112. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  113. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  114. package/src/plugins/tui/dist/server-v2.js +19 -666
  115. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  116. package/src/plugins/tui/dist/tui-v2.d.ts +11 -203
  117. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  118. package/src/plugins/tui/dist/tui-v2.js +187 -1917
  119. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  120. package/src/plugins/tui/dist/tui.js +1 -1
  121. package/src/plugins/tui/package-lock.json +17 -2
  122. package/src/plugins/tui/package.json +4 -2
  123. package/src/plugins/tui/src/cost-data.ts +607 -0
  124. package/src/plugins/tui/src/index-v2.tsx +213 -54
  125. package/src/plugins/tui/src/model-pricing.ts +536 -0
  126. package/src/plugins/tui/src/server-v2.ts +18 -838
  127. package/src/plugins/tui/tsdown.config.ts +28 -6
  128. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  129. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  130. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  131. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  132. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  133. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  134. package/src/plugins/tui/dist/quota-cli.js +0 -184
  135. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  136. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +0 -390
  137. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
  138. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  139. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  140. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  141. package/src/plugins/tui/src/quota-cli.ts +0 -237
  142. package/src/plugins/tui/src/quota-rpc.ts +0 -209
  143. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  144. package/src/plugins/tui/src/quota-v2.tsx +0 -986
package/src/plugin-v2.ts CHANGED
@@ -2,12 +2,14 @@
2
2
  * Pantheon V2 Plugin — full orchestration plugin for OpenCode V2.
3
3
  *
4
4
  * Registers:
5
- * - 3 unconditional self-sufficient tools via V2 tool.transform (hashline_edit,
6
- * pantheon_cost, pantheon_model) plus up to 2 host-dependent ones: native
5
+ * - 4 unconditional self-sufficient tools via V2 tool.transform (hashline_edit,
6
+ * pantheon_cost, pantheon_model, pantheon_local_decision) plus up to 2 host-dependent ones: native
7
7
  * `vision_describe` when the host exposes the V2 model catalog (it resolves
8
8
  * OpenCode Zen auth and sends images directly to the selected multimodal
9
9
  * model), and `pantheon_bounded_read` when the host exposes its permission
10
10
  * and session APIs (root Zeus sessions only).
11
+ * `pantheon_local_decision` is advisory and rejects execution unless the
12
+ * host tool context identifies the caller as Zeus.
11
13
  * The goal tools need V1 infrastructure and are absent from this surface.
12
14
  * - 5 event subscriptions (session.created, idle, deleted, error, compacted)
13
15
  * - Session hooks (prompt, context, compaction)
@@ -71,6 +73,11 @@
71
73
  * If the SDK ever exposes these host domains, replacing `hostDomains` with the real
72
74
  * type is a one-line change. Do NOT make that change while 1.18.x lacks them.
73
75
  *
76
+ * The separate offline native Decisions scaffold is typed against
77
+ * `@opencode/plugin@2.2.5`. It intentionally has no production call site and
78
+ * does not claim native Decisions support for V1 or OpenCode V2.0/2.1. The
79
+ * legacy plugin registrations are not migrated as part of that scaffold.
80
+ *
74
81
  * V2_UNSUPPORTED_FEATURES distinguishes adapter limitations from observed
75
82
  * host-absent APIs; setup handles optional registrations on a best-effort basis.
76
83
  *
@@ -108,6 +115,9 @@ import {
108
115
  } from './pantheon/delegation-enforce.ts'
109
116
  import { GOAL_LOOP_DEFAULTS, GoalStore } from './pantheon/goal-loop.ts'
110
117
  import { createGuardPathResolver } from './pantheon/guard-path.ts'
118
+ import type { V2JevDecisionRuntime } from './pantheon/jev-decision-tool.ts'
119
+ import { DECISION_EGRESS_ACTION } from './pantheon/local-decision-egress-gate.ts'
120
+ import { applyDecisionRouterToPrompt } from './pantheon/local-decision-prompt.ts'
111
121
  import { getSharedBoard } from './pantheon/shared-board.ts'
112
122
  import {
113
123
  TODO_ENFORCER_DEFAULTS,
@@ -132,6 +142,16 @@ import {
132
142
  registerV2Bridge,
133
143
  type V2ContextLike,
134
144
  } from './pantheon/v2-bridge.ts'
145
+ import { createP7LoopPoint, p7LoopEnabledFromEnv } from './pantheon/v2-decision-points/p7-loop.ts'
146
+ import {
147
+ createP8Guardrail,
148
+ p8GuardrailEnabledFromEnv,
149
+ } from './pantheon/v2-decision-points/p8-guardrail.ts'
150
+ import { evaluateCompactionMemoryPoint } from './pantheon/v2-decision-points/p9-memory-compaction.ts'
151
+ import { evaluateCatalogPoint } from './pantheon/v2-decision-points/p11-catalog.ts'
152
+ import { DECISION_POINT_REGISTRY } from './pantheon/v2-decision-points.ts'
153
+ import { observePromptSurface } from './pantheon/v2-decision-prompt-surface.ts'
154
+ import { createTelemetrySink, type TelemetrySink } from './pantheon/v2-decision-telemetry.ts'
135
155
  import {
136
156
  type AuthoritativeSession,
137
157
  evaluateV2Delegation,
@@ -141,13 +161,15 @@ import {
141
161
  v2ResourceTarget,
142
162
  } from './pantheon/v2-delegation-enforce.ts'
143
163
  import { createV2ExecuteAfter, resolveV2SandboxConfig } from './pantheon/v2-execute-after.ts'
164
+ import { runSecretScanInProcess } from './pantheon/v2-hook-engine.ts'
144
165
  import { applyV2ModelOverrides, readV2ModelConfiguration } from './pantheon/v2-model-overrides.ts'
166
+ import type { NativeDecisionRequest } from './pantheon/v2-native-decisions.ts'
145
167
  import { createV2ShellHooks, type V2ShellRunner } from './pantheon/v2-shell-hooks.ts'
146
168
  import { createV2ToolDefinitions, type V2ToolResult } from './pantheon/v2-tools.ts'
147
169
  import { V2_UNSUPPORTED_FEATURE_SEED } from './pantheon/v2-unsupported.mjs'
148
170
  import { buildV2VisionPromptContext, type V2VisionRuntime } from './pantheon/v2-vision.ts'
149
171
  import { sanitizeVisionHistory } from './pantheon/vision.ts'
150
- import { type HookPayload, type HookResult, runHook } from './plugins/hook-runner.ts'
172
+ import type { HookPayload, HookResult } from './plugins/hook-runner.ts'
151
173
 
152
174
  // ─── Unsupported Features Registry ───────────────────────────────────────
153
175
 
@@ -337,6 +359,16 @@ interface V2GenerateDomain {
337
359
  text?: (input: { model: { providerID: string; id: string }; prompt: string }) => Promise<unknown>
338
360
  }
339
361
 
362
+ /**
363
+ * The host's experimental generation domain. Only `decisions` is declared: the
364
+ * native Jev route feature-detects it, and every other member stays unknown.
365
+ */
366
+ interface V2ExperimentalDomain {
367
+ generate?: {
368
+ decisions?: (request: NativeDecisionRequest) => Promise<unknown>
369
+ }
370
+ }
371
+
340
372
  /** `PluginContext` plus the host domains 1.18.x omits. See the module header. */
341
373
  interface HostPluginContext extends PluginContext {
342
374
  tool?: V2ToolDomain
@@ -345,6 +377,7 @@ interface HostPluginContext extends PluginContext {
345
377
  session?: V2SessionDomain
346
378
  model?: V2ModelDomain
347
379
  generate?: V2GenerateDomain
380
+ experimental?: V2ExperimentalDomain
348
381
  location?: V2LocationDomain
349
382
  }
350
383
 
@@ -655,12 +688,65 @@ async function registerV2Tools(
655
688
  // it, and the host rejects a definition whose result shape cannot satisfy
656
689
  // the declaration it makes.
657
690
  const model = host.model
658
- const visionReady = typeof model?.list === 'function'
691
+ const modelListFn = model?.list
692
+ const visionReady = typeof modelListFn === 'function'
659
693
  if (!visionReady) markUnsupported('vision-tool')
660
694
  const visionRuntime = visionReady ? ({ model } as V2VisionRuntime) : undefined
661
- const toolDefs = createV2ToolDefinitions(visionRuntime)
695
+ // The native Jev tool needs BOTH the V2 model catalog (route resolution)
696
+ // and the host's native Decisions API. A host without either simply does
697
+ // not get the tool — same feature-detect discipline as vision_describe.
698
+ const decisionsFn = host.experimental?.generate?.decisions
699
+ const jevReady = visionReady && typeof decisionsFn === 'function'
700
+ if (!jevReady) markUnsupported('jev-decision-tool')
701
+ const permissionAssertFn = host.permission?.assert
702
+ let jevRuntime: V2JevDecisionRuntime | undefined
703
+ if (jevReady && typeof decisionsFn === 'function' && typeof modelListFn === 'function') {
704
+ const decisionsOwner = host.experimental?.generate
705
+ const decide = decisionsFn
706
+ const listModels = modelListFn
707
+ // The 2.2.5 host exposes ctx.skill as the SkillEditor (list()); the SDK
708
+ // types this file sees declare skill as the registration hook, so the
709
+ // runtime shape is read through one narrow, feature-detected cast.
710
+ const skillDomain = (host as { skill?: { list?: () => unknown } }).skill
711
+ const skillList = skillDomain?.list
712
+ const permissionAssert =
713
+ typeof permissionAssertFn === 'function'
714
+ ? (input: Record<string, unknown>) => permissionAssertFn.call(host.permission, input)
715
+ : undefined
716
+ jevRuntime = {
717
+ // Every host method is invoked with its owning domain as receiver:
718
+ // the canary records `ctx.model.list()` (bound) succeeding on 2.2.5
719
+ // while a detached reference threw in the field and surfaced only as
720
+ // CATALOG_UNAVAILABLE. Same discipline as permissionAssert above.
721
+ listModels: () => listModels.call(host.model),
722
+ decide: (request: NativeDecisionRequest) => decide.call(decisionsOwner, request),
723
+ // Sync-or-async host skill list; absent/throwing falls back to the
724
+ // catalog-only preset inside the tool.
725
+ listSkills: async () => skillList?.call(skillDomain),
726
+ ...(permissionAssert === undefined ? {} : { permissionAssert }),
727
+ }
728
+ }
729
+ // P3 (complexity) declares `tool.invoke`; its construction site is the
730
+ // local selector's execute, fed by that tool's own input schema. The sink
731
+ // is the 0b record path (in-memory, bounded, I/O-free) and every record
732
+ // carries `mode: 'shadow'` — the mode the registry declares.
733
+ const p3Sink = createTelemetrySink()
734
+ p3TelemetrySink = p3Sink
735
+ const toolDefs = createV2ToolDefinitions(
736
+ visionRuntime,
737
+ {
738
+ complexitySink: (record) => {
739
+ p3Sink.emit({ ...record, mode: 'shadow' })
740
+ },
741
+ },
742
+ jevRuntime,
743
+ )
662
744
  if (boundedRead !== undefined) toolDefs.push(boundedRead)
663
745
 
746
+ // P11's record sink, created per registration (in-memory, bounded, I/O-free).
747
+ const p11Sink = createTelemetrySink()
748
+ p11TelemetrySink = p11Sink
749
+
664
750
  await toolCtx.transform((draft: V2ToolDraft) => {
665
751
  // Catalog grouping only. The host computes a tool's registration id as
666
752
  // `options.namespace === undefined ? name : `${namespace}_${name}``, and
@@ -682,6 +768,24 @@ async function registerV2Tools(
682
768
  execute: def.execute,
683
769
  })
684
770
  }
771
+
772
+ // P11 (catalog) shadow observation on the only measured catalogue
773
+ // surface: the draft the host hands this callback — `{list, get,
774
+ // namespace, add, update, remove}`, 20 host tools, 46 with MCP servers
775
+ // registered (F-07). `ctx.catalog` is absent at every measured point
776
+ // (F-05) and is not used. The adapter reads and nothing else: `list()` is
777
+ // called, the six members are type-checked, and no add/update/remove is
778
+ // ever invoked, so the registration above is the only mutation. Shadow
779
+ // has no responder, so the record names the validated `choice` question
780
+ // (`catalog.no.answer`) instead of inventing a selection. Runs after the
781
+ // adds so the draft it reads is the one the host will keep.
782
+ try {
783
+ evaluateCatalogPoint(draft, (record) => {
784
+ p11Sink.emit({ ...record, mode: 'shadow' })
785
+ })
786
+ } catch {
787
+ // Observation must never fail the tool registration.
788
+ }
685
789
  })
686
790
  return true
687
791
  } catch {
@@ -691,6 +795,105 @@ async function registerV2Tools(
691
795
 
692
796
  // ─── V2 Event Subscription ──────────────────────────────────────────────
693
797
 
798
+ /**
799
+ * The P7 telemetry sink created by the most recent event subscription.
800
+ *
801
+ * P7 writes through the 0b record path (`createTelemetrySink`): in-memory,
802
+ * bounded and I/O-free by design, so a test that asserts "the decision was
803
+ * actually recorded" has to read the same collector the wiring wrote to.
804
+ * Exported only for tests/pantheon/plugin-v2-contract.test.ts — production has
805
+ * no caller, and nothing in the plugin reads this back.
806
+ */
807
+ export function getP7TelemetrySinkForTests(): TelemetrySink | undefined {
808
+ return p7TelemetrySink
809
+ }
810
+
811
+ let p7TelemetrySink: TelemetrySink | undefined
812
+
813
+ /**
814
+ * The P8 telemetry sink created by the most recent permission-hook
815
+ * registration.
816
+ *
817
+ * P8 records every outcome it is responsible for — `guardrail.narrow`,
818
+ * `guardrail.keep`, `guardrail.refusal`, `p8.write.rejected`,
819
+ * `p8.write.delegation` and `p8.write.unconfirmed` — through the 0b record path
820
+ * (`createTelemetrySink`, in-memory, bounded, I/O-free). A guardrail that
821
+ * narrows without a record is indistinguishable from an inert one, which is
822
+ * exactly the defect PH5-1 closed. Every record carries the P8 registry `mode`
823
+ * (`off`), never `active`, and a `narrow` is recorded only when a re-read of
824
+ * the event still holds it (N9/N10). Exported only for
825
+ * tests/pantheon/plugin-v2-contract.test.ts.
826
+ */
827
+ export function getP8TelemetrySinkForTests(): TelemetrySink | undefined {
828
+ return p8TelemetrySink
829
+ }
830
+
831
+ let p8TelemetrySink: TelemetrySink | undefined
832
+
833
+ /**
834
+ * The prompt-surface telemetry sink created by the most recent prompt-hook
835
+ * registration.
836
+ *
837
+ * P1 and P2 observe the same admission payload through `observePromptSurface`;
838
+ * each shadow record is reduced through the 0b record path
839
+ * (`createTelemetrySink`, in-memory, bounded, I/O-free) and carries
840
+ * `mode: 'shadow'` — the registry mode both declare. Nothing in production
841
+ * reads this collector back, so the write is only a claim if a reader can
842
+ * assert it: this accessor is that reader, and
843
+ * tests/pantheon/plugin-v2-contract.test.ts is its only caller.
844
+ */
845
+ export function getPromptSurfaceTelemetrySinkForTests(): TelemetrySink | undefined {
846
+ return promptSurfaceTelemetrySink
847
+ }
848
+
849
+ let promptSurfaceTelemetrySink: TelemetrySink | undefined
850
+
851
+ /**
852
+ * The P3 telemetry sink created by the most recent tool registration.
853
+ *
854
+ * P3 is constructed at `tool.invoke`: `pantheon_local_decision`'s execute calls
855
+ * the adapter with the tool input, which carries `complexity` and `gateStatus`.
856
+ * Records are reduced through the same in-memory 0b path and carry the P3
857
+ * registry `mode` (`shadow`). Exported only for
858
+ * tests/pantheon/plugin-v2-contract.test.ts and the wiring audit.
859
+ */
860
+ export function getP3TelemetrySinkForTests(): TelemetrySink | undefined {
861
+ return p3TelemetrySink
862
+ }
863
+
864
+ let p3TelemetrySink: TelemetrySink | undefined
865
+
866
+ /**
867
+ * The P9 telemetry sink created by the most recent compaction-hook
868
+ * registration.
869
+ *
870
+ * P9 declares `session.hook('compaction')` and observes the MEASURED carrier
871
+ * only: the top-level `sessionID` and the `system` part array (F-01, F-02).
872
+ * Records go through the same in-memory, bounded 0b path and carry the P9
873
+ * registry `mode` (`shadow`). Exported only for
874
+ * tests/pantheon/plugin-v2-contract.test.ts and the wiring audit.
875
+ */
876
+ export function getP9TelemetrySinkForTests(): TelemetrySink | undefined {
877
+ return p9TelemetrySink
878
+ }
879
+
880
+ let p9TelemetrySink: TelemetrySink | undefined
881
+
882
+ /**
883
+ * The P11 telemetry sink created by the most recent tool registration.
884
+ *
885
+ * P11 declares `tool.transform` and reads the draft the host hands that
886
+ * callback (F-07) — the only measured catalogue surface, since `ctx.catalog` is
887
+ * absent (F-05). Records go through the in-memory, bounded 0b path and carry the
888
+ * P11 registry `mode` (`shadow`). Exported only for
889
+ * tests/pantheon/plugin-v2-contract.test.ts and the wiring audit.
890
+ */
891
+ export function getP11TelemetrySinkForTests(): TelemetrySink | undefined {
892
+ return p11TelemetrySink
893
+ }
894
+
895
+ let p11TelemetrySink: TelemetrySink | undefined
896
+
694
897
  /**
695
898
  * Attempt to subscribe to session events via V2 ctx.event.subscribe.
696
899
  *
@@ -709,12 +912,45 @@ function subscribeV2Events(
709
912
  return undefined
710
913
  }
711
914
 
915
+ // P7 loop adapter (PLAN §5.1 branch 1, selected by PROBE-D §7). Constructed
916
+ // here but inert unless PANTHEON_V2_P7_LOOP is set: the flag is OFF by
917
+ // default, and activation is Phase 4b — not this change. Observation is
918
+ // synchronous and self-contained, so it cannot block the stream, cannot
919
+ // throw into the dispatch, and does not alter the cleanup below.
920
+ //
921
+ // The sink is the 0b telemetry record path (`createTelemetrySink`, in-memory
922
+ // and bounded, no I/O). Each shadow record is reduced to its own allowlisted
923
+ // fields plus `mode: 'migration'` — the P7 registry mode — and nothing else:
924
+ // the execution count is not on the allowlist, so it is not recorded, and no
925
+ // prompt, response or user content can reach the record. A disabled adapter
926
+ // never calls the sink, so flag-off still emits zero records.
927
+ const telemetrySink = createTelemetrySink()
928
+ p7TelemetrySink = telemetrySink
929
+ const loopPoint = createP7LoopPoint({
930
+ enabled: p7LoopEnabledFromEnv(),
931
+ sink: (record) => {
932
+ telemetrySink.emit({ ...record, mode: 'migration' })
933
+ },
934
+ })
935
+
712
936
  const controller = new AbortController()
713
937
  void (async () => {
714
938
  try {
715
939
  // biome-ignore lint/style/noNonNullAssertion: subscribe guaranteed by guard above
716
940
  for await (const event of eventCtx.subscribe!({ signal: controller.signal })) {
717
941
  await handleV2SessionEvent(event)
942
+ try {
943
+ loopPoint.observe(event)
944
+ } catch {
945
+ // The adapter contains its own failures; this keeps a future
946
+ // regression out of the dispatch loop.
947
+ }
948
+ // KNOWN DEFECT, out of scope for Phase 4a: this branch and
949
+ // `handleV2SessionEvent`'s `session.compacted` case key on types the
950
+ // measured host never delivers — `session.idle` 0/11 runs and
951
+ // `session.compacted` 0/11 (PROBE-C, F-12). The live turn-end signal
952
+ // is `session.execution.succeeded`, observed above. The branches are
953
+ // left untouched on purpose; removing them is a separate change.
718
954
  if (event.type === 'session.idle' || event.type === 'session.deleted') {
719
955
  const properties = event.properties ?? {}
720
956
  const info = properties.info
@@ -1024,7 +1260,8 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
1024
1260
  // Config validity is independent of hook availability; warn before the early
1025
1261
  // return so a typo is visible even on a host that registers no session hook.
1026
1262
  warnContextPrunerConfigOnce(context.options)
1027
- const sessionCtx = hostDomains(context).session
1263
+ const host = hostDomains(context)
1264
+ const sessionCtx = host.session
1028
1265
 
1029
1266
  if (!sessionCtx?.hook) {
1030
1267
  return false
@@ -1113,10 +1350,17 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
1113
1350
  }
1114
1351
 
1115
1352
  try {
1353
+ // Prompt-surface shadow points (P1 and P2) share this payload. P3 moved to
1354
+ // `tool.invoke`, where its input actually carries a complexity vector; P6
1355
+ // and P10 are unwired because no measured surface carries their inputs.
1356
+ // The sink is in-memory and bounded, exactly like P7/P8; it is created per
1357
+ // registration so one setup cannot observe another's records.
1358
+ const promptSurfaceSink = createTelemetrySink()
1359
+ promptSurfaceTelemetrySink = promptSurfaceSink
1116
1360
  // "prompt" hook — preserve attached image references and add model-visible
1117
1361
  // instructions so Zeus can inspect visual context and pass it to the
1118
1362
  // implementation specialist before editing.
1119
- await sessionCtx.hook('prompt', (event: unknown) => {
1363
+ await sessionCtx.hook('prompt', async (event: unknown) => {
1120
1364
  try {
1121
1365
  // 2.0.29 host payload: `{ sessionID, messageID, prompt: { text,
1122
1366
  // files, agents, skills }, metadata, delivery }`. The session id is
@@ -1124,17 +1368,33 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
1124
1368
  // data: attachment's panic-free moment also relays it to the MCP.
1125
1369
  const admission = event as {
1126
1370
  sessionID?: unknown
1127
- prompt?: { text?: unknown; files?: unknown }
1371
+ messageID?: unknown
1372
+ prompt?: { text?: unknown; files?: unknown; skills?: unknown }
1128
1373
  } | null
1129
1374
  const prompt = admission?.prompt
1130
1375
  if (!prompt || typeof prompt.text !== 'string') return
1131
- if (prompt.text.includes('<!-- pantheon-v2-visual-context -->')) return
1132
- const sessionID =
1133
- typeof admission?.sessionID === 'string' && admission.sessionID.trim() !== ''
1134
- ? admission.sessionID
1135
- : undefined
1136
- const visualContext = buildV2VisionPromptContext(prompt.files, prompt.text, sessionID)
1137
- if (visualContext) prompt.text = `${prompt.text}\n\n${visualContext}`
1376
+ const userRequest = prompt.text
1377
+ if (!prompt.text.includes('<!-- pantheon-v2-visual-context -->')) {
1378
+ const sessionID =
1379
+ typeof admission?.sessionID === 'string' && admission.sessionID.trim() !== ''
1380
+ ? admission.sessionID
1381
+ : undefined
1382
+ const visualContext = buildV2VisionPromptContext(prompt.files, prompt.text, sessionID)
1383
+ if (visualContext) prompt.text = `${prompt.text}\n\n${visualContext}`
1384
+ }
1385
+
1386
+ // Local deterministic recommendations are advisory only. This path
1387
+ // never consults provider consent/credentials or invokes remote egress.
1388
+ await applyDecisionRouterToPrompt(admission, userRequest)
1389
+
1390
+ // Shadow observation only. The projection carries `prompt.agents` and
1391
+ // `prompt.skills` and nothing else, so no prompt text or file bytes
1392
+ // reach a record; observeShadow clones and freezes it, so admission is
1393
+ // not mutated. A failure here is contained by the outer catch and never
1394
+ // reaches the host.
1395
+ observePromptSurface(admission, (record) => {
1396
+ promptSurfaceSink.emit({ ...record, mode: 'shadow' })
1397
+ })
1138
1398
  } catch {
1139
1399
  // Fail-open: malformed/unsupported prompt shapes must not block input.
1140
1400
  }
@@ -1406,10 +1666,17 @@ function evaluateSecretScanResult(scan: HookResult): SecretScanDecision {
1406
1666
  return { action: 'fail-closed', reason: 'scanner-unexpected-exit' }
1407
1667
  }
1408
1668
 
1409
- /** Invocation of scripts/hooks/scan-secrets.sh used by the tool guard. */
1669
+ /** Invocation of the secret scan used by the tool guard. */
1410
1670
  type SecretScanRunner = (payload: HookPayload) => Promise<HookResult>
1411
1671
 
1412
- const defaultSecretScanRunner: SecretScanRunner = (payload) => runHook('scan-secrets.sh', payload)
1672
+ /**
1673
+ * The scan runs IN-PROCESS (src/pantheon/v2-hook-engine.ts, same patterns and
1674
+ * exit-code contract as the former scripts/hooks/scan-secrets.sh) so a tool
1675
+ * call no longer spawns a bash child. The runner signature and the classifier
1676
+ * below are unchanged; {@link setV2SecretScanRunnerForTests} still injects
1677
+ * structured results the in-process path cannot produce on its own.
1678
+ */
1679
+ const defaultSecretScanRunner: SecretScanRunner = async (payload) => runSecretScanInProcess(payload)
1413
1680
 
1414
1681
  let secretScanRunner: SecretScanRunner = defaultSecretScanRunner
1415
1682
 
@@ -1774,6 +2041,23 @@ async function registerV2ToolHooks(
1774
2041
 
1775
2042
  // ─── V2 Permission Hook ─────────────────────────────────────────────────
1776
2043
 
2044
+ /**
2045
+ * Read `event.effect` after P8 wrote to it, for the record.
2046
+ *
2047
+ * A hostile getter reads as `null`, which can only downgrade a recorded
2048
+ * `narrow` to `keep`, never upgrade one — the failure direction is "the record
2049
+ * claims less", never "the record claims an effect the event does not hold".
2050
+ */
2051
+ function readPermissionEffect(event: unknown): string | null {
2052
+ try {
2053
+ if (event === null || typeof event !== 'object') return null
2054
+ const effect = (event as { readonly effect?: unknown }).effect
2055
+ return typeof effect === 'string' ? effect : null
2056
+ } catch {
2057
+ return null
2058
+ }
2059
+ }
2060
+
1777
2061
  /**
1778
2062
  * Register permission hook via V2 ctx.permission.hook.
1779
2063
  *
@@ -1796,6 +2080,48 @@ async function registerV2PermissionHook(
1796
2080
  return false
1797
2081
  }
1798
2082
 
2083
+ // P8 guardrail (PLAN §5 P8, Phase 5). Constructed once at registration and
2084
+ // inert by default: `PANTHEON_V2_P8_GUARDRAIL` is absent in a default
2085
+ // install, and absent means disabled — this ships no behavioural change.
2086
+ // Enabled, it may only replace a wider effect with `deny`; it is synchronous,
2087
+ // never throws, and never runs for `decision.egress` or an existing deny.
2088
+ // Its outcome is recorded through the 0b telemetry path (in-memory, bounded,
2089
+ // I/O-free) so a narrow, a refusal and a rejected write are observable; the
2090
+ // disabled guardrail emits nothing.
2091
+ const p8Guardrail = createP8Guardrail({ enabled: p8GuardrailEnabledFromEnv() })
2092
+ const p8Sink = createTelemetrySink()
2093
+ p8TelemetrySink = p8Sink
2094
+ // The record's `mode` mirrors the P8 registry entry — `off` today — instead
2095
+ // of asserting `active` (N10a). A record may never advertise an activation
2096
+ // the registry and C8 deny, and deriving the value from the registry means
2097
+ // the two cannot drift apart again. `mode` describes the point's declared
2098
+ // mode; `decision`/`reason` carry the observation.
2099
+ const p8RegistryMode = DECISION_POINT_REGISTRY.find((point) => point.id === 'P8')?.mode ?? 'off'
2100
+ /**
2101
+ * Record one P8 outcome.
2102
+ *
2103
+ * `event` is re-read immediately before emitting: `narrowed`/`wrote` are the
2104
+ * guardrail's own post-write read, and a `Proxy` whose descriptor trap lies
2105
+ * can make that read and the next one disagree (N9). A `narrow` is therefore
2106
+ * recorded only when the event still holds `deny`; otherwise the record
2107
+ * states the effect that is actually there (`guardrail.keep` with
2108
+ * `p8.write.unconfirmed`), so sink and proof cannot contradict each other.
2109
+ */
2110
+ const recordP8 = (result: ReturnType<typeof p8Guardrail.apply>, event: unknown): void => {
2111
+ if (!p8Guardrail.enabled) return
2112
+ try {
2113
+ const unconfirmed = result.narrowed && readPermissionEffect(event) !== 'deny'
2114
+ p8Sink.emit({
2115
+ point: 'P8',
2116
+ decision: unconfirmed ? 'guardrail.keep' : result.decision,
2117
+ reason: unconfirmed ? 'p8.write.unconfirmed' : result.reason,
2118
+ mode: p8RegistryMode,
2119
+ })
2120
+ } catch {
2121
+ // Telemetry is best-effort and must not affect permission flow.
2122
+ }
2123
+ }
2124
+
1799
2125
  try {
1800
2126
  await permCtx.hook('evaluate', async (rawEvent: unknown) => {
1801
2127
  const event = rawEvent as V2PermissionEvent | null
@@ -1855,6 +2181,17 @@ async function registerV2PermissionHook(
1855
2181
  deny('permission event is missing')
1856
2182
  return
1857
2183
  }
2184
+ // `decision.egress` is Pantheon's own custom action. It is NOT decided
2185
+ // here: the user-level config/consent is the source of truth, and the
2186
+ // host's own permission rules are the kill-switch (see
2187
+ // local-decision-egress-gate). The v2.2.0 canary observed this hook runs
2188
+ // on the allow path of `permission.assert` and is skipped for an explicit
2189
+ // deny, so egress must never depend on it. Leaving the effect untouched
2190
+ // preserves whatever the host decided.
2191
+ if (event.action === DECISION_EGRESS_ACTION) {
2192
+ writeProof()
2193
+ return
2194
+ }
1858
2195
  if (!Array.isArray(event.resources) || event.resources.length === 0) {
1859
2196
  deny('permission resources are missing or malformed')
1860
2197
  return
@@ -1906,8 +2243,29 @@ async function registerV2PermissionHook(
1906
2243
  // Native-only resources remain under host policy. If a Pantheon target
1907
2244
  // appears anywhere, the shared policy evaluates the complete resource set.
1908
2245
  decision = evaluateV2Delegation(event, session, event.effect, origin)
1909
- if (decision === 'deny') deny('caller or target is not allowed by delegation policy')
1910
- else writeProof()
2246
+
2247
+ // P8 (Phase 5): read the effect left in place and, only when the flag is
2248
+ // on and a declared rule matches, replace it with `deny`. Off by default,
2249
+ // synchronous, contained — it cannot grant, delay or throw into admission.
2250
+ //
2251
+ // Apply BEFORE recording (PH5-1): `writeProof` reads `event.effect`, so a
2252
+ // proof written first recorded `effectAfter: allow` for an event P8 then
2253
+ // narrowed. The order below is apply → final effect → record, and the
2254
+ // record carries the post-apply effect plus the guardrail outcome.
2255
+ //
2256
+ // Record only after the effect is final (N10b). `deny()` below rewrites
2257
+ // the effect, and a record emitted before it would describe a state the
2258
+ // handler never leaves behind; when the delegation policy already denies,
2259
+ // the deny is the policy's, so P8 claims no narrowing at all — it changed
2260
+ // nothing about that outcome. `deny()` also throws on an immutable event,
2261
+ // and a record emitted after a throw would describe an unreached state.
2262
+ const p8Result = p8Guardrail.apply(event)
2263
+ if (decision === 'deny') {
2264
+ deny('caller or target is not allowed by delegation policy')
2265
+ return
2266
+ }
2267
+ writeProof()
2268
+ recordP8(p8Result, event)
1911
2269
  })
1912
2270
  return true
1913
2271
  } catch {
@@ -2110,7 +2468,13 @@ export const plugin = define({
2110
2468
  const boundedRead = await prepareV2BoundedRead(context).catch(() => undefined)
2111
2469
  if (boundedRead === undefined) markUnsupported('bounded-read')
2112
2470
 
2113
- // ─── Phase 2: V2 Event Subscription (best-effort) ────────────────
2471
+ // ─── Phase 2: V2 Permission Hook (best-effort) ───────────────────
2472
+ // Registered before the event subscription and session hooks so the
2473
+ // delegation matrix is enforced before any turn runs. Egress never depends
2474
+ // on this hook: the user-level config plus the host's own rules gate it.
2475
+ await registerV2PermissionHook(context, subagentOrigins).catch(() => false)
2476
+
2477
+ // ─── Phase 3: V2 Event Subscription (best-effort) ────────────────
2114
2478
  const eventCleanup = subscribeV2Events(context, boundedRead?.clearSession)
2115
2479
  if (eventCleanup) {
2116
2480
  activeCleanups.push(eventCleanup)
@@ -2118,13 +2482,13 @@ export const plugin = define({
2118
2482
  markUnsupported('event-stream')
2119
2483
  }
2120
2484
 
2121
- // ─── Phase 3: V2 Session Hooks (best-effort) ─────────────────────
2485
+ // ─── Phase 4: V2 Session Hooks (best-effort) ─────────────────────
2122
2486
  const sessionHooksRegistered = await registerV2SessionHooks(context).catch(() => false)
2123
2487
  if (!sessionHooksRegistered) {
2124
2488
  markUnsupported('session-hooks')
2125
2489
  }
2126
2490
 
2127
- // ─── Phase 4: V2 Tool Hooks (best-effort) ────────────────────────
2491
+ // ─── Phase 5: V2 Tool Hooks (best-effort) ────────────────────────
2128
2492
  const toolHookResult = await registerV2ToolHooks(
2129
2493
  context,
2130
2494
  subagentOrigins,
@@ -2134,7 +2498,7 @@ export const plugin = define({
2134
2498
  markUnsupported('tool-execute-hooks')
2135
2499
  }
2136
2500
 
2137
- // ─── Phase 5: V2 Tool Registration (best-effort) ─────────────────
2501
+ // ─── Phase 6: V2 Tool Registration (best-effort) ─────────────────
2138
2502
  const boundedReadDefinition = toolHookResult.beforeRegistered
2139
2503
  ? boundedRead?.definition
2140
2504
  : undefined
@@ -2144,9 +2508,6 @@ export const plugin = define({
2144
2508
  const toolsRegistered = await registerV2Tools(context, boundedReadDefinition).catch(() => false)
2145
2509
  if (!toolsRegistered) markUnsupported('tool-transform')
2146
2510
 
2147
- // ─── Phase 6: V2 Permission Hook (best-effort) ───────────────────
2148
- await registerV2PermissionHook(context, subagentOrigins).catch(() => false)
2149
-
2150
2511
  // ─── Phase 7: V2 Compaction Hook (best-effort) ───────────────────
2151
2512
  const compactionCtx = hostDomains(context).session
2152
2513
  if (compactionCtx?.hook) {
@@ -2154,6 +2515,10 @@ export const plugin = define({
2154
2515
  // active goals per session, and the store needs no host API (same
2155
2516
  // `.pantheon/goals` directory V1 uses).
2156
2517
  const goalStore = new GoalStore({ dir: '.pantheon/goals' })
2518
+ // P9's record sink, created per registration (in-memory, bounded,
2519
+ // I/O-free) so one setup cannot observe another's records.
2520
+ const p9Sink = createTelemetrySink()
2521
+ p9TelemetrySink = p9Sink
2157
2522
  try {
2158
2523
  // 2.0.16 `SessionHooks` key is `compaction` (the migration doc maps
2159
2524
  // `experimental.session.compacting` → `ctx.session.hook("compaction")`).
@@ -2202,6 +2567,34 @@ export const plugin = define({
2202
2567
  : typeof payload?.session?.id === 'string'
2203
2568
  ? payload.session.id
2204
2569
  : undefined
2570
+
2571
+ // P9 (compaction) shadow observation, on the MEASURED carrier only.
2572
+ // The 2.2.5 compaction payload carries a TOP-LEVEL `sessionID` and
2573
+ // no nested `session` object at all (PROBE-A, 11/11 runs), so the
2574
+ // event is handed to the adapter as-is and it reads
2575
+ // `payload.sessionID` — never `session.id`, which is absent there.
2576
+ // A payload that carries only a nested id therefore produces NO
2577
+ // decision (fail-closed) rather than being keyed by a carrier the
2578
+ // host was never observed to send. This runs BEFORE the pruner and
2579
+ // the context injection below, so `systemPartCount` describes the
2580
+ // host payload and not the blocks Pantheon appends; the adapter
2581
+ // clones what it reads and pushes nothing itself, so the injected
2582
+ // context is unchanged — shadow is the record, nothing else.
2583
+ // Child-session compaction is measured and needs no separate path:
2584
+ // PROBE-G §3.1 fired this hook on a real child 3/3 with the CHILD
2585
+ // sessionID at top level and the same payload shape (7 keys, no
2586
+ // nested `session`, `system` array of 4). Compaction with
2587
+ // `reason:"overflow"` was NOT inducible in 6 error shapes (PROBE-G
2588
+ // §3.2 — the host retried and completed, and the one
2589
+ // failure-recovery compaction was persisted as `reason:"auto"`), so
2590
+ // that path remains unmeasured and is not designed for here.
2591
+ try {
2592
+ evaluateCompactionMemoryPoint({ payload }, (record) => {
2593
+ p9Sink.emit({ ...record, mode: 'shadow' })
2594
+ })
2595
+ } catch {
2596
+ // Observation must never reach the compaction request.
2597
+ }
2205
2598
  const prunerConfig = resolveContextPrunerConfig(context.options)
2206
2599
  const stats = pruneMessages(payload?.messages, prunerConfig, 'compaction')
2207
2600
  logContextPrune(stats, sessionID)
package/src/plugin.ts CHANGED
@@ -22,6 +22,7 @@ import { createGuardPathResolver } from './pantheon/guard-path.ts'
22
22
  import { createReadEnhancer } from './pantheon/hashline/read-enhancer.ts'
23
23
  import { createHashlineEditTool } from './pantheon/hashline/tool.ts'
24
24
  import { createIdleDispatcher } from './pantheon/idle-continuation.ts'
25
+ import { createLocalDecisionTool } from './pantheon/local-decision-tool.ts'
25
26
  import { createPantheonLogger } from './pantheon/logger.ts'
26
27
  import { createModelCommand } from './pantheon/model-command.ts'
27
28
  import { pantheonPluginOnce } from './pantheon/plugin-once.ts'
@@ -369,6 +370,7 @@ const plugin: Plugin = async (input: PluginInput) => {
369
370
  // opencode.db read-only via the single node:sqlite backend. Fully wired.
370
371
  const costCommand = createCostCommand()
371
372
  const modelCommand = createModelCommand()
373
+ const localDecisionTool = createLocalDecisionTool()
372
374
 
373
375
  return {
374
376
  config: async (config: PluginConfig) => {
@@ -436,6 +438,8 @@ const plugin: Plugin = async (input: PluginInput) => {
436
438
  pantheon_cost: costCommand.pantheon_cost,
437
439
  // Deterministic /pantheon-model management of top-level model fields.
438
440
  pantheon_model: modelCommand.pantheon_model,
441
+ // Local advisory routing; execute() requires the host's Zeus agent context.
442
+ pantheon_local_decision: localDecisionTool,
439
443
  },
440
444
  'chat.message': async (hookInput, output) => {
441
445
  await vision.chatMessage(hookInput, output)