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
@@ -0,0 +1,625 @@
1
+ /**
2
+ * Native Jev Decisions selection, preparation, and consumption.
3
+ *
4
+ * This is the production half of the offline scaffold in
5
+ * `v2-native-decisions.ts`: it selects a decision-capable model route from the
6
+ * user-level decision-router configuration, prepares a bounded typed request,
7
+ * and consumes a host response as non-authoritative advice. It performs no
8
+ * I/O of its own: no fetch, no credentials, no transport — egress happens only
9
+ * when the caller invokes the host's native `experimental.generate.decisions`
10
+ * API with a request this module prepared, behind the consent, budget, and
11
+ * permission gates wired in `jev-decision-tool.ts`.
12
+ *
13
+ * The config provider namespace is Pantheon's own (the installer's provider
14
+ * matrix); the host model catalog uses the host's provider IDs. The mapping is
15
+ * a frozen table here — the single place the two namespaces meet. Direct
16
+ * OpenAI has no native Decisions route and is never mapped.
17
+ */
18
+
19
+ import type { UserDecisionRouterCandidate } from '../../scripts/install/decision-router-config.mjs'
20
+ import type { BudgetProvider } from './local-decision-budget.ts'
21
+ import {
22
+ DECISION_PROVIDER_ADAPTERS,
23
+ type DecisionProviderId,
24
+ } from './local-decision-provider-matrix.ts'
25
+ import { selectPantheonSkills } from './local-decision-skills.ts'
26
+ import { PANTHEON_AGENT_CATALOG, PANTHEON_SKILL_CATALOG } from './pantheon-decision-catalog.ts'
27
+ import {
28
+ NATIVE_DECISION_MAX_PROMPT_LENGTH,
29
+ type NativeDecisionRequest,
30
+ type ResolvedNativeDecisionRoute,
31
+ resolveNativeDecisionRoute,
32
+ } from './v2-native-decisions.ts'
33
+
34
+ /** Catalog entry shape the route resolver needs from the host model list. */
35
+ export type JevDecisionCatalogEntry = Parameters<typeof resolveNativeDecisionRoute>[2][number]
36
+
37
+ /** Config-level providers that have a native host Decisions route. */
38
+ export type NativeJevProviderId = Extract<
39
+ DecisionProviderId,
40
+ 'typesafe-jev' | 'opencode-console-jev' | 'opencode-console-jev-free'
41
+ >
42
+
43
+ /**
44
+ * Config provider → host `providerID`. `openai-decisions` is deliberately
45
+ * absent: direct OpenAI Decisions are not a native route, and an OpenRouter
46
+ * Jev route is reachable only as a host-configured model, not through this
47
+ * matrix (the installer's candidate list has no `openrouter` provider).
48
+ */
49
+ export const NATIVE_JEV_HOST_PROVIDERS = Object.freeze({
50
+ 'typesafe-jev': 'typesafe-ai',
51
+ 'opencode-console-jev': 'opencode',
52
+ 'opencode-console-jev-free': 'opencode',
53
+ } satisfies Record<NativeJevProviderId, string>)
54
+
55
+ export function isNativeJevProvider(provider: unknown): provider is NativeJevProviderId {
56
+ return typeof provider === 'string' && Object.hasOwn(NATIVE_JEV_HOST_PROVIDERS, provider)
57
+ }
58
+
59
+ export type NativeJevRouteFailure = 'NO_ELIGIBLE_CANDIDATE' | 'ROUTE_UNRESOLVED'
60
+
61
+ export interface NativeJevRouteSelection {
62
+ readonly route: ResolvedNativeDecisionRoute
63
+ readonly provider: NativeJevProviderId
64
+ readonly accountingProvider: BudgetProvider
65
+ readonly model: string
66
+ }
67
+
68
+ export type NativeJevRouteResolution =
69
+ | { readonly ok: true; readonly selection: NativeJevRouteSelection }
70
+ | { readonly ok: false; readonly reasonCode: NativeJevRouteFailure }
71
+
72
+ /**
73
+ * Keep only candidates that both map to a native route and pass the caller's
74
+ * admission check. Pure: the admission check is injected so tests can run
75
+ * without a ledger; the production caller passes `ledger.canReserve(...)`.
76
+ */
77
+ export function filterNativeCapValidCandidates(
78
+ candidates: readonly UserDecisionRouterCandidate[],
79
+ checkAdmission: (provider: BudgetProvider, model: string) => boolean,
80
+ ): UserDecisionRouterCandidate[] {
81
+ const valid: UserDecisionRouterCandidate[] = []
82
+ for (const candidate of candidates) {
83
+ if (!isNativeJevProvider(candidate.provider)) continue
84
+ const adapter = DECISION_PROVIDER_ADAPTERS[candidate.provider]
85
+ if (!checkAdmission(adapter.accountingProvider, candidate.model)) continue
86
+ valid.push(candidate)
87
+ }
88
+ return valid
89
+ }
90
+
91
+ function readEnabledCandidates(config: unknown): UserDecisionRouterCandidate[] {
92
+ if (config === null || typeof config !== 'object' || Array.isArray(config)) return []
93
+ const value = (config as { enabled_candidates?: unknown }).enabled_candidates
94
+ if (!Array.isArray(value)) return []
95
+ return value.filter(
96
+ (candidate): candidate is UserDecisionRouterCandidate =>
97
+ candidate !== null &&
98
+ typeof candidate === 'object' &&
99
+ !Array.isArray(candidate) &&
100
+ typeof (candidate as { provider?: unknown }).provider === 'string' &&
101
+ typeof (candidate as { model?: unknown }).model === 'string',
102
+ )
103
+ }
104
+
105
+ /**
106
+ * Resolve the one explicit-or-auto native route for a migrated user config.
107
+ *
108
+ * The legacy `resolveUserDecisionRouterCandidate` policy only admits
109
+ * remotely-eligible direct-fetch providers, so it can never select the Console
110
+ * routes; this resolver repeats its shape (explicit wins, auto requires
111
+ * exactly one cap-valid candidate) over the native-eligible candidate set.
112
+ * A selection that resolves to a provider without a native route (explicit
113
+ * `openai-decisions`) is a refusal, never a substitution.
114
+ */
115
+ export function resolveNativeJevRoute(
116
+ config: unknown,
117
+ catalog: readonly JevDecisionCatalogEntry[],
118
+ checkAdmission: (provider: BudgetProvider, model: string) => boolean,
119
+ ): NativeJevRouteResolution {
120
+ const record =
121
+ config !== null && typeof config === 'object' && !Array.isArray(config)
122
+ ? (config as {
123
+ enabled?: unknown
124
+ egress_consent?: unknown
125
+ selection?: unknown
126
+ })
127
+ : undefined
128
+ if (record?.enabled !== true || record.egress_consent !== true) {
129
+ return { ok: false, reasonCode: 'NO_ELIGIBLE_CANDIDATE' }
130
+ }
131
+ const selection =
132
+ record.selection !== null &&
133
+ typeof record.selection === 'object' &&
134
+ !Array.isArray(record.selection)
135
+ ? (record.selection as { mode?: unknown; provider?: unknown; model?: unknown })
136
+ : undefined
137
+ if (typeof selection?.mode !== 'string' || selection.mode === 'local') {
138
+ return { ok: false, reasonCode: 'NO_ELIGIBLE_CANDIDATE' }
139
+ }
140
+
141
+ const capValid = filterNativeCapValidCandidates(readEnabledCandidates(config), checkAdmission)
142
+ const selected =
143
+ selection.mode === 'explicit'
144
+ ? capValid.find(
145
+ (candidate) =>
146
+ candidate.provider === selection.provider && candidate.model === selection.model,
147
+ )
148
+ : capValid.length === 1
149
+ ? capValid[0]
150
+ : undefined
151
+ if (selected === undefined || !isNativeJevProvider(selected.provider)) {
152
+ return { ok: false, reasonCode: 'NO_ELIGIBLE_CANDIDATE' }
153
+ }
154
+
155
+ const hostProvider = NATIVE_JEV_HOST_PROVIDERS[selected.provider]
156
+ const resolution = resolveNativeDecisionRoute(
157
+ { providerID: hostProvider, id: selected.model },
158
+ undefined,
159
+ catalog,
160
+ )
161
+ if (!resolution.ok) return { ok: false, reasonCode: 'ROUTE_UNRESOLVED' }
162
+ return {
163
+ ok: true,
164
+ selection: {
165
+ route: resolution.route,
166
+ provider: selected.provider,
167
+ accountingProvider: DECISION_PROVIDER_ADAPTERS[selected.provider].accountingProvider,
168
+ model: selected.model,
169
+ },
170
+ }
171
+ }
172
+
173
+ // ─── Request preparation ────────────────────────────────────────────────
174
+
175
+ export const JEV_DECISION_MAX_QUESTIONS = 4
176
+ /** Wide enough for the full skill catalog (20) plus `none` in preset mode. */
177
+ export const JEV_DECISION_MAX_CHOICES = 24
178
+ export const JEV_DECISION_MIN_CHOICES = 2
179
+ export const JEV_DECISION_MAX_SCORE_LEVELS = 10
180
+ export const JEV_DECISION_MIN_SCORE_LEVELS = 2
181
+ export const JEV_DECISION_MAX_NAME_LENGTH = 64
182
+ export const JEV_DECISION_MAX_INSTRUCTIONS_LENGTH = 2_000
183
+ export const JEV_DECISION_MAX_DESCRIPTION_LENGTH = 500
184
+ const QUESTION_NAME_PATTERN = /^[a-z0-9_.-]{1,64}$/i
185
+
186
+ export type JevDecisionQuestionInput = {
187
+ readonly type: unknown
188
+ readonly name: unknown
189
+ readonly instructions: unknown
190
+ readonly choices?: unknown
191
+ readonly levels?: unknown
192
+ }
193
+
194
+ export type JevDecisionPreparationFailure = 'STATE_INVALID' | 'QUESTIONS_INVALID' | 'PRESET_INVALID'
195
+
196
+ export type JevDecisionPreparation =
197
+ | { readonly ok: true; readonly request: NativeDecisionRequest }
198
+ | { readonly ok: false; readonly reasonCode: JevDecisionPreparationFailure }
199
+
200
+ function isBoundedNonBlankString(value: unknown, max: number): value is string {
201
+ return typeof value === 'string' && value.trim().length > 0 && value.length <= max
202
+ }
203
+
204
+ function readBoundedDescription(value: unknown): string | undefined {
205
+ if (value === undefined) return undefined
206
+ return typeof value === 'string' && value.length > 0 && value.length <= 500 ? value : undefined
207
+ }
208
+
209
+ function readChoiceQuestion(
210
+ question: JevDecisionQuestionInput,
211
+ ): NativeDecisionRequest['questions'][number] | null {
212
+ if (!Array.isArray(question.choices)) return null
213
+ if (
214
+ question.choices.length < JEV_DECISION_MIN_CHOICES ||
215
+ question.choices.length > JEV_DECISION_MAX_CHOICES
216
+ ) {
217
+ return null
218
+ }
219
+ const seen = new Set<string>()
220
+ const choices: Array<{ value: string; description?: string }> = []
221
+ for (const raw of question.choices) {
222
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
223
+ const record = raw as { value?: unknown; description?: unknown }
224
+ if (!isBoundedNonBlankString(record.value, JEV_DECISION_MAX_NAME_LENGTH)) return null
225
+ if (seen.has(record.value)) return null
226
+ seen.add(record.value)
227
+ const description = readBoundedDescription(record.description)
228
+ choices.push(
229
+ description === undefined ? { value: record.value } : { value: record.value, description },
230
+ )
231
+ }
232
+ return {
233
+ type: 'choice',
234
+ name: question.name as string,
235
+ instructions: question.instructions as string,
236
+ choices,
237
+ }
238
+ }
239
+
240
+ function readScoreQuestion(
241
+ question: JevDecisionQuestionInput,
242
+ ): NativeDecisionRequest['questions'][number] | null {
243
+ if (!Array.isArray(question.levels)) return null
244
+ if (
245
+ question.levels.length < JEV_DECISION_MIN_SCORE_LEVELS ||
246
+ question.levels.length > JEV_DECISION_MAX_SCORE_LEVELS
247
+ ) {
248
+ return null
249
+ }
250
+ const seen = new Set<string>()
251
+ const levels: Array<{ label: string; description?: string }> = []
252
+ for (const raw of question.levels) {
253
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
254
+ const record = raw as { label?: unknown; description?: unknown }
255
+ if (!isBoundedNonBlankString(record.label, JEV_DECISION_MAX_NAME_LENGTH)) return null
256
+ if (seen.has(record.label)) return null
257
+ seen.add(record.label)
258
+ const description = readBoundedDescription(record.description)
259
+ levels.push(
260
+ description === undefined ? { label: record.label } : { label: record.label, description },
261
+ )
262
+ }
263
+ return {
264
+ type: 'score',
265
+ name: question.name as string,
266
+ instructions: question.instructions as string,
267
+ levels,
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Build one bounded native Decisions request from the tool input.
273
+ *
274
+ * The state is the only input part, carried verbatim as a single text part —
275
+ * the same payload rule as the hook scaffold: no files, no history, no system
276
+ * instructions, no memory. The host schema allows JSON and file parts; this
277
+ * preparer never produces them.
278
+ */
279
+ export function prepareJevDecisionRequest(
280
+ route: ResolvedNativeDecisionRoute,
281
+ input: { readonly state?: unknown; readonly questions?: unknown },
282
+ ): JevDecisionPreparation {
283
+ const state = input.state
284
+ if (!isBoundedNonBlankString(state, NATIVE_DECISION_MAX_PROMPT_LENGTH)) {
285
+ return { ok: false, reasonCode: 'STATE_INVALID' }
286
+ }
287
+ const rawQuestions = input.questions
288
+ if (!Array.isArray(rawQuestions)) return { ok: false, reasonCode: 'QUESTIONS_INVALID' }
289
+ if (rawQuestions.length < 1 || rawQuestions.length > JEV_DECISION_MAX_QUESTIONS) {
290
+ return { ok: false, reasonCode: 'QUESTIONS_INVALID' }
291
+ }
292
+
293
+ const names = new Set<string>()
294
+ const questions: NativeDecisionRequest['questions'][number][] = []
295
+ for (const raw of rawQuestions) {
296
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
297
+ return { ok: false, reasonCode: 'QUESTIONS_INVALID' }
298
+ }
299
+ const question = raw as JevDecisionQuestionInput
300
+ if (!isBoundedNonBlankString(question.name, JEV_DECISION_MAX_NAME_LENGTH)) {
301
+ return { ok: false, reasonCode: 'QUESTIONS_INVALID' }
302
+ }
303
+ if (!QUESTION_NAME_PATTERN.test(question.name) || names.has(question.name)) {
304
+ return { ok: false, reasonCode: 'QUESTIONS_INVALID' }
305
+ }
306
+ if (!isBoundedNonBlankString(question.instructions, JEV_DECISION_MAX_INSTRUCTIONS_LENGTH)) {
307
+ return { ok: false, reasonCode: 'QUESTIONS_INVALID' }
308
+ }
309
+ names.add(question.name)
310
+
311
+ if (question.type === 'choice') {
312
+ const built = readChoiceQuestion(question)
313
+ if (built === null) return { ok: false, reasonCode: 'QUESTIONS_INVALID' }
314
+ questions.push(built)
315
+ } else if (question.type === 'score') {
316
+ const built = readScoreQuestion(question)
317
+ if (built === null) return { ok: false, reasonCode: 'QUESTIONS_INVALID' }
318
+ questions.push(built)
319
+ } else if (question.type === 'predicate') {
320
+ if (question.choices !== undefined || question.levels !== undefined) {
321
+ return { ok: false, reasonCode: 'QUESTIONS_INVALID' }
322
+ }
323
+ questions.push({
324
+ type: 'predicate',
325
+ name: question.name,
326
+ instructions: question.instructions,
327
+ })
328
+ } else {
329
+ return { ok: false, reasonCode: 'QUESTIONS_INVALID' }
330
+ }
331
+ }
332
+
333
+ const request = {
334
+ model: route.model,
335
+ input: [{ type: 'text', text: state }],
336
+ questions,
337
+ } satisfies NativeDecisionRequest
338
+ return { ok: true, request: Object.freeze(request) }
339
+ }
340
+
341
+ // ─── Preset requests: skill stacking and delegation ─────────────────────
342
+
343
+ /**
344
+ * Ready-made single-question requests over Pantheon's own catalog.
345
+ *
346
+ * The point is speed with breadth: a free deterministic local prefilter picks
347
+ * the skill shortlist when it can (≤ 4 skills), and Jev decides over it in one
348
+ * typed call; when nothing pre-matches, the whole skill catalog is offered
349
+ * instead. Both presets always include `none` — advice may abstain, and
350
+ * `effect` stays `none` no matter what comes back.
351
+ */
352
+ export type JevDecisionPreset = 'skills' | 'delegation'
353
+
354
+ export const JEV_DECISION_PRESETS = Object.freeze(['skills', 'delegation'] as const)
355
+
356
+ export function isJevDecisionPreset(value: unknown): value is JevDecisionPreset {
357
+ return typeof value === 'string' && (JEV_DECISION_PRESETS as readonly string[]).includes(value)
358
+ }
359
+
360
+ /** Every canonical specialist except the orchestrator itself. */
361
+ const SPECIALIST_CHOICES: ReadonlyArray<{ value: string }> = Object.freeze(
362
+ PANTHEON_AGENT_CATALOG.filter((agent) => agent.id !== 'zeus').map((agent) => ({
363
+ value: agent.id,
364
+ })),
365
+ )
366
+
367
+ const SKILL_DESCRIPTIONS = new Map(
368
+ PANTHEON_SKILL_CATALOG.map((entry) => [entry.id, entry.description]),
369
+ )
370
+
371
+ function choiceList(
372
+ values: readonly string[],
373
+ descriptions: ReadonlyMap<string, string | undefined> = SKILL_DESCRIPTIONS,
374
+ ): Array<{ value: string; description?: string }> {
375
+ return values.map((value) => {
376
+ const description = descriptions.get(value)
377
+ return description
378
+ ? { value, description: description.slice(0, JEV_DECISION_MAX_DESCRIPTION_LENGTH) }
379
+ : { value }
380
+ })
381
+ }
382
+
383
+ /** One installed skill the host reports (`ctx.skill.list()`), bounded. */
384
+ export interface JevHostSkill {
385
+ readonly id: string
386
+ readonly description?: string
387
+ }
388
+
389
+ const CATALOG_SKILL_IDS = PANTHEON_SKILL_CATALOG.map((entry) => entry.id)
390
+
391
+ /**
392
+ * Merge host-discovered skills behind the catalog pool: the local prefilter
393
+ * (or the whole catalog, when nothing pre-matches) always comes first, then
394
+ * every installed skill the host reports that is not already present, until
395
+ * the choice bound minus `none` is reached. This is what makes the preset
396
+ * open: anything installed into the host's skill directories — Pantheon's
397
+ * own or third-party Agent Skills — becomes decidable without Pantheon
398
+ * knowing about it at build time. Trusting an install is the user's manual
399
+ * act; this merger only decides among what is already trusted.
400
+ */
401
+ export function mergeHostSkills(
402
+ pool: readonly string[],
403
+ hostSkills: readonly JevHostSkill[] | undefined,
404
+ descriptions: Map<string, string | undefined>,
405
+ ): Array<{ value: string; description?: string }> {
406
+ const merged = [...pool]
407
+ const seen = new Set(merged)
408
+ const bound = JEV_DECISION_MAX_CHOICES - 1
409
+ if (hostSkills !== undefined) {
410
+ for (const skill of hostSkills) {
411
+ if (merged.length >= bound) break
412
+ if (
413
+ skill === null ||
414
+ typeof skill !== 'object' ||
415
+ typeof skill.id !== 'string' ||
416
+ skill.id.length === 0 ||
417
+ skill.id.length > JEV_DECISION_MAX_NAME_LENGTH ||
418
+ skill.id.trim() !== skill.id ||
419
+ seen.has(skill.id)
420
+ ) {
421
+ continue
422
+ }
423
+ seen.add(skill.id)
424
+ merged.push(skill.id)
425
+ if (typeof skill.description === 'string' && skill.description.length > 0) {
426
+ descriptions.set(skill.id, skill.description.slice(0, JEV_DECISION_MAX_DESCRIPTION_LENGTH))
427
+ }
428
+ }
429
+ }
430
+ return choiceList(merged, descriptions)
431
+ }
432
+
433
+ /**
434
+ * Build a preset request: one choice question over catalog-backed options.
435
+ * `skills` stacks the local skill shortlist (falling back to the whole
436
+ * catalog, extended with host-installed skills); `delegation` offers every
437
+ * canonical specialist except Zeus.
438
+ */
439
+ export function prepareJevPresetRequest(
440
+ route: ResolvedNativeDecisionRoute,
441
+ mode: JevDecisionPreset,
442
+ input: { readonly state?: unknown; readonly questions?: unknown },
443
+ hostSkills?: readonly JevHostSkill[],
444
+ ): JevDecisionPreparation {
445
+ if (input.questions !== undefined) return { ok: false, reasonCode: 'PRESET_INVALID' }
446
+ const state = input.state
447
+ if (!isBoundedNonBlankString(state, NATIVE_DECISION_MAX_PROMPT_LENGTH)) {
448
+ return { ok: false, reasonCode: 'STATE_INVALID' }
449
+ }
450
+
451
+ if (mode === 'delegation') {
452
+ const request = {
453
+ model: route.model,
454
+ input: [{ type: 'text', text: state }],
455
+ questions: [
456
+ {
457
+ type: 'choice' as const,
458
+ name: 'specialist',
459
+ instructions:
460
+ 'Choose one listed specialist only when the described task clearly needs it; ' +
461
+ 'otherwise choose none. This is advisory only; nothing is dispatched.',
462
+ choices: [...SPECIALIST_CHOICES, { value: 'none' }],
463
+ },
464
+ ],
465
+ } satisfies NativeDecisionRequest
466
+ return { ok: true, request: Object.freeze(request) }
467
+ }
468
+
469
+ const shortlist = selectPantheonSkills(state).skillIds
470
+ const pool = shortlist.length > 0 ? shortlist : CATALOG_SKILL_IDS
471
+ const descriptions = new Map(PANTHEON_SKILL_CATALOG.map((entry) => [entry.id, entry.description]))
472
+ const request = {
473
+ model: route.model,
474
+ input: [{ type: 'text', text: state }],
475
+ questions: [
476
+ {
477
+ type: 'choice' as const,
478
+ name: 'stack',
479
+ instructions:
480
+ 'Choose the skills worth stacking for the described task, or none when none apply. ' +
481
+ 'This is advisory only; nothing is loaded or executed by this decision.',
482
+ choices: [...mergeHostSkills(pool, hostSkills, descriptions), { value: 'none' }],
483
+ },
484
+ ],
485
+ } satisfies NativeDecisionRequest
486
+ return { ok: true, request: Object.freeze(request) }
487
+ }
488
+ // ─── Response consumption ───────────────────────────────────────────────
489
+
490
+ export interface JevDecisionAdviceAnswer {
491
+ readonly type: 'choice' | 'score' | 'predicate' | 'error'
492
+ readonly name: string
493
+ /** `choice` answers only, when the value is one of the question's choices. */
494
+ readonly choice?: string
495
+ /** `score` answers only. */
496
+ readonly score?: number
497
+ /** `predicate` answers only. */
498
+ readonly probability?: number
499
+ /** `choice` and `score` answers only, when finite in [0, 1]. */
500
+ readonly confidence?: number
501
+ /** `error` answers only. */
502
+ readonly reason?: string
503
+ }
504
+
505
+ export interface JevDecisionAdvice {
506
+ readonly answers: readonly JevDecisionAdviceAnswer[]
507
+ /** Requested question names the host did not answer. */
508
+ readonly missing: readonly string[]
509
+ readonly costUsd: number | null
510
+ readonly tokens: { readonly input: number | null; readonly output: number | null } | null
511
+ /** Always `none`: advice never dispatches, narrows, or alters permissions. */
512
+ readonly effect: 'none'
513
+ }
514
+
515
+ function isUnitInterval(value: unknown): value is number {
516
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1
517
+ }
518
+
519
+ function isNonNegativeFinite(value: unknown): value is number {
520
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0
521
+ }
522
+
523
+ function answerForQuestion(
524
+ answer: unknown,
525
+ question: NativeDecisionRequest['questions'][number],
526
+ ): JevDecisionAdviceAnswer | null {
527
+ if (answer === null || typeof answer !== 'object' || Array.isArray(answer)) return null
528
+ const record = answer as Record<string, unknown>
529
+ if (record.name !== question.name) return null
530
+ if (record.type === 'error') {
531
+ if (typeof record.reason !== 'string' || record.reason.length === 0) return null
532
+ return { type: 'error', name: question.name, reason: record.reason }
533
+ }
534
+ if (record.type !== question.type) return null
535
+ if (question.type === 'choice') {
536
+ if (typeof record.choice !== 'string') return null
537
+ if (!question.choices.some((option) => option.value === record.choice)) return null
538
+ return {
539
+ type: 'choice',
540
+ name: question.name,
541
+ choice: record.choice,
542
+ ...(isUnitInterval(record.confidence) ? { confidence: record.confidence } : {}),
543
+ }
544
+ }
545
+ if (question.type === 'score') {
546
+ if (!isNonNegativeFinite(record.score)) return null
547
+ return {
548
+ type: 'score',
549
+ name: question.name,
550
+ score: record.score,
551
+ ...(isUnitInterval(record.confidence) ? { confidence: record.confidence } : {}),
552
+ }
553
+ }
554
+ if (!isUnitInterval(record.probability)) return null
555
+ return { type: 'predicate', name: question.name, probability: record.probability }
556
+ }
557
+
558
+ /**
559
+ * Validate one host Decisions result against the prepared request.
560
+ *
561
+ * Every requested question must be answered by exactly one well-typed answer;
562
+ * a missing answer lands in `missing`, an answer whose choice is outside the
563
+ * prepared options is dropped. The consumer copies only allowlisted fields, so
564
+ * unbounded host metadata (`native`, extra probability rows) never reaches the
565
+ * tool output. The result is always advice: `effect` stays `none`.
566
+ */
567
+ export function consumeJevDecisionResult(
568
+ response: unknown,
569
+ request: NativeDecisionRequest,
570
+ ): JevDecisionAdvice {
571
+ const empty: JevDecisionAdvice = {
572
+ answers: [],
573
+ missing: request.questions.map((question) => question.name),
574
+ costUsd: null,
575
+ tokens: null,
576
+ effect: 'none',
577
+ }
578
+ if (response === null || typeof response !== 'object' || Array.isArray(response)) return empty
579
+ const record = response as Record<string, unknown>
580
+ if (!Array.isArray(record.answers)) return empty
581
+
582
+ const answers: JevDecisionAdviceAnswer[] = []
583
+ const missing: string[] = []
584
+ for (const question of request.questions) {
585
+ const matches = record.answers
586
+ .map((candidate) => answerForQuestion(candidate, question))
587
+ .filter((answer): answer is JevDecisionAdviceAnswer => answer !== null)
588
+ if (matches.length === 0) {
589
+ missing.push(question.name)
590
+ continue
591
+ }
592
+ // One answer per question is the host contract; duplicates are untrustworthy.
593
+ answers.push(
594
+ matches.length === 1
595
+ ? (matches[0] as JevDecisionAdviceAnswer)
596
+ : {
597
+ type: 'error',
598
+ name: question.name,
599
+ reason: 'DUPLICATE_ANSWER',
600
+ },
601
+ )
602
+ }
603
+
604
+ const costUsd = isNonNegativeFinite(record.cost) ? record.cost : null
605
+ let tokens: JevDecisionAdvice['tokens'] = null
606
+ if (
607
+ record.tokens !== undefined &&
608
+ record.tokens !== null &&
609
+ typeof record.tokens === 'object' &&
610
+ !Array.isArray(record.tokens)
611
+ ) {
612
+ const usage = record.tokens as Record<string, unknown>
613
+ tokens = {
614
+ input: isNonNegativeFinite(usage.input) ? usage.input : null,
615
+ output: isNonNegativeFinite(usage.output) ? usage.output : null,
616
+ }
617
+ }
618
+ return Object.freeze({
619
+ answers: Object.freeze(answers),
620
+ missing: Object.freeze(missing),
621
+ costUsd,
622
+ tokens,
623
+ effect: 'none' as const,
624
+ })
625
+ }