pantheon-opencode 1.6.2-beta.4 → 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.
Files changed (65) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +202 -29
  3. package/README.pt-BR.md +9 -0
  4. package/bin/pantheon-init.mjs +6 -1
  5. package/package.json +2 -1
  6. package/plugin.json +1 -1
  7. package/pyproject.toml +1 -1
  8. package/scripts/decision-router-budget.mjs +7 -8
  9. package/scripts/decision-router-v2-budget.mjs +218 -0
  10. package/scripts/decision-router-v2-egress.mjs +272 -0
  11. package/scripts/decision-router.mjs +268 -46
  12. package/scripts/docs-check-changelog.mjs +5 -3
  13. package/scripts/install/decision-layer-preview.mjs +376 -0
  14. package/scripts/install/decision-router-config.mjs +162 -34
  15. package/scripts/mcp_resources.py +11 -9
  16. package/scripts/release-notes.mjs +30 -7
  17. package/scripts/versioning.mjs +41 -5
  18. package/src/mcp/eval_store.py +11 -4
  19. package/src/mcp/mcp_resources.py +11 -9
  20. package/src/mcp/memory_mcp.py +293 -150
  21. package/src/pantheon/jev-decision-tool.ts +336 -0
  22. package/src/pantheon/jev-decisions.ts +625 -0
  23. package/src/pantheon/local-decision-budget.ts +4 -1
  24. package/src/pantheon/local-decision-egress-gate.ts +16 -136
  25. package/src/pantheon/local-decision-prompt.ts +184 -45
  26. package/src/pantheon/local-decision-provider-matrix.ts +14 -62
  27. package/src/pantheon/local-decision-skills.ts +115 -5
  28. package/src/pantheon/local-decision-tool.ts +35 -1
  29. package/src/pantheon/local-decision-turn.ts +15 -252
  30. package/src/pantheon/local-decision-usage-evidence.internal.ts +80 -119
  31. package/src/pantheon/v2-decision-budget.ts +456 -0
  32. package/src/pantheon/v2-decision-contracts.ts +300 -0
  33. package/src/pantheon/v2-decision-egress.ts +203 -0
  34. package/src/pantheon/v2-decision-events.ts +180 -0
  35. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  36. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  37. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  38. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  39. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  40. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  41. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  42. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  43. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  44. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  45. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  46. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  47. package/src/pantheon/v2-decision-points.ts +242 -0
  48. package/src/pantheon/v2-decision-policy.ts +166 -0
  49. package/src/pantheon/v2-decision-premises.ts +146 -0
  50. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  51. package/src/pantheon/v2-decision-rank.ts +91 -0
  52. package/src/pantheon/v2-decision-registry.ts +391 -0
  53. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  54. package/src/pantheon/v2-decision-shadow.ts +123 -0
  55. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  56. package/src/pantheon/v2-decision-verify.ts +51 -0
  57. package/src/pantheon/v2-native-decisions.ts +365 -0
  58. package/src/pantheon/v2-tools.ts +24 -2
  59. package/src/plugin-v2.ts +360 -14
  60. package/src/plugins/tui/dist/tui-v2.js +3 -3
  61. package/src/plugins/tui/dist/tui.js +1 -1
  62. package/src/plugins/tui/package-lock.json +2 -2
  63. package/src/plugins/tui/package.json +1 -1
  64. package/src/pantheon/local-decision-provider-protocol.ts +0 -335
  65. package/src/pantheon/local-decision-provider.internal.ts +0 -260
