pantheon-opencode 1.6.2-beta.5 → 1.6.2-beta.6

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.
@@ -1,13 +1,27 @@
1
1
  /**
2
- * Internal, parser-issued usage capabilities. This module is deliberately not
3
- * exported from the package entrypoints; callers cannot provide a cost value.
2
+ * Internal, parser-issued usage capabilities for the native Decisions route.
3
+ * This module is deliberately not exported from the package entrypoints;
4
+ * callers cannot provide a cost value — the cost comes from the host's own
5
+ * DecisionResult, and this module only mints the opaque capability the ledger
6
+ * accepts. The legacy direct-fetch receipt verifier was removed with the fetch
7
+ * runner.
4
8
  */
5
9
 
6
- export type ReconciliableUsageProvider = 'openai-decisions' | 'typesafe-jev'
10
+ /** Providers that can appear in usage details: native Decisions routes. */
11
+ export type UsageProvider = 'typesafe-jev' | 'opencode-console' | 'jev-free'
12
+
13
+ export interface ParsedUsageCounts {
14
+ provider: UsageProvider
15
+ model: string
16
+ inputTokens: number
17
+ outputTokens: number
18
+ cachedInputTokens: number
19
+ cacheWriteInputTokens: number
20
+ }
7
21
 
8
22
  export interface UsageReservationBinding {
9
23
  reservationId: string
10
- provider: ReconciliableUsageProvider
24
+ provider: UsageProvider
11
25
  model: string
12
26
  period: string
13
27
  }
@@ -17,38 +31,39 @@ export type VerifiedUsageEvidence = {
17
31
  readonly [verifiedUsageEvidenceBrand]: true
18
32
  }
19
33
 
20
- export interface ParsedUsageCounts {
21
- provider: ReconciliableUsageProvider
22
- model: string
23
- inputTokens: number
24
- outputTokens: number
25
- cachedInputTokens: number
26
- cacheWriteInputTokens: number
27
- }
28
-
29
34
  export interface VerifiedUsageEvidenceDetails extends ParsedUsageCounts {
30
35
  reservationId: string
31
36
  period: string
32
37
  actualCostMicros: number
33
- pricingSnapshot: '2026-10-30'
38
+ pricingSnapshot: 'host-reported'
34
39
  }
35
40
 
36
- const MODEL_IDS: Readonly<Record<ReconciliableUsageProvider, string>> = Object.freeze({
37
- 'openai-decisions': 'gpt-6-luna',
38
- 'typesafe-jev': 'jev-1.14.0',
39
- })
40
41
  const RESERVATION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
41
42
  const UTC_PERIOD = /^\d{4}-(0[1-9]|1[0-2])$/
42
43
  const evidenceDetails = new WeakMap<object, VerifiedUsageEvidenceDetails>()
43
44
 
44
45
  /**
45
- * Validate only official usage fields for providers with a documented price
46
- * snapshot, then mint an opaque capability bound to one reservation identity.
47
- * Console models and zero-cost results deliberately produce no capability.
46
+ * Budget providers with a native host Decisions route. `openai-decisions` is
47
+ * absent: direct OpenAI has no native route, so it can never settle one.
48
48
  */
