pantheon-opencode 1.6.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 (169) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +179 -0
  4. package/README.md +268 -20
  5. package/README.pt-BR.md +34 -11
  6. package/bin/pantheon-init.mjs +301 -32
  7. package/package.json +13 -4
  8. package/plugin.json +1 -1
  9. package/prompts/README.md +58 -0
  10. package/prompts/debug-issue.prompt.md +46 -0
  11. package/prompts/dynamic/agora-generated.txt +38 -0
  12. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  13. package/prompts/focus.prompt.md +42 -0
  14. package/prompts/implement-feature.prompt.md +39 -0
  15. package/prompts/optimize-database.prompt.md +58 -0
  16. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  17. package/prompts/plan-architecture.prompt.md +59 -0
  18. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  19. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  20. package/prompts/semantic-summarize.md +50 -0
  21. package/prompts/sketch.prompt.md +91 -0
  22. package/prompts/subtask.prompt.md +131 -0
  23. package/pyproject.toml +1 -1
  24. package/scripts/build-agents-md.mjs +1 -1
  25. package/scripts/decision-router-budget.mjs +780 -0
  26. package/scripts/decision-router-v2-budget.mjs +218 -0
  27. package/scripts/decision-router-v2-egress.mjs +272 -0
  28. package/scripts/decision-router.mjs +758 -0
  29. package/scripts/docs-check-changelog.mjs +5 -3
  30. package/scripts/doctor.mjs +213 -45
  31. package/scripts/install/agents-md.mjs +2 -1
  32. package/scripts/install/component-selection.mjs +9 -4
  33. package/scripts/install/config-migration.mjs +344 -393
  34. package/scripts/install/config-paths.mjs +15 -0
  35. package/scripts/install/decision-layer-preview.mjs +376 -0
  36. package/scripts/install/decision-router-config.mjs +560 -0
  37. package/scripts/install/health-check.mjs +20 -11
  38. package/scripts/install/interactive.mjs +103 -14
  39. package/scripts/install/interrupt.mjs +4 -3
  40. package/scripts/install/mcp-permissions.mjs +164 -0
  41. package/scripts/install/migrate.mjs +123 -72
  42. package/scripts/install/opencode-version.mjs +31 -13
  43. package/scripts/install/opencode-wildcard.mjs +106 -0
  44. package/scripts/install/opencode.mjs +411 -184
  45. package/scripts/install/plan-artifact.mjs +12 -1
  46. package/scripts/install/plan.mjs +8 -1
  47. package/scripts/install/plugin.mjs +18 -1
  48. package/scripts/install/state.mjs +12 -0
  49. package/scripts/install/strings.mjs +22 -0
  50. package/scripts/install/v2-capabilities.mjs +5 -6
  51. package/scripts/install/venv.mjs +34 -17
  52. package/scripts/mcp_resources.py +11 -9
  53. package/scripts/package-evidence.mjs +1 -0
  54. package/scripts/release-notes.mjs +30 -7
  55. package/scripts/restore.mjs +22 -10
  56. package/scripts/sandbox-env.sh +174 -0
  57. package/scripts/setup-v2-config.mjs +1703 -0
  58. package/scripts/setup.mjs +415 -0
  59. package/scripts/sync-tui.mjs +9 -1
  60. package/scripts/test-opencode-v2-sandbox.sh +448 -157
  61. package/scripts/update-skills-lock.mjs +30 -0
  62. package/scripts/versioning.mjs +41 -5
  63. package/skills-lock.json +10 -10
  64. package/src/agents/aphrodite.md +11 -3
  65. package/src/agents/apollo.md +6 -0
  66. package/src/agents/athena.md +7 -1
  67. package/src/agents/demeter.md +6 -2
  68. package/src/agents/gaia.md +5 -0
  69. package/src/agents/hephaestus.md +7 -2
  70. package/src/agents/hermes.md +14 -13
  71. package/src/agents/iris.md +6 -2
  72. package/src/agents/mnemosyne.md +21 -50
  73. package/src/agents/nyx.md +6 -2
  74. package/src/agents/prometheus.md +5 -1
  75. package/src/agents/talos.md +10 -1
  76. package/src/agents/themis.md +5 -1
  77. package/src/agents/zeus.md +61 -65
  78. package/src/instructions/agent-return-format.instructions.md +1 -1
  79. package/src/instructions/memory-protocol.instructions.md +3 -3
  80. package/src/instructions/test-economy.instructions.md +6 -6
  81. package/src/mcp/eval_store.py +11 -4
  82. package/src/mcp/mcp_resources.py +11 -9
  83. package/src/mcp/memory_mcp.py +293 -150
  84. package/src/mcp/pantheon_vision.py +37 -36
  85. package/src/pantheon/cost-command.ts +30 -133
  86. package/src/pantheon/jev-decision-tool.ts +347 -0
  87. package/src/pantheon/jev-decisions.ts +625 -0
  88. package/src/pantheon/local-decision-agents.ts +170 -0
  89. package/src/pantheon/local-decision-budget.ts +1046 -0
  90. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  91. package/src/pantheon/local-decision-prompt.ts +256 -0
  92. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  93. package/src/pantheon/local-decision-router.ts +225 -0
  94. package/src/pantheon/local-decision-skills.ts +281 -0
  95. package/src/pantheon/local-decision-tool.ts +160 -0
  96. package/src/pantheon/local-decision-turn.ts +101 -0
  97. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  98. package/src/pantheon/local-orchestration.ts +322 -0
  99. package/src/pantheon/model-pricing.ts +1 -536
  100. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  101. package/src/pantheon/v2-decision-budget.ts +456 -0
  102. package/src/pantheon/v2-decision-contracts.ts +300 -0
  103. package/src/pantheon/v2-decision-egress.ts +203 -0
  104. package/src/pantheon/v2-decision-events.ts +180 -0
  105. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  106. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  107. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  108. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  109. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  110. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  111. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  112. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  113. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  114. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  115. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  116. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  117. package/src/pantheon/v2-decision-points.ts +242 -0
  118. package/src/pantheon/v2-decision-policy.ts +166 -0
  119. package/src/pantheon/v2-decision-premises.ts +146 -0
  120. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  121. package/src/pantheon/v2-decision-rank.ts +91 -0
  122. package/src/pantheon/v2-decision-registry.ts +391 -0
  123. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  124. package/src/pantheon/v2-decision-shadow.ts +123 -0
  125. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  126. package/src/pantheon/v2-decision-verify.ts +51 -0
  127. package/src/pantheon/v2-hook-engine.ts +307 -0
  128. package/src/pantheon/v2-native-decisions.ts +365 -0
  129. package/src/pantheon/v2-shell-hooks.ts +66 -2
  130. package/src/pantheon/v2-tools.ts +38 -15
  131. package/src/pantheon/v2-vision.ts +34 -29
  132. package/src/pantheon/vision.ts +43 -10
  133. package/src/plugin-v2.ts +449 -79
  134. package/src/plugin.ts +4 -0
  135. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  136. package/src/plugins/tui/dist/server-v2.d.ts +22 -0
  137. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  138. package/src/plugins/tui/dist/server-v2.js +26 -0
  139. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  140. package/src/plugins/tui/dist/tui-v2.d.ts +54 -51
  141. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  142. package/src/plugins/tui/dist/tui-v2.js +762 -529
  143. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  144. package/src/plugins/tui/dist/tui.js +1 -1
  145. package/src/plugins/tui/index-v2.ts +3 -6
  146. package/src/plugins/tui/package-lock.json +17 -2
  147. package/src/plugins/tui/package.json +6 -3
  148. package/src/plugins/tui/src/context-gauge.ts +59 -0
  149. package/src/plugins/tui/src/cost-data.ts +607 -0
  150. package/src/plugins/tui/src/index-v2.tsx +360 -242
  151. package/src/plugins/tui/src/model-pricing.ts +536 -0
  152. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  153. package/src/plugins/tui/src/server-v2.ts +21 -0
  154. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  155. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  156. package/src/plugins/tui/tsdown.config.ts +34 -5
  157. package/src/routing.yml +72 -13
  158. package/src/skills/README.md +4 -0
  159. package/src/skills/agent-coordination/SKILL.md +0 -3
  160. package/src/skills/artifact-management/SKILL.md +0 -3
  161. package/src/skills/auto-continue/SKILL.md +0 -3
  162. package/src/skills/code-review-checklist/SKILL.md +0 -3
  163. package/src/skills/context-compression/SKILL.md +0 -3
  164. package/src/skills/memory-bank/SKILL.md +6 -28
  165. package/src/skills/session-goal/SKILL.md +0 -3
  166. package/src/skills/simplify/SKILL.md +5 -4
  167. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  168. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  169. package/src/pantheon/memory-context.ts +0 -1017
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Host kill-switch contract for the single decision-egress action.
3
+ *
4
+ * `permission.assert` is a host kill-switch layered on top of the user-level
5
+ * config, never consent itself. The native `pantheon_jev_decide` tool asks it
6
+ * with the logical resource `pantheon-native-decisions://<providerID>/<id>`
7
+ * after its own config/route/ledger gates pass.
8
+ *
9
+ * - Deny is observable: the host throws (`Permission.BlockedError`, whose
10
+ * message is `Permission denied: <action>` unless an evaluate hook supplied a
11
+ * reason) or, defensively, resolves an explicit denial marker.
12
+ * - Allow is NOT observable as a positive value. The measured host contract
13
+ * (`Permission.assert` in the bundled opencode host) resolves `undefined` when
14
+ * every rule admits the request. A resolved non-denial therefore only means
15
+ * "the host did not block it"; the configuration gates remain the authority.
16
+ *
17
+ * The custom action has no default rule, and the measured v2.2.0 canary showed
18
+ * the host is NOT deny-by-default for it: an assertion with no matching rule
19
+ * resolved allow. The config/consent gate is therefore the source of truth for
20
+ * authorization, and an explicit `deny` rule is the kill-switch; the fix for a
21
+ * blocked host is an explicit user permission rule for `decision.egress`, not a
22
+ * bypass in this plugin. This module never retries, downgrades, or reinterprets
23
+ * a denial. Pantheon owns no transport: there is no endpoint to fall back to.
24
+ */
25
+ /**
26
+ * Custom host action, distinct from `webfetch`. It has no default host rule; the
27
+ * measured host resolves an unruled assertion as allow, so only an explicit
28
+ * `deny` rule blocks it.
29
+ */
30
+ export const DECISION_EGRESS_ACTION = 'decision.egress'
31
+
32
+ /** Namespaced prefix that marks a Pantheon-internal assertion, not a real call. */
33
+ export const DECISION_EGRESS_SOURCE_PREFIX = 'pantheon-decision:'
34
+
35
+ export interface DecisionEgressSource {
36
+ type: 'tool'
37
+ id: string
38
+ messageID: string
39
+ }
40
+
41
+ export type PermissionAssert = (input: Record<string, unknown>) => Promise<unknown>
42
+
43
+ export type DecisionEgressAssertion = 'allow' | 'deny'
44
+
45
+ function nonEmptyString(value: unknown): string | undefined {
46
+ if (typeof value !== 'string') return undefined
47
+ const trimmed = value.trim()
48
+ return trimmed.length === 0 ? undefined : trimmed
49
+ }
50
+
51
+ /** Synthetic, stable source accepted by the host for this action. */
52
+ export function decisionPermissionSource(
53
+ sessionID: string,
54
+ messageID: string,
55
+ ): DecisionEgressSource {
56
+ return {
57
+ type: 'tool',
58
+ id: `${DECISION_EGRESS_SOURCE_PREFIX}${sessionID}:${messageID}`,
59
+ messageID,
60
+ }
61
+ }
62
+
63
+ /**
64
+ * The only shape the native tool sends to `permission.assert`. The resource is
65
+ * a logical URI (the host owns any real endpoint), so permission rules can
66
+ * target the native route without exposing a URL.
67
+ */
68
+ export function buildDecisionEgressRequest(input: {
69
+ sessionID: string
70
+ messageID: string
71
+ endpoint: string
72
+ /** Current agent, only when the caller actually knows it. */
73
+ agent?: string | undefined
74
+ }): Record<string, unknown> {
75
+ const request: Record<string, unknown> = {
76
+ sessionID: input.sessionID,
77
+ action: DECISION_EGRESS_ACTION,
78
+ resources: [input.endpoint],
79
+ save: [],
80
+ source: decisionPermissionSource(input.sessionID, input.messageID),
81
+ }
82
+ // The host only uses `agent` to resolve that agent's rules. Emit it only when
83
+ // the caller knows the current agent; never invent a default such as `zeus`.
84
+ const agent = nonEmptyString(input.agent)
85
+ if (agent !== undefined) request.agent = agent
86
+ return request
87
+ }
88
+
89
+ const DENIAL_VALUES = new Set(['deny', 'denied', 'reject', 'rejected', 'blocked'])
90
+
91
+ /**
92
+ * The host words a denial as prose (`Permission denied: decision.egress`), not
93
+ * only as an enum value. Matching it is what makes a returned host denial — as
94
+ * a bare string or inside `message`/`error` — recognizable as deny.
95
+ */
96
+ const DENIAL_PATTERN = /permission\s+denied|not\s+allowed|forbidden|(?<!not\s)blocked/i
97
+
98
+ /**
99
+ * Defensive read of an assertion result.
100
+ *
101
+ * The measured contract signals deny by throwing and allow by resolving
102
+ * `undefined`, so this only recognizes the explicit denial shapes a future or
103
+ * alternative host could return. A resolved non-denial is treated as allow
104
+ * because allow has no positive representation to check for.
105
+ */
106
+ export function isDecisionAssertionDenial(result: unknown): boolean {
107
+ if (result === false) return true
108
+ if (typeof result === 'string') {
109
+ return DENIAL_VALUES.has(result.trim().toLowerCase()) || DENIAL_PATTERN.test(result)
110
+ }
111
+ if (result === null || typeof result !== 'object' || Array.isArray(result)) return false
112
+ const record = result as Record<string, unknown>
113
+ if (record.denied === true || record.allowed === false || record.ok === false) return true
114
+ for (const key of ['effect', 'decision', 'status', 'result']) {
115
+ const value = record[key]
116
+ if (typeof value === 'string' && DENIAL_VALUES.has(value.trim().toLowerCase())) return true
117
+ }
118
+ for (const key of ['message', 'error']) {
119
+ const value = record[key]
120
+ if (typeof value === 'string' && DENIAL_PATTERN.test(value)) return true
121
+ }
122
+ return false
123
+ }
124
+
125
+ /**
126
+ * Ask the host's kill-switch and normalize the outcome.
127
+ *
128
+ * A throw is a deny. A resolved explicit denial marker is a deny. Everything
129
+ * else is `allow` — not because the host promised consent, but because the
130
+ * host's allow path is indistinguishable from `undefined`; the config gates
131
+ * are what actually authorize egress.
132
+ */
133
+ export async function assertDecisionEgressPermission(
134
+ permissionAssert: PermissionAssert,
135
+ request: Record<string, unknown>,
136
+ ): Promise<DecisionEgressAssertion> {
137
+ let result: unknown
138
+ try {
139
+ result = await permissionAssert(request)
140
+ } catch {
141
+ return 'deny'
142
+ }
143
+ return isDecisionAssertionDenial(result) ? 'deny' : 'allow'
144
+ }
@@ -0,0 +1,256 @@
1
+ import { decideLocalForTurn, type TurnDecision } from './local-decision-turn.ts'
2
+ import { isPantheonSkillId } from './pantheon-decision-catalog.ts'
3
+
4
+ // The marker FORMAT stays pinned: prompts that still carry one (saved prompts,
5
+ // copied messages) short-circuit through `hasDecisionRouterMarker`.
6
+ const MARKER_PATTERN = /<!-- pantheon-decision-router:v1\b[^>]*-->/
7
+
8
+ /** The host sends the *string* `"undefined"` for absent prompt fields (F-08). */
9
+ const MEASURED_SENTINELS: ReadonlySet<string> = new Set(['undefined', 'null'])
10
+
11
+ /** Where the observed skill list came from: the prompt array, the draft, or nowhere. */
12
+ export type SkillsSource = 'none' | 'prompt' | 'draft'
13
+
14
+ /**
15
+ * Why the skill outcome is what it is. Tokens only — no content, no count of
16
+ * user text. Every result carries one, so an empty selection is never silent.
17
+ */
18
+ export type PromptApplicationReason =
19
+ | 'invalid.payload'
20
+ | 'request.empty'
21
+ | 'marker.present'
22
+ | 'decision.inactive'
23
+ | 'selection.empty'
24
+ | 'skills.source.prompt'
25
+ | 'skills.source.draft'
26
+ | 'skills.source.absent'
27
+ | 'skills.source.empty'
28
+ | 'skills.source.unstable'
29
+ | 'skills.selection.disjoint'
30
+ | 'skills.synthetic.narrowed'
31
+
32
+ export interface PromptApplicationResult {
33
+ /** Always false since beta.10: the visible marker is suppressed. */
34
+ markerApplied: boolean
35
+ skillsFiltered: boolean
36
+ /** Observable source of the skill list; `none` in the measured host shape (F-08). */
37
+ skillsSource: SkillsSource
38
+ /** Always present: explains the skill outcome, including every empty selection. */
39
+ reason: PromptApplicationReason
40
+ }
41
+
42
+ export interface SkillSourceResolution {
43
+ readonly skillsSource: SkillsSource
44
+ /** Stable identifiers found in the chosen source, deduplicated, in order. */
45
+ readonly skillIds: readonly string[]
46
+ readonly reason: PromptApplicationReason
47
+ }
48
+
49
+ interface SkillNarrowing {
50
+ readonly skillsFiltered: boolean
51
+ readonly skillsSource: SkillsSource
52
+ readonly reason: PromptApplicationReason
53
+ }
54
+
55
+ /** True when the value is the measured placeholder string, not real data. */
56
+ function isMeasuredSentinel(value: unknown): boolean {
57
+ return typeof value === 'string' && MEASURED_SENTINELS.has(value)
58
+ }
59
+
60
+ /** Normalize a measured prompt field: a sentinel string or null means "absent". */
61
+ export function normalizeMeasuredValue(value: unknown): unknown {
62
+ if (value === null || value === undefined) return undefined
63
+ return isMeasuredSentinel(value) ? undefined : value
64
+ }
65
+
66
+ function skillIdentifier(value: unknown): string | undefined {
67
+ if (typeof value === 'string') return value
68
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
69
+ const record = value as { name?: unknown; id?: unknown; slug?: unknown }
70
+ for (const candidate of [record.name, record.id, record.slug]) {
71
+ if (typeof candidate === 'string' && candidate.length > 0) return candidate
72
+ }
73
+ return undefined
74
+ }
75
+
76
+ function identifiers(list: readonly unknown[]): { ids: string[]; unstable: boolean } {
77
+ const ids: string[] = []
78
+ let unstable = false
79
+ for (const item of list) {
80
+ const identifier = skillIdentifier(item)
81
+ if (identifier === undefined) unstable = true
82
+ else if (!ids.includes(identifier)) ids.push(identifier)
83
+ }
84
+ return { ids, unstable }
85
+ }
86
+
87
+ /**
88
+ * Resolve the observed skill list and say where it came from.
89
+ *
90
+ * The prompt list wins when it is a real array. Otherwise the per-turn draft
91
+ * (`ctx.skill.list()`, F-06) is reported as `draft`. The measured host shape
92
+ * carries the sentinel string `"undefined"` (F-08), which is treated as absent.
93
+ *
94
+ * The `draft` branch has **no production caller**: the shipped prompt hook calls
95
+ * `applyTurnDecisionToPrompt(prompt, decision)` without `skillsDraft`, and
96
+ * `ctx.skill.list()` is never read by it. At runtime `skillsSource` is therefore
97
+ * `none` or `prompt` only, and the `draft` source is exercised by tests alone.
98
+ */
99
+ export function resolveSkillSource(
100
+ promptSkills: unknown,
101
+ draftSkills?: unknown,
102
+ ): SkillSourceResolution {
103
+ const promptList = normalizeMeasuredValue(promptSkills)
104
+ const draftList = normalizeMeasuredValue(draftSkills)
105
+
106
+ if (Array.isArray(promptList) && promptList.length > 0) {
107
+ const resolved = identifiers(promptList)
108
+ return {
109
+ skillsSource: 'prompt',
110
+ skillIds: resolved.ids,
111
+ reason: resolved.unstable ? 'skills.source.unstable' : 'skills.source.prompt',
112
+ }
113
+ }
114
+ if (Array.isArray(draftList) && draftList.length > 0) {
115
+ const resolved = identifiers(draftList)
116
+ return {
117
+ skillsSource: 'draft',
118
+ skillIds: resolved.ids,
119
+ reason: resolved.unstable ? 'skills.source.unstable' : 'skills.source.draft',
120
+ }
121
+ }
122
+ return {
123
+ skillsSource: 'none',
124
+ skillIds: [],
125
+ reason: Array.isArray(promptList) ? 'skills.source.empty' : 'skills.source.absent',
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Best-effort narrowing of the host's pre-resolution skill list.
131
+ *
132
+ * Only a real prompt array can be narrowed, and an empty advisory selection
133
+ * must never erase skills the host or user chose. The measured host shape is
134
+ * the sentinel string (F-08), so this is unreachable on the default path: P2 is
135
+ * an empirical no-op there (F-09). The array shape is synthetic — never
136
+ * observed — and its outcome is not a measured effect: PROBE-E measured no
137
+ * effect for any `prompt.skills`/`prompt.agents` mutation (F-24), while C6 as a
138
+ * question is closed for `skill.transform` and `prompt.text`.
139
+ */
140
+ function narrowSkills(
141
+ prompt: Record<string, unknown>,
142
+ selection: readonly string[],
143
+ draftSkills?: unknown,
144
+ ): SkillNarrowing {
145
+ const resolution = resolveSkillSource(prompt.skills, draftSkills)
146
+ if (selection.length === 0) {
147
+ return {
148
+ skillsFiltered: false,
149
+ skillsSource: resolution.skillsSource,
150
+ reason: 'selection.empty',
151
+ }
152
+ }
153
+ if (resolution.skillsSource !== 'prompt') {
154
+ return {
155
+ skillsFiltered: false,
156
+ skillsSource: resolution.skillsSource,
157
+ reason: resolution.reason,
158
+ }
159
+ }
160
+ if (resolution.skillIds.length === 0) {
161
+ return { skillsFiltered: false, skillsSource: 'prompt', reason: 'skills.source.unstable' }
162
+ }
163
+ const selected = new Set(selection)
164
+ const kept = (prompt.skills as readonly unknown[]).filter((item) => {
165
+ const identifier = skillIdentifier(item)
166
+ return identifier !== undefined && selected.has(identifier)
167
+ })
168
+ if (kept.length === 0) {
169
+ return { skillsFiltered: false, skillsSource: 'prompt', reason: 'skills.selection.disjoint' }
170
+ }
171
+ prompt.skills = kept
172
+ return { skillsFiltered: true, skillsSource: 'prompt', reason: 'skills.synthetic.narrowed' }
173
+ }
174
+
175
+ /**
176
+ * Apply an advisory decision to the host prompt payload in place. It never
177
+ * dispatches, changes permissions, or removes a pre-existing host marker.
178
+ * `skillsDraft` is the per-turn draft list; it is observed for `skillsSource`
179
+ * and never applied to admission.
180
+ *
181
+ * The visible `<!-- pantheon-decision-router:v1 … -->` marker is SUPPRESSED
182
+ * (1.6.2-beta.10): the host chat rendered the HTML comment to the user. The
183
+ * router itself keeps running — shadow observation, telemetry and the
184
+ * synthetic-shape skill guard all stay — and measured evidence showed the
185
+ * marker was the only live prompt mutation while every measured prompt
186
+ * mutation was a no-op (F-24, F-08/F-09), so nothing behavioral is lost.
187
+ */
188
+ export function applyTurnDecisionToPrompt(
189
+ prompt: unknown,
190
+ decision: TurnDecision | null,
191
+ skillsDraft?: unknown,
192
+ ): PromptApplicationResult {
193
+ const invalid: PromptApplicationResult = {
194
+ markerApplied: false,
195
+ skillsFiltered: false,
196
+ skillsSource: 'none',
197
+ reason: 'invalid.payload',
198
+ }
199
+ if (prompt === null || typeof prompt !== 'object' || Array.isArray(prompt)) return invalid
200
+ if (decision === null || !decision.active) return { ...invalid, reason: 'decision.inactive' }
201
+ const target = prompt as Record<string, unknown>
202
+ const narrowing = narrowSkills(
203
+ target,
204
+ decision.skillIds.filter((id) => isPantheonSkillId(id)),
205
+ skillsDraft,
206
+ )
207
+ return {
208
+ markerApplied: false,
209
+ skillsFiltered: narrowing.skillsFiltered,
210
+ skillsSource: narrowing.skillsSource,
211
+ reason: narrowing.reason,
212
+ }
213
+ }
214
+
215
+ /** True when the prompt already carries a decision-router marker. */
216
+ export function hasDecisionRouterMarker(text: unknown): boolean {
217
+ return typeof text === 'string' && MARKER_PATTERN.test(text)
218
+ }
219
+
220
+ /** Apply the local advisory selector while keeping provider egress out of this route. */
221
+ export async function applyDecisionRouterToPrompt(
222
+ admission: unknown,
223
+ requestText?: string,
224
+ ): Promise<PromptApplicationResult> {
225
+ const none = (reason: PromptApplicationReason): PromptApplicationResult => ({
226
+ markerApplied: false,
227
+ skillsFiltered: false,
228
+ skillsSource: 'none',
229
+ reason,
230
+ })
231
+ if (admission === null || typeof admission !== 'object' || Array.isArray(admission)) {
232
+ return none('invalid.payload')
233
+ }
234
+ const event = admission as { sessionID?: unknown; messageID?: unknown; prompt?: unknown }
235
+ const prompt = event.prompt
236
+ if (prompt === null || typeof prompt !== 'object' || Array.isArray(prompt)) {
237
+ return none('invalid.payload')
238
+ }
239
+ const promptText = (prompt as { text?: unknown }).text
240
+ if (typeof promptText !== 'string' || promptText.trim().length === 0) {
241
+ return none('request.empty')
242
+ }
243
+ const text =
244
+ typeof requestText === 'string' && requestText.trim().length > 0 ? requestText : promptText
245
+ if (hasDecisionRouterMarker(text)) return none('marker.present')
246
+ try {
247
+ const decision = await decideLocalForTurn({
248
+ request: text,
249
+ sessionID: event.sessionID,
250
+ messageID: event.messageID,
251
+ })
252
+ return applyTurnDecisionToPrompt(prompt, decision)
253
+ } catch {
254
+ return none('invalid.payload')
255
+ }
256
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Private provider matrix: fixed provider/model rows and their ledger
3
+ * accounting mapping. No network I/O, no endpoints, no credentials — the
4
+ * direct-fetch adapter fields were removed with the legacy fetch runner; the
5
+ * only egress transport is the host's native Decisions layer, whose provider
6
+ * and credentials the host owns. Pantheon uses this matrix for the config
7
+ * candidate model IDs and ledger accounting names only.
8
+ */
9
+ import {
10
+ DECISION_PROVIDER_BUDGET_MAPPING,
11
+ DECISION_ROUTER_MODELS,
12
+ } from '../../scripts/install/decision-router-config.mjs'
13
+ import type { BudgetProvider } from './local-decision-budget.ts'
14
+
15
+ export type DecisionProviderId =
16
+ | 'openai-decisions'
17
+ | 'typesafe-jev'
18
+ | 'opencode-console-jev'
19
+ | 'opencode-console-jev-free'
20
+
21
+ /**
22
+ * Single provider matrix. Model and accounting IDs come from the canonical
23
+ * config so the route resolver and the ledger can never drift silently.
24
+ */
25
+ export const DECISION_PROVIDER_ADAPTERS: Readonly<
26
+ Record<DecisionProviderId, { model: string; accountingProvider: BudgetProvider }>
27
+ > = Object.freeze(
28
+ Object.fromEntries(
29
+ (Object.keys(DECISION_ROUTER_MODELS) as DecisionProviderId[]).map((provider) => {
30
+ const model = DECISION_ROUTER_MODELS[provider]?.[0]
31
+ if (model === undefined) throw new Error(`Missing decision provider model: ${provider}`)
32
+ return [
33
+ provider,
34
+ Object.freeze({
35
+ model,
36
+ accountingProvider: DECISION_PROVIDER_BUDGET_MAPPING[provider] as BudgetProvider,
37
+ }),
38
+ ]
39
+ }),
40
+ ) as Record<
41
+ DecisionProviderId,
42
+ { readonly model: string; readonly accountingProvider: BudgetProvider }
43
+ >,
44
+ )
@@ -0,0 +1,225 @@
1
+ import { PANTHEON_AGENTS } from './v2-delegation-enforce.ts'
2
+
3
+ /** Explicit opt-in for the local advisory API. Unset and any value except `1` disable it. */
4
+ export const LOCAL_DECISION_ROUTER_ENV = 'PANTHEON_LOCAL_DECISION_ROUTER'
5
+ export const LOCAL_DECISION_ROUTER_POLICY_VERSION = 'local-decision-router/v1'
6
+
7
+ export const LOCAL_DECISION_COMPLEXITY_DIMENSIONS = [
8
+ 'boundedness',
9
+ 'reversibility',
10
+ 'dependencies',
11
+ 'uncertainty',
12
+ 'verification',
13
+ ] as const
14
+
15
+ export type LocalDecisionComplexityDimensions = Readonly<
16
+ Record<(typeof LOCAL_DECISION_COMPLEXITY_DIMENSIONS)[number], 0 | 1 | 2>
17
+ >
18
+
19
+ export type LocalDecisionGateStatus =
20
+ | 'none'
21
+ | 'review_required'
22
+ | 'human_approval_required'
23
+ | 'unresolved'
24
+
25
+ /** Versioned structured input; domain entries are exact canonical specialist IDs. */
26
+ export interface LocalDecisionInput {
27
+ schemaVersion: 1
28
+ domains: readonly string[]
29
+ complexity: LocalDecisionComplexityDimensions
30
+ gateStatus: LocalDecisionGateStatus
31
+ }
32
+
33
+ export type LocalDecisionRouteReasonCode =
34
+ | 'DISABLED'
35
+ | 'INVALID_INPUT'
36
+ | 'NO_DOMAIN'
37
+ | 'AMBIGUOUS_DOMAIN'
38
+ | 'UNKNOWN_DOMAIN'
39
+ | 'UNROUTABLE_ROLE'
40
+ | 'CANONICAL_ROLE'
41
+
42
+ export type LocalDecisionComplexityReasonCode =
43
+ | 'DISABLED'
44
+ | 'INVALID_INPUT'
45
+ | 'INVALID_COMPLEXITY'
46
+ | 'CLASSIFIED_FROM_STRUCTURED_DIMENSIONS'
47
+
48
+ export interface LocalDecisionRecommendation {
49
+ schemaVersion: 1
50
+ policyVersion: typeof LOCAL_DECISION_ROUTER_POLICY_VERSION
51
+ decision: 'route' | 'abstain'
52
+ /** Non-null only when `decision` is `route`, and always a canonical specialist ID. */
53
+ agent: string | null
54
+ reasonCode: LocalDecisionRouteReasonCode
55
+ complexity: {
56
+ label: 'low' | 'medium' | 'high' | 'abstain'
57
+ reasonCode: LocalDecisionComplexityReasonCode
58
+ }
59
+ /** Security/authorization status is carried separately and never changes complexity. */
60
+ gateStatus: LocalDecisionGateStatus
61
+ }
62
+
63
+ const ROUTABLE_AGENTS: ReadonlySet<string> = new Set(
64
+ [...PANTHEON_AGENTS].filter((agent) => agent !== 'zeus'),
65
+ )
66
+
67
+ const GATE_STATUSES: ReadonlySet<string> = new Set([
68
+ 'none',
69
+ 'review_required',
70
+ 'human_approval_required',
71
+ 'unresolved',
72
+ ])
73
+
74
+ const INPUT_KEYS = ['complexity', 'domains', 'gateStatus', 'schemaVersion']
75
+ const COMPLEXITY_KEYS = [...LOCAL_DECISION_COMPLEXITY_DIMENSIONS].sort()
76
+
77
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
78
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
79
+ const prototype = Object.getPrototypeOf(value)
80
+ return prototype === Object.prototype || prototype === null
81
+ }
82
+
83
+ function hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
84
+ const actualKeys = Object.keys(value).sort()
85
+ const expectedKeys = [...keys].sort()
86
+ return (
87
+ actualKeys.length === expectedKeys.length &&
88
+ actualKeys.every((key, index) => key === expectedKeys[index])
89
+ )
90
+ }
91
+
92
+ function isValidInputShape(input: unknown): input is LocalDecisionInput {
93
+ if (!isPlainRecord(input) || !hasExactKeys(input, INPUT_KEYS)) return false
94
+ if (
95
+ input.schemaVersion !== 1 ||
96
+ typeof input.gateStatus !== 'string' ||
97
+ !GATE_STATUSES.has(input.gateStatus)
98
+ ) {
99
+ return false
100
+ }
101
+ if (
102
+ !Array.isArray(input.domains) ||
103
+ !input.domains.every((domain) => typeof domain === 'string')
104
+ ) {
105
+ return false
106
+ }
107
+ if (!isPlainRecord(input.complexity) || !hasExactKeys(input.complexity, COMPLEXITY_KEYS)) {
108
+ return false
109
+ }
110
+ return classifyLocalDecisionComplexity(input.complexity).label !== 'abstain'
111
+ }
112
+
113
+ export function classifyLocalDecisionComplexity(
114
+ value: unknown,
115
+ ): LocalDecisionRecommendation['complexity'] {
116
+ if (!isPlainRecord(value) || !hasExactKeys(value, COMPLEXITY_KEYS)) {
117
+ return { label: 'abstain', reasonCode: 'INVALID_COMPLEXITY' }
118
+ }
119
+
120
+ const scores = LOCAL_DECISION_COMPLEXITY_DIMENSIONS.map((dimension) => value[dimension])
121
+ if (
122
+ !scores.every(
123
+ (score) => typeof score === 'number' && Number.isInteger(score) && score >= 0 && score <= 2,
124
+ )
125
+ ) {
126
+ return { label: 'abstain', reasonCode: 'INVALID_COMPLEXITY' }
127
+ }
128
+
129
+ const label = scores.includes(2) ? 'high' : scores.includes(1) ? 'medium' : 'low'
130
+ return { label, reasonCode: 'CLASSIFIED_FROM_STRUCTURED_DIMENSIONS' }
131
+ }
132
+
133
+ function createAbstention(
134
+ reasonCode: LocalDecisionRouteReasonCode,
135
+ complexityReasonCode: LocalDecisionComplexityReasonCode,
136
+ gateStatus: LocalDecisionGateStatus = 'unresolved',
137
+ ): LocalDecisionRecommendation {
138
+ return {
139
+ schemaVersion: 1,
140
+ policyVersion: LOCAL_DECISION_ROUTER_POLICY_VERSION,
141
+ decision: 'abstain',
142
+ agent: null,
143
+ reasonCode,
144
+ complexity: { label: 'abstain', reasonCode: complexityReasonCode },
145
+ gateStatus,
146
+ }
147
+ }
148
+
149
+ function evaluateEnabledInput(input: unknown): LocalDecisionRecommendation {
150
+ if (!isValidInputShape(input)) {
151
+ const gateStatus =
152
+ isPlainRecord(input) &&
153
+ typeof input.gateStatus === 'string' &&
154
+ GATE_STATUSES.has(input.gateStatus)
155
+ ? (input.gateStatus as LocalDecisionGateStatus)
156
+ : 'unresolved'
157
+ const complexity = isPlainRecord(input)
158
+ ? classifyLocalDecisionComplexity(input.complexity)
159
+ : { label: 'abstain' as const, reasonCode: 'INVALID_COMPLEXITY' as const }
160
+ const complexityReasonCode =
161
+ complexity.reasonCode === 'INVALID_COMPLEXITY' ? 'INVALID_COMPLEXITY' : 'INVALID_INPUT'
162
+ return createAbstention('INVALID_INPUT', complexityReasonCode, gateStatus)
163
+ }
164
+
165
+ const gateStatus = input.gateStatus
166
+ const complexity = classifyLocalDecisionComplexity(input.complexity)
167
+
168
+ if (input.domains.length === 0) {
169
+ return { ...createAbstention('NO_DOMAIN', complexity.reasonCode, gateStatus), complexity }
170
+ }
171
+ if (input.domains.length !== 1) {
172
+ return {
173
+ ...createAbstention('AMBIGUOUS_DOMAIN', complexity.reasonCode, gateStatus),
174
+ complexity,
175
+ }
176
+ }
177
+
178
+ const [domain] = input.domains
179
+ if (typeof domain !== 'string') {
180
+ return createAbstention('INVALID_INPUT', complexity.reasonCode, gateStatus)
181
+ }
182
+ if (domain === 'zeus') {
183
+ return {
184
+ ...createAbstention('UNROUTABLE_ROLE', complexity.reasonCode, gateStatus),
185
+ complexity,
186
+ }
187
+ }
188
+ if (!ROUTABLE_AGENTS.has(domain)) {
189
+ return {
190
+ ...createAbstention('UNKNOWN_DOMAIN', complexity.reasonCode, gateStatus),
191
+ complexity,
192
+ }
193
+ }
194
+
195
+ return {
196
+ schemaVersion: 1,
197
+ policyVersion: LOCAL_DECISION_ROUTER_POLICY_VERSION,
198
+ decision: 'route',
199
+ agent: domain,
200
+ reasonCode: 'CANONICAL_ROLE',
201
+ complexity,
202
+ gateStatus,
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Return a local advisory recommendation only when explicitly enabled.
208
+ *
209
+ * This function never calls a provider, dispatches an agent, or changes permissions.
210
+ * The default-off environment gate intentionally leaves native host dispatch untouched.
211
+ */
212
+ export function recommendLocalDecision(
213
+ input: LocalDecisionInput,
214
+ env: Readonly<Record<string, string | undefined>> = process.env,
215
+ ): LocalDecisionRecommendation {
216
+ try {
217
+ if (env[LOCAL_DECISION_ROUTER_ENV] !== '1') {
218
+ return createAbstention('DISABLED', 'DISABLED')
219
+ }
220
+ return evaluateEnabledInput(input)
221
+ } catch {
222
+ // Malformed accessors and injected env are invalid data; never route on failure.
223
+ return createAbstention('INVALID_INPUT', 'INVALID_INPUT')
224
+ }
225
+ }