@@ -0,0 +1,214 @@
1
+ /**
2
+ * V2 decision telemetry — allowlist sanitisation, closing defect D10.
3
+ *
4
+ * Telemetry must never carry prompt, response, user content, credentials or
5
+ * free-form text. The strongest way to guarantee that is not to scrub known
6
+ * keys but to accept only a small allowlist whose values are constrained to
7
+ * short tokens and bounded numbers:
8
+ *
9
+ * schemaVersion, point, decision, effect, reason, mode, durationMs, candidateCount
10
+ *
11
+ * Any other key is dropped and only a count is reported. Neither the key nor
12
+ * its value is ever copied into the result, so no attacker-controlled string
13
+ * reaches telemetry through a rejection path.
14
+ *
15
+ * `effect` is fixed to `'none'`. An event that claims anything else is rejected
16
+ * outright: this layer has no measured effect to report, and silently rewriting
17
+ * the claim would hide the caller's error.
18
+ *
19
+ * The sink is in-memory and bounded. It performs no I/O, so the offline harness
20
+ * can assert exactly what would be emitted.
21
+ */
22
+
23
+ import type { DecisionPointId } from './v2-decision-registry.ts'
24
+
25
+ export const TELEMETRY_SCHEMA_VERSION = 1
26
+ export const TELEMETRY_FIELDS = [
27
+ 'schemaVersion',
28
+ 'point',
29
+ 'decision',
30
+ 'effect',
31
+ 'reason',
32
+ 'mode',
33
+ 'durationMs',
34
+ 'candidateCount',
35
+ ] as const
36
+
37
+ export type TelemetryField = (typeof TELEMETRY_FIELDS)[number]
38
+ export type TelemetryMode = 'shadow' | 'active' | 'off' | 'migration'
39
+
40
+ export interface DecisionTelemetryEvent {
41
+ readonly schemaVersion: typeof TELEMETRY_SCHEMA_VERSION
42
+ readonly point: DecisionPointId
43
+ readonly decision: string
44
+ readonly effect: 'none'
45
+ readonly reason: string
46
+ readonly mode?: TelemetryMode
47
+ readonly durationMs?: number
48
+ readonly candidateCount?: number
49
+ }
50
+
51
+ export type TelemetryRejection = 'INVALID_INPUT' | 'MISSING_REQUIRED_FIELD' | 'EFFECT_NOT_MEASURED'
52
+
53
+ export type TelemetryResult =
54
+ | {
55
+ readonly ok: true
56
+ readonly event: DecisionTelemetryEvent
57
+ readonly droppedFieldCount: number
58
+ }
59
+ | {
60
+ readonly ok: false
61
+ readonly reasonCode: TelemetryRejection
62
+ readonly droppedFieldCount: number
63
+ }
64
+
65
+ const TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/
66
+ const POINT_ID = /^P(?:[1-9]|1[01])$/
67
+ const TELEMETRY_KEYS: ReadonlySet<string> = new Set(TELEMETRY_FIELDS)
68
+ const MODES: ReadonlySet<string> = new Set(['shadow', 'active', 'off', 'migration'])
69
+ const DURATION_MAX_MS = 60_000
70
+ const CANDIDATE_MAX = 10_000
71
+ function isRecord(value: unknown): value is Record<string, unknown> {
72
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
73
+ }
74
+
75
+ function isToken(value: unknown): value is string {
76
+ return typeof value === 'string' && TOKEN.test(value)
77
+ }
78
+
79
+ function isPointId(value: unknown): value is DecisionPointId {
80
+ return typeof value === 'string' && POINT_ID.test(value)
81
+ }
82
+
83
+ function rejected(reasonCode: TelemetryRejection, droppedFieldCount: number): TelemetryResult {
84
+ return { ok: false, reasonCode, droppedFieldCount }
85
+ }
86
+
87
+ /**
88
+ * Reduce an arbitrary record to the telemetry allowlist.
89
+ *
90
+ * Required survivors: `point`, `decision` and `reason`. `effect`, when present,
91
+ * must already be `'none'`; the output always carries `'none'`.
92
+ */
93
+ export function sanitizeTelemetry(input: unknown): TelemetryResult {
94
+ if (!isRecord(input)) return rejected('INVALID_INPUT', 0)
95
+
96
+ let droppedFieldCount = 0
97
+ const drop = (): void => {
98
+ droppedFieldCount += 1
99
+ }
100
+
101
+ let point: DecisionPointId | null = null
102
+ let decision: string | null = null
103
+ let reason: string | null = null
104
+ let mode: TelemetryMode | null = null
105
+ let durationMs: number | null = null
106
+ let candidateCount: number | null = null
107
+ let effectNotMeasured = false
108
+
109
+ for (const key of Object.keys(input).sort()) {
110
+ const value = input[key]
111
+ if (!TELEMETRY_KEYS.has(key)) {
112
+ drop()
113
+ continue
114
+ }
115
+ switch (key) {
116
+ case 'schemaVersion':
117
+ if (value !== TELEMETRY_SCHEMA_VERSION) drop()
118
+ break
119
+ case 'point':
120
+ if (isPointId(value)) point = value
121
+ else drop()
122
+ break
123
+ case 'decision':
124
+ if (isToken(value)) decision = value
125
+ else drop()
126
+ break
127
+ case 'reason':
128
+ if (isToken(value)) reason = value
129
+ else drop()
130
+ break
131
+ case 'mode':
132
+ if (typeof value === 'string' && MODES.has(value)) {
133
+ mode = value as TelemetryMode
134
+ } else {
135
+ drop()
136
+ }
137
+ break
138
+ case 'durationMs':
139
+ if (
140
+ typeof value === 'number' &&
141
+ Number.isFinite(value) &&
142
+ value >= 0 &&
143
+ value <= DURATION_MAX_MS
144
+ ) {
145
+ durationMs = value
146
+ } else {
147
+ drop()
148
+ }
149
+ break
150
+ case 'candidateCount':
151
+ if (
152
+ Number.isInteger(value) &&
153
+ (value as number) >= 0 &&
154
+ (value as number) <= CANDIDATE_MAX
155
+ ) {
156
+ candidateCount = value as number
157
+ } else {
158
+ drop()
159
+ }
160
+ break
161
+ case 'effect':
162
+ if (value === 'none') break
163
+ effectNotMeasured = true
164
+ drop()
165
+ break
166
+ default:
167
+ drop()
168
+ }
169
+ }
170
+
171
+ if (effectNotMeasured) return rejected('EFFECT_NOT_MEASURED', droppedFieldCount)
172
+ if (point === null || decision === null || reason === null) {
173
+ return rejected('MISSING_REQUIRED_FIELD', droppedFieldCount)
174
+ }
175
+
176
+ const event: DecisionTelemetryEvent = {
177
+ schemaVersion: TELEMETRY_SCHEMA_VERSION,
178
+ point,
179
+ decision,
180
+ effect: 'none',
181
+ reason,
182
+ ...(mode !== null ? { mode } : {}),
183
+ ...(durationMs !== null ? { durationMs } : {}),
184
+ ...(candidateCount !== null ? { candidateCount } : {}),
185
+ }
186
+ return { ok: true, event: Object.freeze(event), droppedFieldCount }
187
+ }
188
+
189
+ /** In-memory, bounded telemetry collector. No I/O, no network. */
190
+ export interface TelemetrySink {
191
+ emit(input: unknown): TelemetryResult
192
+ events(): readonly DecisionTelemetryEvent[]
193
+ size(): number
194
+ }
195
+
196
+ export function createTelemetrySink(maxEvents = 1_000): TelemetrySink {
197
+ if (!Number.isInteger(maxEvents) || maxEvents < 0 || maxEvents > 100_000) {
198
+ throw new RangeError('maxEvents must be an integer in 0..100000')
199
+ }
200
+ const collected: DecisionTelemetryEvent[] = []
201
+ return {
202
+ emit(input: unknown) {
203
+ const result = sanitizeTelemetry(input)
204
+ if (result.ok && collected.length < maxEvents) collected.push(result.event)
205
+ return result
206
+ },
207
+ events() {
208
+ return Object.freeze([...collected])
209
+ },
210
+ size() {
211
+ return collected.length
212
+ },
213
+ }
214
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * V2 verification contract — explicit verdicts, never inferred.
3
+ *
4
+ * `failed_to_respond` during mandatory verification is `BLOCK`; during advisory
5
+ * verification it is `FAIL`. Neither is ever `PASS`, and no scalar can stand in
6
+ * for a verdict.
7
+ */
8
+
9
+ export const VERIFY_VERDICTS = ['PASS', 'FAIL', 'BLOCK'] as const
10
+ export type VerifyVerdict = (typeof VERIFY_VERDICTS)[number]
11
+
12
+ export interface VerifyRequirement {
13
+ readonly id: string
14
+ readonly mandatory: boolean
15
+ }
16
+
17
+ export type VerifyReasonCode = 'VERDICT' | 'FAILED_TO_RESPOND' | 'UNRECOGNIZED_VERDICT'
18
+
19
+ export interface VerifyOutcome {
20
+ readonly requirementId: string
21
+ readonly verdict: VerifyVerdict
22
+ readonly reasonCode: VerifyReasonCode
23
+ readonly mandatory: boolean
24
+ }
25
+
26
+ /**
27
+ * Resolve a verification verdict.
28
+ *
29
+ * The verdict must be stated explicitly. `failed_to_respond` during a
30
+ * mandatory verification is `BLOCK`; during an advisory verification it is
31
+ * `FAIL`. Neither case is ever `PASS`, and no certainty scalar can stand in
32
+ * for a verdict.
33
+ */
34
+ export function resolveVerify(requirement: VerifyRequirement, response: unknown): VerifyOutcome {
35
+ const base = { requirementId: requirement.id, mandatory: requirement.mandatory }
36
+ if (typeof response === 'string') {
37
+ if (response === 'PASS' || response === 'FAIL' || response === 'BLOCK') {
38
+ return { ...base, verdict: response, reasonCode: 'VERDICT' }
39
+ }
40
+ return {
41
+ ...base,
42
+ verdict: requirement.mandatory ? 'BLOCK' : 'FAIL',
43
+ reasonCode: 'UNRECOGNIZED_VERDICT',
44
+ }
45
+ }
46
+ return {
47
+ ...base,
48
+ verdict: requirement.mandatory ? 'BLOCK' : 'FAIL',
49
+ reasonCode: 'FAILED_TO_RESPOND',
50
+ }
51
+ }
@@ -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,9 +48,11 @@
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'
55
+ import type { ShadowSink } from './v2-decision-shadow.ts'
54
56
  import { createV2VisionTool, type V2VisionRuntime } from './v2-vision.ts'
55
57
 
56
58
  // ─── Contract types ─────────────────────────────────────────────────────
@@ -420,6 +422,17 @@ async function executeModel(
420
422
 
421
423
  // ─── Tool set ───────────────────────────────────────────────────────────
422
424
 
425
+ /**
426
+ * Optional shadow sinks wired at tool registration.
427
+ *
428
+ * `complexity` belongs to P3, whose declared host surface is `tool.invoke`: the
429
+ * local selector's own input carries the complexity vector and gate status, so
430
+ * the observation is constructed where the payload can actually feed it.
431
+ */
432
+ export interface V2ToolShadowOptions {
433
+ readonly complexitySink?: ShadowSink
434
+ }
435
+
423
436
  /**
424
437
  * Build the V2 tool definitions.
425
438
  *
@@ -434,7 +447,11 @@ async function executeModel(
434
447
  * per-call definition with no construction-time I/O. A fresh descriptor array
435
448
  * prevents callers from mutating another registration's definitions.
436
449
  */
437
- export function createV2ToolDefinitions(visionRuntime?: V2VisionRuntime): V2ToolDef[] {
450
+ export function createV2ToolDefinitions(
451
+ visionRuntime?: V2VisionRuntime,
452
+ shadow: V2ToolShadowOptions = {},
453
+ jevRuntime?: V2JevDecisionRuntime,
454
+ ): V2ToolDef[] {
438
455
  const definitions: V2ToolDef[] = [
439
456
  {
440
457
  name: 'hashline_edit',
@@ -475,7 +492,12 @@ export function createV2ToolDefinitions(visionRuntime?: V2VisionRuntime): V2Tool
475
492
  execute: executeModel,
476
493
  },
477
494
  ]
478
- definitions.push(createV2LocalDecisionDefinition())
495
+ definitions.push(
496
+ createV2LocalDecisionDefinition({
497
+ ...(shadow.complexitySink === undefined ? {} : { sink: shadow.complexitySink }),
498
+ }),
499
+ )
479
500
  if (visionRuntime) definitions.push(createV2VisionTool(visionRuntime))
501
+ if (jevRuntime) definitions.push(createV2JevDecisionDefinition(jevRuntime))
480
502
  return definitions
481
503
  }