49
- export function verifyProviderUsageForReservation(
49
+ function isNativeUsageProvider(value: string): value is UsageProvider {
50
+ return value === 'typesafe-jev' || value === 'opencode-console' || value === 'jev-free'
51
+ }
52
+
53
+ /**
54
+ * Mint a reconciliation capability from a native host Decisions result.
55
+ *
56
+ * On the native route the host is the billing authority (it owns the provider
57
+ * credentials and the Console ledger), so the host-reported `cost` plays the
58
+ * role the fetch path's provider receipt played. Absent cost is a real zero —
59
+ * the free Console variant and hosts that do not price Decisions both land
60
+ * here, and reconciling at zero releases the reservation instead of burning
61
+ * the period's budget. A result that produced no answer settles nothing: an
62
+ * error payload is not evidence that a decision was paid for.
63
+ */
64
+ export function verifyNativeUsageForReservation(
50
65
  bindingInput: unknown,
51
- response: unknown,
66
+ result: unknown,
52
67
  ): VerifiedUsageEvidence | null {
53
68
  try {
54
69
  if (
@@ -62,8 +77,10 @@ export function verifyProviderUsageForReservation(
62
77
  const reservationId = bindingInput.reservationId
63
78
  const period = bindingInput.period
64
79
  if (
65
- !isReconciliableProvider(provider) ||
66
- model !== MODEL_IDS[provider] ||
80
+ typeof provider !== 'string' ||
81
+ !isNativeUsageProvider(provider) ||
82
+ typeof model !== 'string' ||
83
+ model.length === 0 ||
67
84
  typeof reservationId !== 'string' ||
68
85
  !RESERVATION_ID.test(reservationId) ||
69
86
  typeof period !== 'string' ||
@@ -71,21 +88,50 @@ export function verifyProviderUsageForReservation(
71
88
  ) {
72
89
  return null
73
90
  }
74
- const parsed = parseProviderUsageCounts(provider, response)
75
- if (!parsed || parsed.model !== model) return null
76
- if (parsed.cachedInputTokens !== 0 || parsed.cacheWriteInputTokens !== 0) return null
77
- const actualCostMicros = priceUsageMicros(parsed)
78
- if (actualCostMicros === null || actualCostMicros <= 0) return null
91
+ if (
92
+ !isPlainRecord(result) ||
93
+ !Array.isArray(result.answers) ||
94
+ result.answers.length === 0 ||
95
+ !result.answers.every((answer) => isPlainRecord(answer))
96
+ ) {
97
+ return null
98
+ }
99
+
100
+ let actualCostMicros = 0
101
+ if (result.cost !== undefined) {
102
+ if (!isNonNegativeFinite(result.cost)) return null
103
+ actualCostMicros = Math.round(result.cost * 1_000_000)
104
+ if (!Number.isSafeInteger(actualCostMicros)) return null
105
+ }
106
+ let inputTokens = 0
107
+ let outputTokens = 0
108
+ if (result.tokens !== undefined) {
109
+ if (!isPlainRecord(result.tokens)) return null
110
+ const { input, output } = result.tokens
111
+ if (
112
+ (input !== undefined && !isNonNegativeFinite(input)) ||
113
+ (output !== undefined && !isNonNegativeFinite(output))
114
+ ) {
115
+ return null
116
+ }
117
+ inputTokens = typeof input === 'number' ? input : 0
118
+ outputTokens = typeof output === 'number' ? output : 0
119
+ }
79
120
 
80
121
  const evidence = Object.freeze(Object.create(null)) as VerifiedUsageEvidence
81
122
  evidenceDetails.set(
82
123
  evidence,
83
124
  Object.freeze({
84
- ...parsed,
125
+ provider,
126
+ model,
127
+ inputTokens,
128
+ outputTokens,
129
+ cachedInputTokens: 0,
130
+ cacheWriteInputTokens: 0,
85
131
  reservationId,
86
132
  period,
87
133
  actualCostMicros,
88
- pricingSnapshot: '2026-10-30',
134
+ pricingSnapshot: 'host-reported',
89
135
  }),
90
136
  )
91
137
  return evidence
@@ -102,93 +148,8 @@ export function getVerifiedUsageEvidenceDetails(
102
148
  return evidenceDetails.get(value as object) ?? null
103
149
  }
104
150
 
105
- /** Shared strict usage parser used by the isolated provider-contract tests. */
106
- export function parseProviderUsageCounts(
107
- provider: unknown,
108
- response: unknown,
109
- ): ParsedUsageCounts | null {
110
- try {
111
- if (
112
- !isReconciliableProvider(provider) ||
113
- !isPlainRecord(response) ||
114
- response.model !== MODEL_IDS[provider] ||
115
- !isPlainRecord(response.usage)
116
- ) {
117
- return null
118
- }
119
- const usage = response.usage
120
- if (provider === 'openai-decisions') {
121
- if (
122
- !hasExactKeys(usage, [
123
- 'input_tokens',
124
- 'input_tokens_details',
125
- 'output_tokens',
126
- 'output_tokens_details',
127
- 'total_tokens',
128
- ]) ||
129
- !isPlainRecord(usage.input_tokens_details) ||
130
- !hasExactKeys(usage.input_tokens_details, ['cache_write_tokens', 'cached_tokens']) ||
131
- !isPlainRecord(usage.output_tokens_details) ||
132
- !hasExactKeys(usage.output_tokens_details, ['reasoning_tokens']) ||
133
- !isNonNegativeSafeInteger(usage.input_tokens) ||
134
- !isNonNegativeSafeInteger(usage.output_tokens) ||
135
- !isNonNegativeSafeInteger(usage.total_tokens) ||
136
- !isNonNegativeSafeInteger(usage.input_tokens_details.cache_write_tokens) ||
137
- !isNonNegativeSafeInteger(usage.input_tokens_details.cached_tokens) ||
138
- !isNonNegativeSafeInteger(usage.output_tokens_details.reasoning_tokens) ||
139
- !Number.isSafeInteger(usage.input_tokens + usage.output_tokens) ||
140
- usage.input_tokens + usage.output_tokens !== usage.total_tokens ||
141
- usage.input_tokens_details.cache_write_tokens + usage.input_tokens_details.cached_tokens >
142
- usage.input_tokens ||
143
- usage.output_tokens_details.reasoning_tokens > usage.output_tokens
144
- ) {
145
- return null
146
- }
147
- } else if (
148
- !hasExactKeys(usage, ['input_tokens', 'output_tokens']) ||
149
- !isNonNegativeSafeInteger(usage.input_tokens) ||
150
- !isNonNegativeSafeInteger(usage.output_tokens)
151
- ) {
152
- return null
153
- }
154
- return {
155
- provider,
156
- model: MODEL_IDS[provider],
157
- inputTokens: usage.input_tokens as number,
158
- outputTokens: usage.output_tokens as number,
159
- cachedInputTokens:
160
- provider === 'openai-decisions'
161
- ? ((usage.input_tokens_details as Record<string, number>).cached_tokens as number)
162
- : 0,
163
- cacheWriteInputTokens:
164
- provider === 'openai-decisions'
165
- ? ((usage.input_tokens_details as Record<string, number>).cache_write_tokens as number)
166
- : 0,
167
- }
168
- } catch {
169
- return null
170
- }
171
- }
172
-
173
- function priceUsageMicros(usage: ParsedUsageCounts): number | null {
174
- // Snapshot: GPT-6 Luna standard rates are $0.10/M input and $0.50/M output;
175
- // TypeSafe Jev 1.14 is $0.042/M input and $0 output. Discounts are not applied.
176
- const numerator =
177
- usage.provider === 'openai-decisions'
178
- ? BigInt(usage.inputTokens) + 5n * BigInt(usage.outputTokens)
179
- : 42n * BigInt(usage.inputTokens)
180
- const denominator = usage.provider === 'openai-decisions' ? 10n : 1_000n
181
- const roundedMicros = (numerator + denominator - 1n) / denominator
182
- if (roundedMicros <= 0n || roundedMicros > BigInt(Number.MAX_SAFE_INTEGER)) return null
183
- return Number(roundedMicros)
184
- }
185
-
186
- function isReconciliableProvider(value: unknown): value is ReconciliableUsageProvider {
187
- return value === 'openai-decisions' || value === 'typesafe-jev'
188
- }
189
-
190
- function isNonNegativeSafeInteger(value: unknown): value is number {
191
- return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
151
+ function isNonNegativeFinite(value: unknown): value is number {
152
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0
192
153
  }
193
154
 
194
155
  function isPlainRecord(value: unknown): value is Record<string, unknown> {
@@ -29,8 +29,9 @@
29
29
  *
30
30
  * ## Blast radius (N5) — measured: the declared rules match nothing
31
31
  *
32
- * PROBE-F (`.pantheon/deepwork/decision-layer-v2/PROBE-F-permission-paths.md`)
33
- * delivered 24 real `permission.evaluate` events on the 2.2.5 host. Every one
32
+ * PROBE-F (permission.evaluate paths; measured facts summarized in
33
+ * docs/reference/local-decision-router.md) delivered 24 real
34
+ * `permission.evaluate` events on the 2.2.5 host. Every one
34
35
  * carries a valid `action` token and a non-empty top-level `sessionID`
35
36
  * (PROBE-F §3.2), so neither declared rule can match: `action.unusable` needs a
36
37
  * non-token action, `allow.unattributed` needs an `allow` with no session. With
@@ -157,7 +157,7 @@ export const DECISION_POINT_REGISTRY: readonly DecisionPoint[] = Object.freeze([
157
157
  'a background image job was never exercised (PROBE-D §5.4)',
158
158
  ],
159
159
  notes:
160
- 'Branch 1 of PLAN §5.1 was selected by PROBE-D §7 (`.pantheon/deepwork/decision-layer-v2/PROBE-D-turn-end-channel.md`): `session.execution.succeeded` is delivered for child sessions with the child copy of `data.sessionID` — 13/13 children (6 foreground, 5 background, 2 with compaction) — and for background work (PROBE-D §4.1–§4.2). The event does NOT carry `parentID` (`dataKeys=["sessionID"]`, 44/44): attribution comes from `session.created.parentID` or `ctx.session.get`, never from the succeeded event (PROBE-D §4.1). Multiplicity is per EXECUTION, not per turn: 44 `started` = 44 `succeeded` for 46 inbox items; manual compaction adds +1 (C2 = 3), automatic compaction +0 (C1 = 1), a late background notification +1 on the parent (B3/B4/B5 = 2 vs B1/B2 = 1) (PROBE-D §4.3). The adapter implements that execution counter (`v2-decision-points/p7-loop.ts`) behind `PANTHEON_V2_P7_LOOP`, OFF by default; cutover is Phase 4b. Effect stays unmeasured (C6 is closed by PROBE-E; no effect of P7 itself was observed): the adapter records `effect: none` and must never be described as working enforcement while the flag is off. The 12-execution cap (`P7_LOOP_MAX_EXECUTIONS`) is ADVISORY: `reset()` is caller-supplied, no measured user-input surface in the probed host provides a signal to call it, and the streak is not claimed to reset on any event. PROBE-D retires the PRE-01/PM-12 blocking premises; the premise register records PM-12 as closed by that measurement.',
160
+ 'Branch 1 of PLAN §5.1 was selected by PROBE-D §7 (measured facts summarized in docs/reference/local-decision-router.md): `session.execution.succeeded` is delivered for child sessions with the child copy of `data.sessionID` — 13/13 children (6 foreground, 5 background, 2 with compaction) — and for background work (PROBE-D §4.1–§4.2). The event does NOT carry `parentID` (`dataKeys=["sessionID"]`, 44/44): attribution comes from `session.created.parentID` or `ctx.session.get`, never from the succeeded event (PROBE-D §4.1). Multiplicity is per EXECUTION, not per turn: 44 `started` = 44 `succeeded` for 46 inbox items; manual compaction adds +1 (C2 = 3), automatic compaction +0 (C1 = 1), a late background notification +1 on the parent (B3/B4/B5 = 2 vs B1/B2 = 1) (PROBE-D §4.3). The adapter implements that execution counter (`v2-decision-points/p7-loop.ts`) behind `PANTHEON_V2_P7_LOOP`, OFF by default; cutover is Phase 4b. Effect stays unmeasured (C6 is closed by PROBE-E; no effect of P7 itself was observed): the adapter records `effect: none` and must never be described as working enforcement while the flag is off. The 12-execution cap (`P7_LOOP_MAX_EXECUTIONS`) is ADVISORY: `reset()` is caller-supplied, no measured user-input surface in the probed host provides a signal to call it, and the streak is not claimed to reset on any event. PROBE-D retires the PRE-01/PM-12 blocking premises; the premise register records PM-12 as closed by that measurement.',
161
161
  }),
162
162
  Object.freeze<DecisionPoint>({
163
163
  id: 'P8',
@@ -0,0 +1,365 @@
1
+ /**
2
+ * Offline scaffolding for OpenCode V2.2.5's native Decisions API.
3
+ *
4
+ * This module intentionally has no host call site. It resolves only model refs
5
+ * already present in the host model catalog, prepares a minimal current-turn
6
+ * request, and consumes a mocked/host response as non-authoritative advice.
7
+ * Nothing here calls a provider, reads credentials, or changes host behavior.
8
+ */
9
+ import type { Model } from '@opencode/plugin'
10
+ import type { Context } from '@opencode/plugin/promise/plugin'
11
+ import type { SessionPrompt } from '@opencode/plugin/promise/session'
12
+ import { PANTHEON_AGENT_CATALOG } from './pantheon-decision-catalog.ts'
13
+
14
+ export const NATIVE_DECISION_ANSWER_NAME = 'specialist'
15
+ export const NATIVE_DECISION_MAX_PROMPT_LENGTH = 12_000
16
+
17
+ type NativeDecisionGenerator = Context['experimental']['generate']['decisions']
18
+ export type NativeDecisionRequest = Parameters<NativeDecisionGenerator>[0]
19
+ export type NativeDecisionResponse = Awaited<ReturnType<NativeDecisionGenerator>>
20
+ export type NativeDecisionModelRef = NativeDecisionRequest['model']
21
+
22
+ export const NATIVE_STOCK_DECISION_ROUTES = Object.freeze([
23
+ Object.freeze({
24
+ providerID: 'opencode',
25
+ id: 'jev-1.13',
26
+ kind: 'opencode-console-jev',
27
+ billing: 'OpenCode Console',
28
+ }),
29
+ Object.freeze({
30
+ providerID: 'openrouter',
31
+ id: 'typesafe/jev-1.13',
32
+ kind: 'openrouter-jev',
33
+ billing: 'OpenRouter',
34
+ }),
35
+ ] as const)
36
+
37
+ type NativeDecisionRouteKind =
38
+ | (typeof NATIVE_STOCK_DECISION_ROUTES)[number]['kind']
39
+ | 'custom-decision'
40
+
41
+ export interface ResolvedNativeDecisionRoute {
42
+ readonly model: NativeDecisionModelRef
43
+ readonly kind: NativeDecisionRouteKind
44
+ readonly billing: string
45
+ }
46
+
47
+ export type NativeDecisionRouteFailure =
48
+ | 'AUTO_MODEL_UNAVAILABLE'
49
+ | 'INVALID_MODEL_REF'
50
+ | 'DIRECT_OPENAI_UNSUPPORTED'
51
+ | 'MODEL_NOT_IN_CATALOG'
52
+ | 'AMBIGUOUS_MODEL'
53
+ | 'MODEL_NOT_DECISION'
54
+
55
+ export type NativeDecisionRouteResolution =
56
+ | { readonly ok: true; readonly route: ResolvedNativeDecisionRoute }
57
+ | { readonly ok: false; readonly reasonCode: NativeDecisionRouteFailure }
58
+
59
+ export type NativeDecisionSelection = 'auto' | NativeDecisionModelRef
60
+
61
+ type DecisionModelCatalogEntry = Pick<Model.Info, 'providerID' | 'id' | 'type'>
62
+
63
+ function readModelRef(value: unknown): NativeDecisionModelRef | null {
64
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return null
65
+ const record = value as Record<string, unknown>
66
+ if (
67
+ typeof record.providerID !== 'string' ||
68
+ record.providerID.length === 0 ||
69
+ record.providerID.trim() !== record.providerID ||
70
+ typeof record.id !== 'string' ||
71
+ record.id.length === 0 ||
72
+ record.id.trim() !== record.id ||
73
+ (record.variant !== undefined && typeof record.variant !== 'string')
74
+ ) {
75
+ return null
76
+ }
77
+ return {
78
+ providerID: record.providerID,
79
+ id: record.id,
80
+ ...(record.variant === undefined ? {} : { variant: record.variant }),
81
+ }
82
+ }
83
+
84
+ function findRouteKind(
85
+ model: NativeDecisionModelRef,
86
+ ): Pick<ResolvedNativeDecisionRoute, 'kind' | 'billing'> {
87
+ const stock = NATIVE_STOCK_DECISION_ROUTES.find(
88
+ (candidate) => candidate.providerID === model.providerID && candidate.id === model.id,
89
+ )
90
+ if (stock !== undefined) return { kind: stock.kind, billing: stock.billing }
91
+ if (model.providerID === 'openrouter') {
92
+ return { kind: 'custom-decision', billing: 'OpenRouter' }
93
+ }
94
+ if (model.providerID === 'opencode') {
95
+ return { kind: 'custom-decision', billing: 'OpenCode Console' }
96
+ }
97
+ return { kind: 'custom-decision', billing: 'Provider configured in OpenCode' }
98
+ }
99
+
100
+ /**
101
+ * Resolve Auto strictly against the exact effective session model. It never
102
+ * searches for a substitute, changes providers, or infers decision capability
103
+ * from a chat model's provider or id.
104
+ */
105
+ export function resolveNativeDecisionRoute(
106
+ selection: NativeDecisionSelection,
107
+ effectiveSessionModel: unknown,
108
+ modelCatalog: readonly DecisionModelCatalogEntry[],
109
+ ): NativeDecisionRouteResolution {
110
+ const requested =
111
+ selection === 'auto' ? readModelRef(effectiveSessionModel) : readModelRef(selection)
112
+ if (selection === 'auto' && requested === null) {
113
+ return { ok: false, reasonCode: 'AUTO_MODEL_UNAVAILABLE' }
114
+ }
115
+ if (requested === null) return { ok: false, reasonCode: 'INVALID_MODEL_REF' }
116
+ if (requested.providerID === 'openai') {
117
+ return { ok: false, reasonCode: 'DIRECT_OPENAI_UNSUPPORTED' }
118
+ }
119
+
120
+ const matches = modelCatalog.filter(
121
+ (model) => model.providerID === requested.providerID && model.id === requested.id,
122
+ )
123
+ if (matches.length === 0) return { ok: false, reasonCode: 'MODEL_NOT_IN_CATALOG' }
124
+ if (matches.length !== 1) return { ok: false, reasonCode: 'AMBIGUOUS_MODEL' }
125
+ if (matches[0]?.type !== 'decision') {
126
+ return { ok: false, reasonCode: 'MODEL_NOT_DECISION' }
127
+ }
128
+
129
+ return {
130
+ ok: true,
131
+ route: Object.freeze({ model: requested, ...findRouteKind(requested) }),
132
+ }
133
+ }
134
+
135
+ export interface NativeDecisionConsentEntry {
136
+ readonly providerID: string
137
+ readonly modelID: string
138
+ readonly enabled: boolean
139
+ }
140
+
141
+ export type NativeDecisionConsentResult =
142
+ | { readonly allowed: true; readonly reasonCode: 'EXACT_ROUTE_CONSENT' }
143
+ | {
144
+ readonly allowed: false
145
+ readonly reasonCode: 'CONSENT_MISSING' | 'CONSENT_AMBIGUOUS' | 'CONSENT_DISABLED'
146
+ }
147
+
148
+ /** Pure provider+model-specific consent check. Missing consent is always off. */
149
+ export function evaluateNativeDecisionConsent(
150
+ route: ResolvedNativeDecisionRoute,
151
+ entries: readonly NativeDecisionConsentEntry[] = [],
152
+ ): NativeDecisionConsentResult {
153
+ const exact = entries.filter(
154
+ (entry) => entry.providerID === route.model.providerID && entry.modelID === route.model.id,
155
+ )
156
+ if (exact.length === 0) return { allowed: false, reasonCode: 'CONSENT_MISSING' }
157
+ if (exact.length !== 1) return { allowed: false, reasonCode: 'CONSENT_AMBIGUOUS' }
158
+ if (exact[0]?.enabled !== true) return { allowed: false, reasonCode: 'CONSENT_DISABLED' }
159
+ return { allowed: true, reasonCode: 'EXACT_ROUTE_CONSENT' }
160
+ }
161
+
162
+ /**
163
+ * Evidence required to bind a prompt callback to exactly one current turn.
164
+ * OpenCode V2.2.5's SessionPrompt event does not supply these queue/activity
165
+ * facts, so this contract is currently test-only and cannot authorize a call.
166
+ */
167
+ export interface NativeDecisionCorrelationEvidence {
168
+ readonly sessionID: string
169
+ readonly messageID: string
170
+ readonly currentMessageID: string
171
+ readonly delivery: 'steer' | 'queue'
172
+ readonly pendingMessageIDs: readonly string[]
173
+ readonly activeMessageID: string | null
174
+ readonly continuation: boolean
175
+ }
176
+
177
+ export type NativeDecisionCorrelationFailure =
178
+ | 'CORRELATION_UNAVAILABLE'
179
+ | 'CORRELATION_MISMATCH'
180
+ | 'QUEUED_TURN'
181
+ | 'CONCURRENT_TURN'
182
+ | 'CONTINUATION_TURN'
183
+
184
+ function isNonBlankID(value: unknown): value is string {
185
+ return typeof value === 'string' && value.trim().length > 0
186
+ }
187
+
188
+ export function validateNativeDecisionCorrelation(
189
+ event: SessionPrompt,
190
+ evidence: NativeDecisionCorrelationEvidence | undefined,
191
+ ): NativeDecisionCorrelationFailure | null {
192
+ if (event === null || typeof event !== 'object' || Array.isArray(event)) {
193
+ return 'CORRELATION_MISMATCH'
194
+ }
195
+ if (!isNonBlankID(event.sessionID) || !isNonBlankID(event.messageID)) {
196
+ return 'CORRELATION_MISMATCH'
197
+ }
198
+ if (evidence === undefined) return 'CORRELATION_UNAVAILABLE'
199
+ if (evidence === null || typeof evidence !== 'object' || Array.isArray(evidence)) {
200
+ return 'CORRELATION_UNAVAILABLE'
201
+ }
202
+ if (
203
+ !isNonBlankID(evidence.sessionID) ||
204
+ !isNonBlankID(evidence.messageID) ||
205
+ !isNonBlankID(evidence.currentMessageID) ||
206
+ (evidence.delivery !== 'steer' && evidence.delivery !== 'queue') ||
207
+ !Array.isArray(evidence.pendingMessageIDs) ||
208
+ evidence.pendingMessageIDs.some((id) => !isNonBlankID(id)) ||
209
+ (evidence.activeMessageID !== null && !isNonBlankID(evidence.activeMessageID)) ||
210
+ typeof evidence.continuation !== 'boolean'
211
+ ) {
212
+ return 'CORRELATION_UNAVAILABLE'
213
+ }
214
+ if (
215
+ event.sessionID !== evidence.sessionID ||
216
+ event.messageID !== evidence.messageID ||
217
+ event.messageID !== evidence.currentMessageID
218
+ ) {
219
+ return 'CORRELATION_MISMATCH'
220
+ }
221
+ if (event.delivery !== 'steer' || evidence.delivery !== 'steer') return 'QUEUED_TURN'
222
+ if (
223
+ evidence.activeMessageID !== null ||
224
+ evidence.pendingMessageIDs.length !== 1 ||
225
+ evidence.pendingMessageIDs[0] !== event.messageID
226
+ ) {
227
+ return 'CONCURRENT_TURN'
228
+ }
229
+ if (evidence.continuation) return 'CONTINUATION_TURN'
230
+ return null
231
+ }
232
+
233
+ const DECISION_AGENT_IDS = new Set(
234
+ PANTHEON_AGENT_CATALOG.filter((agent) => agent.id !== 'zeus').map((agent) => agent.id),
235
+ )
236
+
237
+ export type NativeDecisionPreparationFailure =
238
+ | NativeDecisionRouteFailure
239
+ | NativeDecisionCorrelationFailure
240
+ | 'CONSENT_MISSING'
241
+ | 'CONSENT_AMBIGUOUS'
242
+ | 'CONSENT_DISABLED'
243
+ | 'PROMPT_EMPTY'
244
+ | 'PROMPT_TOO_LONG'
245
+ | 'FILES_NOT_ALLOWED'
246
+ | 'INVALID_CANDIDATES'
247
+
248
+ export type NativeDecisionPreparation =
249
+ | { readonly ok: true; readonly request: NativeDecisionRequest }
250
+ | { readonly ok: false; readonly reasonCode: NativeDecisionPreparationFailure }
251
+
252
+ /**
253
+ * Prepare only the current user text and a fixed question. This function does
254
+ * not invoke the native API and does not accept history, tools, paths, files,
255
+ * system instructions, memory, or catalog descriptions as inputs.
256
+ */
257
+ export function prepareNativeDecisionRequest(
258
+ route: ResolvedNativeDecisionRoute,
259
+ event: SessionPrompt,
260
+ eligibleAgentIDs: readonly string[],
261
+ consentEntries: readonly NativeDecisionConsentEntry[] = [],
262
+ correlationEvidence?: NativeDecisionCorrelationEvidence,
263
+ ): NativeDecisionPreparation {
264
+ if (
265
+ event === null ||
266
+ typeof event !== 'object' ||
267
+ event.prompt === null ||
268
+ typeof event.prompt !== 'object'
269
+ ) {
270
+ return { ok: false, reasonCode: 'CORRELATION_MISMATCH' }
271
+ }
272
+ const consent = evaluateNativeDecisionConsent(route, consentEntries)
273
+ if (!consent.allowed) return { ok: false, reasonCode: consent.reasonCode }
274
+
275
+ const correlationFailure = validateNativeDecisionCorrelation(event, correlationEvidence)
276
+ if (correlationFailure !== null) return { ok: false, reasonCode: correlationFailure }
277
+
278
+ const promptFiles = (event.prompt as { files?: unknown }).files
279
+ if (promptFiles !== undefined && (!Array.isArray(promptFiles) || promptFiles.length > 0)) {
280
+ return { ok: false, reasonCode: 'FILES_NOT_ALLOWED' }
281
+ }
282
+ const promptText = event.prompt.text
283
+ if (typeof promptText !== 'string' || promptText.trim().length === 0) {
284
+ return { ok: false, reasonCode: 'PROMPT_EMPTY' }
285
+ }
286
+ if (promptText.length > NATIVE_DECISION_MAX_PROMPT_LENGTH) {
287
+ return { ok: false, reasonCode: 'PROMPT_TOO_LONG' }
288
+ }
289
+
290
+ const candidates = new Set<string>()
291
+ for (const id of eligibleAgentIDs) {
292
+ if (typeof id !== 'string' || !DECISION_AGENT_IDS.has(id) || candidates.has(id)) {
293
+ return { ok: false, reasonCode: 'INVALID_CANDIDATES' }
294
+ }
295
+ candidates.add(id)
296
+ }
297
+ if (candidates.size > DECISION_AGENT_IDS.size) {
298
+ return { ok: false, reasonCode: 'INVALID_CANDIDATES' }
299
+ }
300
+
301
+ const request = {
302
+ model: route.model,
303
+ input: [{ type: 'text', text: promptText }],
304
+ questions: [
305
+ {
306
+ type: 'choice',
307
+ name: NATIVE_DECISION_ANSWER_NAME,
308
+ instructions:
309
+ 'Choose one listed specialist only when the current request clearly needs it; otherwise choose none. This is advisory only.',
310
+ choices: [...[...candidates].map((value) => ({ value })), { value: 'none' }],
311
+ },
312
+ ],
313
+ } satisfies NativeDecisionRequest
314
+
315
+ return { ok: true, request: Object.freeze(request) }
316
+ }
317
+
318
+ export interface NativeDecisionAdvice {
319
+ readonly agent: string | null
320
+ readonly reasonCode: 'RECOMMENDED' | 'ABSTAIN' | 'INVALID_RESPONSE' | 'LOW_CONFIDENCE'
321
+ readonly effect: 'none'
322
+ }
323
+
324
+ /** Bounded consumer: validates one candidate and returns advice only. */
325
+ export function consumeNativeDecisionAdvice(
326
+ response: unknown,
327
+ eligibleAgentIDs: readonly string[],
328
+ ): NativeDecisionAdvice {
329
+ const abstain = (reasonCode: NativeDecisionAdvice['reasonCode']): NativeDecisionAdvice =>
330
+ Object.freeze({ agent: null, reasonCode, effect: 'none' })
331
+ if (response === null || typeof response !== 'object' || Array.isArray(response)) {
332
+ return abstain('INVALID_RESPONSE')
333
+ }
334
+ const answers = (response as { answers?: unknown }).answers
335
+ if (!Array.isArray(answers)) return abstain('INVALID_RESPONSE')
336
+ const matches = answers.filter(
337
+ (answer): answer is Record<string, unknown> =>
338
+ answer !== null &&
339
+ typeof answer === 'object' &&
340
+ !Array.isArray(answer) &&
341
+ answer.name === NATIVE_DECISION_ANSWER_NAME,
342
+ )
343
+ if (matches.length !== 1) return abstain(matches.length === 0 ? 'ABSTAIN' : 'INVALID_RESPONSE')
344
+
345
+ const answer = matches[0]
346
+ if (answer?.type !== 'choice') return abstain('ABSTAIN')
347
+ if (answer.choice === 'none') return abstain('ABSTAIN')
348
+ if (typeof answer.choice !== 'string' || !eligibleAgentIDs.includes(answer.choice)) {
349
+ return abstain('INVALID_RESPONSE')
350
+ }
351
+ if (
352
+ typeof answer.confidence !== 'number' ||
353
+ !Number.isFinite(answer.confidence) ||
354
+ answer.confidence < 0 ||
355
+ answer.confidence > 1
356
+ ) {
357
+ return abstain('INVALID_RESPONSE')
358
+ }
359
+ if (!DECISION_AGENT_IDS.has(answer.choice)) return abstain('INVALID_RESPONSE')
360
+ return Object.freeze({ agent: answer.choice, reasonCode: 'RECOMMENDED', effect: 'none' })
361
+ }
362
+
363
+ // This type assertion keeps the source contract tied to @opencode/plugin@2.2.5.
364
+ // Any removal or schema change to the native method fails `npm run typecheck`.
365
+ export type OpenCodeV225DecisionApi = Pick<Context['experimental']['generate'], 'decisions'>
@@ -48,6 +48,7 @@
48
48
 
49
49
  import { createCostCommand } from './cost-command.ts'
50
50
  import { createHashlineEditTool, type HashlineToolResult } from './hashline/tool.ts'
51
+ import { createV2JevDecisionDefinition, type V2JevDecisionRuntime } from './jev-decision-tool.ts'
51
52
  import { createV2LocalDecisionDefinition } from './local-decision-tool.ts'
52
53
  import { createModelCommand } from './model-command.ts'
53
54
  import type { ToolContextLike } from './tool-context.ts'
@@ -449,6 +450,7 @@ export interface V2ToolShadowOptions {
449
450
  export function createV2ToolDefinitions(
450
451
  visionRuntime?: V2VisionRuntime,
451
452
  shadow: V2ToolShadowOptions = {},
453
+ jevRuntime?: V2JevDecisionRuntime,
452
454
  ): V2ToolDef[] {
453
455
  const definitions: V2ToolDef[] = [
454
456
  {
@@ -496,5 +498,6 @@ export function createV2ToolDefinitions(
496
498
  }),
497
499
  )
498
500
  if (visionRuntime) definitions.push(createV2VisionTool(visionRuntime))
501
+ if (jevRuntime) definitions.push(createV2JevDecisionDefinition(jevRuntime))
499
502
  return definitions
500
503
  }