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,300 @@
1
+ /**
2
+ * V2 decision contracts — the offline surface of `ask`, `rank` and `verify`.
3
+ *
4
+ * This module is pure and deterministic: no adapter, no provider, no network.
5
+ * It validates the shape of a decision request and resolves an answer that a
6
+ * caller already obtained. Nothing here observes host state or applies a
7
+ * decision, so every result is replayable by the offline harness.
8
+ *
9
+ * Two rules are structural, not stylistic:
10
+ *
11
+ * - `refusal` is a successful terminal answer. It is reported with
12
+ * `status: 'refusal'` and never as an error.
13
+ * - A missing or unusable answer is reported as `failed_to_respond` and is
14
+ * never promoted to a verdict. During mandatory verification it becomes
15
+ * `BLOCK` (see `resolveVerify` in `v2-decision-verify.ts`).
16
+ *
17
+ * `ask` questions are independent of each other: {@link evaluateAskAnswer}
18
+ * receives exactly one question, so no earlier answer can supply context.
19
+ *
20
+ * `rank` and `verify` are re-exported from their own modules to keep each file
21
+ * focused on one primitive.
22
+ */
23
+
24
+ /** Maximum number of named labels in a `choice` question. */
25
+ export const ASK_CHOICE_MAX_LABELS = 255
26
+ /** Minimum number of ordinal levels in a `score` question. */
27
+ export const ASK_SCORE_MIN_LEVELS = 2
28
+ /** Maximum number of ordinal levels in a `score` question. */
29
+ export const ASK_SCORE_MAX_LEVELS = 10
30
+
31
+ const TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/
32
+
33
+ export interface NoulQuestion {
34
+ readonly mode: 'noul'
35
+ readonly id: string
36
+ readonly text: string
37
+ }
38
+
39
+ export interface ChoiceQuestion {
40
+ readonly mode: 'choice'
41
+ readonly id: string
42
+ readonly text: string
43
+ readonly labels: readonly string[]
44
+ }
45
+
46
+ export interface ScoreQuestion {
47
+ readonly mode: 'score'
48
+ readonly id: string
49
+ readonly text: string
50
+ readonly levels: number
51
+ }
52
+
53
+ export interface RefusalQuestion {
54
+ readonly mode: 'refusal'
55
+ readonly id: string
56
+ readonly text: string
57
+ }
58
+
59
+ /** Modes that carry a question payload; `refusal` is an answer, not a primitive. */
60
+ export type AskMode = NoulQuestion['mode'] | ChoiceQuestion['mode'] | ScoreQuestion['mode']
61
+ export type AskQuestion = NoulQuestion | ChoiceQuestion | ScoreQuestion | RefusalQuestion
62
+
63
+ export type AskValidationFailure =
64
+ | 'INVALID_SHAPE'
65
+ | 'UNKNOWN_MODE'
66
+ | 'MISSING_ID'
67
+ | 'MISSING_TEXT'
68
+ | 'EMPTY_LABELS'
69
+ | 'TOO_MANY_LABELS'
70
+ | 'DUPLICATE_LABEL'
71
+ | 'INVALID_LABEL'
72
+ | 'INVALID_LEVELS'
73
+
74
+ export type AskValidation =
75
+ | { readonly ok: true; readonly question: AskQuestion }
76
+ | { readonly ok: false; readonly code: AskValidationFailure; readonly detail: string }
77
+
78
+ export interface NoulAnswer {
79
+ readonly kind: 'noul'
80
+ readonly value: 0 | 1
81
+ }
82
+
83
+ export interface ChoiceAnswer {
84
+ readonly kind: 'choice'
85
+ readonly index: number
86
+ }
87
+
88
+ export interface ScoreAnswer {
89
+ readonly kind: 'score'
90
+ readonly level: number
91
+ }
92
+
93
+ export interface RefusalAnswer {
94
+ readonly kind: 'refusal'
95
+ }
96
+
97
+ export type AskAnswer = NoulAnswer | ChoiceAnswer | ScoreAnswer | RefusalAnswer
98
+
99
+ export type AskResolution =
100
+ | { readonly status: 'noul'; readonly questionId: string; readonly value: 0 | 1 }
101
+ | {
102
+ readonly status: 'choice'
103
+ readonly questionId: string
104
+ readonly index: number
105
+ readonly label: string
106
+ }
107
+ | { readonly status: 'score'; readonly questionId: string; readonly level: number }
108
+ | {
109
+ readonly status: 'refusal'
110
+ readonly questionId: string
111
+ readonly reasonCode: 'REFUSAL_MODE' | 'ANSWERED_REFUSAL'
112
+ }
113
+ | {
114
+ readonly status: 'failed'
115
+ readonly questionId: string
116
+ readonly reasonCode: 'FAILED_TO_RESPOND' | 'INVALID_ANSWER' | 'OUT_OF_RANGE'
117
+ }
118
+ | {
119
+ readonly status: 'invalid_question'
120
+ readonly questionId: string
121
+ readonly reasonCode: AskValidationFailure
122
+ }
123
+
124
+ function isRecord(value: unknown): value is Record<string, unknown> {
125
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
126
+ }
127
+
128
+ function isNonEmptyString(value: unknown): value is string {
129
+ return typeof value === 'string' && value.trim().length > 0
130
+ }
131
+
132
+ function isToken(value: unknown): value is string {
133
+ return typeof value === 'string' && TOKEN.test(value)
134
+ }
135
+
136
+ function hasControlCharacter(value: string): boolean {
137
+ for (const character of value) {
138
+ const code = character.codePointAt(0) ?? 0
139
+ if (code < 0x20 || code === 0x7f) return true
140
+ }
141
+ return false
142
+ }
143
+
144
+ function isSingleLineLabel(value: unknown): value is string {
145
+ return isNonEmptyString(value) && !hasControlCharacter(value)
146
+ }
147
+
148
+ function questionIdOf(candidate: unknown): string {
149
+ if (isRecord(candidate) && typeof candidate.id === 'string') return candidate.id
150
+ return ''
151
+ }
152
+
153
+ /**
154
+ * Validate one `ask` question.
155
+ *
156
+ * `choice` accepts 1–255 unique single-line labels; `score` accepts 2–10
157
+ * ordinal levels; `noul` is binary by construction; `refusal` carries no
158
+ * payload. A question is never re-interpreted: the mode must match the shape.
159
+ */
160
+ export function validateAsk(candidate: unknown): AskValidation {
161
+ if (!isRecord(candidate)) {
162
+ return { ok: false, code: 'INVALID_SHAPE', detail: 'question must be an object' }
163
+ }
164
+ const mode = candidate.mode
165
+ if (mode !== 'noul' && mode !== 'choice' && mode !== 'score' && mode !== 'refusal') {
166
+ return { ok: false, code: 'UNKNOWN_MODE', detail: 'unrecognized ask mode' }
167
+ }
168
+ if (!isToken(candidate.id)) {
169
+ return { ok: false, code: 'MISSING_ID', detail: 'id must be a short token' }
170
+ }
171
+ if (!isNonEmptyString(candidate.text)) {
172
+ return { ok: false, code: 'MISSING_TEXT', detail: 'text must be non-empty' }
173
+ }
174
+ const id = candidate.id
175
+ const text = candidate.text
176
+
177
+ if (mode === 'noul') return { ok: true, question: { mode, id, text } }
178
+ if (mode === 'refusal') return { ok: true, question: { mode, id, text } }
179
+
180
+ if (mode === 'score') {
181
+ const levels = candidate.levels
182
+ if (
183
+ !Number.isInteger(levels) ||
184
+ (levels as number) < ASK_SCORE_MIN_LEVELS ||
185
+ (levels as number) > ASK_SCORE_MAX_LEVELS
186
+ ) {
187
+ return {
188
+ ok: false,
189
+ code: 'INVALID_LEVELS',
190
+ detail: `levels must be an integer in ${ASK_SCORE_MIN_LEVELS}..${ASK_SCORE_MAX_LEVELS}`,
191
+ }
192
+ }
193
+ return { ok: true, question: { mode, id, text, levels: levels as number } }
194
+ }
195
+
196
+ const labels = candidate.labels
197
+ if (!Array.isArray(labels) || labels.length === 0) {
198
+ return { ok: false, code: 'EMPTY_LABELS', detail: 'choice needs at least one label' }
199
+ }
200
+ if (labels.length > ASK_CHOICE_MAX_LABELS) {
201
+ return {
202
+ ok: false,
203
+ code: 'TOO_MANY_LABELS',
204
+ detail: `choice accepts at most ${ASK_CHOICE_MAX_LABELS} labels`,
205
+ }
206
+ }
207
+ const seen = new Set<string>()
208
+ const normalized: string[] = []
209
+ for (const label of labels) {
210
+ if (!isSingleLineLabel(label)) {
211
+ return { ok: false, code: 'INVALID_LABEL', detail: 'labels must be single-line non-empty' }
212
+ }
213
+ const trimmed = label.trim()
214
+ if (seen.has(trimmed)) {
215
+ return { ok: false, code: 'DUPLICATE_LABEL', detail: 'labels must be unique' }
216
+ }
217
+ seen.add(trimmed)
218
+ normalized.push(trimmed)
219
+ }
220
+ return { ok: true, question: { mode, id, text, labels: normalized } }
221
+ }
222
+
223
+ /** Escape a label so it cannot break the rendered `index. "label"` line. */
224
+ export function escapeAskLabel(label: string): string {
225
+ return label.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
226
+ }
227
+
228
+ /** Render validated choice labels as 1-based numbered lines. */
229
+ export function renderChoiceLabels(question: ChoiceQuestion): readonly string[] {
230
+ return question.labels.map((label, index) => `${index + 1}. "${escapeAskLabel(label)}"`)
231
+ }
232
+
233
+ /**
234
+ * Resolve one answer against exactly one question.
235
+ *
236
+ * A refusal answer is success for every mode. Anything unrecognized is
237
+ * `failed`, never coerced into the nearest valid value.
238
+ */
239
+ export function evaluateAskAnswer(question: unknown, answer: unknown): AskResolution {
240
+ const validation = validateAsk(question)
241
+ if (!validation.ok) {
242
+ return {
243
+ status: 'invalid_question',
244
+ questionId: questionIdOf(question),
245
+ reasonCode: validation.code,
246
+ }
247
+ }
248
+ const spec = validation.question
249
+ if (answer === undefined || answer === null) {
250
+ return { status: 'failed', questionId: spec.id, reasonCode: 'FAILED_TO_RESPOND' }
251
+ }
252
+ if (!isRecord(answer) || typeof answer.kind !== 'string') {
253
+ return { status: 'failed', questionId: spec.id, reasonCode: 'INVALID_ANSWER' }
254
+ }
255
+
256
+ if (answer.kind === 'refusal') {
257
+ return {
258
+ status: 'refusal',
259
+ questionId: spec.id,
260
+ reasonCode: spec.mode === 'refusal' ? 'REFUSAL_MODE' : 'ANSWERED_REFUSAL',
261
+ }
262
+ }
263
+ if (spec.mode === 'refusal') {
264
+ return { status: 'failed', questionId: spec.id, reasonCode: 'INVALID_ANSWER' }
265
+ }
266
+
267
+ if (spec.mode === 'noul') {
268
+ if (answer.kind !== 'noul' || (answer.value !== 0 && answer.value !== 1)) {
269
+ return { status: 'failed', questionId: spec.id, reasonCode: 'INVALID_ANSWER' }
270
+ }
271
+ return { status: 'noul', questionId: spec.id, value: answer.value }
272
+ }
273
+
274
+ if (spec.mode === 'choice') {
275
+ if (answer.kind !== 'choice' || !Number.isInteger(answer.index)) {
276
+ return { status: 'failed', questionId: spec.id, reasonCode: 'INVALID_ANSWER' }
277
+ }
278
+ const index = answer.index as number
279
+ if (index < 1 || index > spec.labels.length) {
280
+ return { status: 'failed', questionId: spec.id, reasonCode: 'OUT_OF_RANGE' }
281
+ }
282
+ const label = spec.labels[index - 1]
283
+ if (label === undefined) {
284
+ return { status: 'failed', questionId: spec.id, reasonCode: 'OUT_OF_RANGE' }
285
+ }
286
+ return { status: 'choice', questionId: spec.id, index, label }
287
+ }
288
+
289
+ if (answer.kind !== 'score' || !Number.isInteger(answer.level)) {
290
+ return { status: 'failed', questionId: spec.id, reasonCode: 'INVALID_ANSWER' }
291
+ }
292
+ const level = answer.level as number
293
+ if (level < 1 || level > spec.levels) {
294
+ return { status: 'failed', questionId: spec.id, reasonCode: 'OUT_OF_RANGE' }
295
+ }
296
+ return { status: 'score', questionId: spec.id, level }
297
+ }
298
+
299
+ export * from './v2-decision-rank.ts'
300
+ export * from './v2-decision-verify.ts'
@@ -0,0 +1,203 @@
1
+ /**
2
+ * V2 decision egress — opt-in only, default OFF (PLAN §7 Fase 7, D11).
3
+ *
4
+ * Two facts this module makes checkable instead of assumed:
5
+ *
6
+ * 1. **The default is off, and "off" is a value.** Every refusal below is a
7
+ * named reason, not a missing return. Absent configuration is `NO_CONFIG`,
8
+ * which is deliberately distinct from `DISABLED`: a user who never wrote a
9
+ * file has not opted in *or* out of anything, and either way nothing egresses.
10
+ *
11
+ * 2. **The provider endpoints are retained inert (UNWIRED).** The fixed
12
+ * OpenAI/TypeSafe URLs in the private provider matrix stay where they are and
13
+ * are not wired by this surface. This module asserts no transport of its own
14
+ * and does not claim the transport was removed — only that it is not wired
15
+ * here. The removed third-party gateway is not a provider id, not a model row
16
+ * and not a budget row of the decision router; that absence is asserted from
17
+ * the config maps in the egress tests, not from this module.
18
+ *
19
+ * 3. **A declared endpoint that is not provably wired must SAY so.** Every
20
+ * endpoint carries an explicit wire status, and
21
+ * {@link findUnverifiedEgressEndpoints} returns the ones that are neither
22
+ * declared `unwired` nor exercised by a real path. The exercised-path list is
23
+ * empty and must stay honest: no probe issued a decision request, so no
24
+ * endpoint can be marked `wired` without failing that check. Verification of
25
+ * this surface therefore covers only the paths a probe exercised — none —
26
+ * and the absence of a probe is recorded, not inferred as safety. Of the
27
+ * ten `permission.evaluate` paths, `.egress` is unreachable in the probed
28
+ * host: a tool declaring that permission registers but is never advertised to
29
+ * the provider (PROBE-F §3.9).
30
+ *
31
+ * Selection cardinality is delegated to `explainUserDecisionRouterAutoSelection`
32
+ * (D5), so 0, 1 and 2+ eligible candidates are three distinct outcomes here too
33
+ * and an ambiguous Auto selection can never be read as "the single one".
34
+ *
35
+ * The gate is pure: no clock, no filesystem, no network, no ledger write. The
36
+ * caller supplies the configuration and the cap-eligible candidates.
37
+ */
38
+ import {
39
+ type AutoSelectionExplanation,
40
+ explainUserDecisionRouterAutoSelection,
41
+ migrateUserDecisionRouterConfig,
42
+ type UserDecisionRouterCandidate,
43
+ type UserDecisionRouterConfig,
44
+ } from '../../scripts/install/decision-router-config.mjs'
45
+
46
+ /** Egress is off unless every gate below is explicitly satisfied. */
47
+ export const V2_DECISION_EGRESS_DEFAULT = 'off' as const
48
+
49
+ export type V2DecisionEgressOffReason =
50
+ | 'NO_CONFIG'
51
+ | 'DISABLED'
52
+ | 'LOCAL_SELECTION'
53
+ | 'CONSENT_MISSING'
54
+ | 'NO_ELIGIBLE_CANDIDATE'
55
+ | 'AMBIGUOUS_CANDIDATES'
56
+ | 'CONFIG_UNAVAILABLE'
57
+
58
+ export type V2DecisionEgressState =
59
+ | { mode: 'off'; reason: V2DecisionEgressOffReason; candidates: number }
60
+ | {
61
+ mode: 'opt-in'
62
+ reason: 'EXPLICIT_OPT_IN'
63
+ provider: string
64
+ candidate: UserDecisionRouterCandidate
65
+ }
66
+
67
+ export type V2DecisionEgressWireStatus = 'unwired' | 'wired'
68
+
69
+ interface DeclaredEgressEndpoint {
70
+ readonly url: string
71
+ readonly wireStatus: V2DecisionEgressWireStatus
72
+ }
73
+
74
+ /**
75
+ * Fixed endpoints retained from the private provider matrix, each with its own
76
+ * wire status. `unwired` is about THIS surface: phase 7 adds no transport, and
77
+ * no code path here can issue a request. It is not a statement that the
78
+ * endpoint strings were removed.
79
+ */
80
+ const DECLARED_EGRESS_ENDPOINTS: readonly DeclaredEgressEndpoint[] = Object.freeze([
81
+ { url: 'https://api.openai.com/v1/decisions', wireStatus: 'unwired' },
82
+ { url: 'https://api.typesafe.ai/v1/systemone', wireStatus: 'unwired' },
83
+ { url: 'https://opencode.ai/inference/systemone/v1/systemone', wireStatus: 'unwired' },
84
+ ])
85
+
86
+ /**
87
+ * Paths a probe actually exercised end to end. Empty, and that is the claim:
88
+ * no probe issued a decision request, so no endpoint may be reported as wired.
89
+ * Adding an entry here is a measurement claim and needs a probe artifact.
90
+ */
91
+ export const V2_DECISION_EGRESS_EXERCISED_PATHS: readonly string[] = Object.freeze([])
92
+
93
+ /** Per-endpoint wire status. Derived from the declaration, never hand-kept. */
94
+ export const V2_DECISION_EGRESS_ENDPOINT_WIRE_STATUS: Readonly<
95
+ Record<string, V2DecisionEgressWireStatus>
96
+ > = Object.freeze(
97
+ Object.fromEntries(DECLARED_EGRESS_ENDPOINTS.map(({ url, wireStatus }) => [url, wireStatus])),
98
+ )
99
+
100
+ /**
101
+ * Endpoints whose wire status is not verifiable: neither declared `unwired` nor
102
+ * covered by an exercised path. An unknown or missing status is unverified too —
103
+ * silence is not evidence of inertia.
104
+ */
105
+ export function findUnverifiedEgressEndpoints(
106
+ endpoints: readonly string[],
107
+ endpointWireStatus: Readonly<Record<string, V2DecisionEgressWireStatus>>,
108
+ exercisedPaths: readonly string[] = V2_DECISION_EGRESS_EXERCISED_PATHS,
109
+ ): readonly string[] {
110
+ const exercised = new Set(exercisedPaths)
111
+ return Object.freeze(
112
+ endpoints.filter((endpoint) => {
113
+ const status = endpointWireStatus[endpoint]
114
+ if (status === 'unwired') return false
115
+ if (status === 'wired') return !exercised.has(endpoint)
116
+ return true
117
+ }),
118
+ )
119
+ }
120
+
121
+ export const V2_DECISION_EGRESS_TRANSPORT = Object.freeze({
122
+ wireStatus: 'unwired',
123
+ wired: false,
124
+ note:
125
+ 'Endpoints are retained inert (UNWIRED) in this surface. No transport, retry or fallback ' +
126
+ 'exists here, and this module never claims the transport was removed. Verification covers ' +
127
+ 'only the paths a probe exercised — none — and every declared endpoint carries an explicit ' +
128
+ 'wire status so an unverified endpoint fails a test instead of passing silently.',
129
+ endpoints: Object.freeze(DECLARED_EGRESS_ENDPOINTS.map(({ url }) => url)),
130
+ endpointWireStatus: V2_DECISION_EGRESS_ENDPOINT_WIRE_STATUS,
131
+ })
132
+
133
+ /**
134
+ * Resolve the egress posture of a configuration.
135
+ *
136
+ * Order is fixed so the reason is reproducible: disabled, then local selection,
137
+ * then consent, then candidate cardinality. Every branch that is not
138
+ * `EXPLICIT_OPT_IN` returns `mode: 'off'`.
139
+ */
140
+ export function resolveV2DecisionEgress(
141
+ config: unknown,
142
+ capEligibleCandidates: readonly UserDecisionRouterCandidate[] = [],
143
+ ): V2DecisionEgressState {
144
+ const preference: UserDecisionRouterConfig = migrateUserDecisionRouterConfig(config)
145
+ const candidates = preference.enabled_candidates.length
146
+ if (!preference.enabled) {
147
+ return { mode: 'off', reason: 'DISABLED', candidates }
148
+ }
149
+ if (preference.selection.mode === 'local') {
150
+ return { mode: 'off', reason: 'LOCAL_SELECTION', candidates }
151
+ }
152
+ if (!preference.egress_consent) {
153
+ return { mode: 'off', reason: 'CONSENT_MISSING', candidates }
154
+ }
155
+
156
+ if (preference.selection.mode === 'auto') {
157
+ const explained: AutoSelectionExplanation = explainUserDecisionRouterAutoSelection(
158
+ preference,
159
+ capEligibleCandidates,
160
+ )
161
+ if (explained.outcome === 'ambiguous') {
162
+ return { mode: 'off', reason: 'AMBIGUOUS_CANDIDATES', candidates: explained.count }
163
+ }
164
+ if (explained.outcome !== 'single') {
165
+ return { mode: 'off', reason: 'NO_ELIGIBLE_CANDIDATE', candidates: 0 }
166
+ }
167
+ return {
168
+ mode: 'opt-in',
169
+ reason: 'EXPLICIT_OPT_IN',
170
+ provider: explained.candidate.provider,
171
+ candidate: explained.candidate,
172
+ }
173
+ }
174
+
175
+ const selected = preference.selection
176
+ const match = capEligibleCandidates.find(
177
+ (candidate) => candidate.provider === selected.provider && candidate.model === selected.model,
178
+ )
179
+ if (match === undefined) {
180
+ return { mode: 'off', reason: 'NO_ELIGIBLE_CANDIDATE', candidates }
181
+ }
182
+ return {
183
+ mode: 'opt-in',
184
+ reason: 'EXPLICIT_OPT_IN',
185
+ provider: selected.provider,
186
+ candidate: match,
187
+ }
188
+ }
189
+
190
+ /** True only for an explicit opt-in. Any other state means zero requests. */
191
+ export function v2DecisionEgressMaySend(state: V2DecisionEgressState): boolean {
192
+ return state.mode === 'opt-in' && state.reason === 'EXPLICIT_OPT_IN'
193
+ }
194
+
195
+ /**
196
+ * The invariant a caller must not be able to violate by accident: a state that
197
+ * is not an explicit opt-in cannot be converted into permission.
198
+ */
199
+ export function assertV2DecisionEgressOptIn(state: V2DecisionEgressState): void {
200
+ if (!v2DecisionEgressMaySend(state)) {
201
+ throw new Error(`Decision egress is off (${state.mode === 'off' ? state.reason : 'unknown'})`)
202
+ }
203
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * V2 event-consumption contract — the only shape P7 and future event consumers
3
+ * may use (PLAN §5.2).
4
+ *
5
+ * Measured facts this module is built on:
6
+ *
7
+ * - F-11: `ctx.event.subscribe` takes ONE argument and returns an async
8
+ * iterable. A callback passed as an argument is never invoked (0/4 runs),
9
+ * and a type argument does not filter on the server.
10
+ * - F-13: the envelope is `{ id, created, type, durable, location?, data }`;
11
+ * `data.sessionID` is the session carrier for `session.*` types.
12
+ *
13
+ * Therefore:
14
+ *
15
+ * 1. `subscribe({ signal })` is called with exactly one argument and the
16
+ * result is consumed with `for await`.
17
+ * 2. Type filtering happens here, on `event.type`, not on the host.
18
+ * 3. The session id is read from `event.data.sessionID` and nowhere else.
19
+ * The unmetered legacy envelope field is never read.
20
+ * 4. Consumption ends through `AbortSignal`; there is no dispose handle.
21
+ * 5. The measured host is 2.2.5. Absence of `session.idle` and
22
+ * `session.compacted` there is not a claim about other host versions.
23
+ */
24
+
25
+ export const P7_TURN_END_EVENT_TYPE = 'session.execution.succeeded'
26
+
27
+ export interface HostEventEnvelope {
28
+ readonly id?: unknown
29
+ readonly created?: unknown
30
+ readonly type?: unknown
31
+ readonly durable?: unknown
32
+ readonly location?: unknown
33
+ readonly data?: unknown
34
+ }
35
+
36
+ export interface EventSubscribeOptions {
37
+ readonly signal: AbortSignal
38
+ }
39
+
40
+ export interface DecisionEventSource {
41
+ subscribe(options: EventSubscribeOptions): AsyncIterable<HostEventEnvelope>
42
+ }
43
+
44
+ export interface DecisionEvent {
45
+ readonly type: string
46
+ readonly sessionID: string
47
+ }
48
+
49
+ export type EventConsumptionFailure = 'SUBSCRIBE_FAILED' | 'STREAM_FAILED'
50
+
51
+ export interface EventConsumptionOptions {
52
+ /** Event types the consumer cares about. Filtering is client-side. */
53
+ readonly types: readonly string[]
54
+ readonly signal: AbortSignal
55
+ readonly onEvent: (event: DecisionEvent) => void
56
+ /** Upper bound so a harness run cannot consume an unbounded stream. */
57
+ readonly maxEvents?: number
58
+ }
59
+
60
+ export interface EventConsumptionSummary {
61
+ readonly delivered: number
62
+ readonly matched: number
63
+ readonly skippedType: number
64
+ readonly skippedMissingSession: number
65
+ readonly handlerErrors: number
66
+ readonly aborted: boolean
67
+ readonly failure: EventConsumptionFailure | null
68
+ }
69
+
70
+ const DEFAULT_MAX_EVENTS = 10_000
71
+ const TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
72
+
73
+ function isRecord(value: unknown): value is Record<string, unknown> {
74
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
75
+ }
76
+
77
+ function emptySummary(overrides: Partial<EventConsumptionSummary> = {}): EventConsumptionSummary {
78
+ return {
79
+ delivered: 0,
80
+ matched: 0,
81
+ skippedType: 0,
82
+ skippedMissingSession: 0,
83
+ handlerErrors: 0,
84
+ aborted: false,
85
+ failure: null,
86
+ ...overrides,
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Read the measured carrier only: `data.sessionID`.
92
+ *
93
+ * This function deliberately touches two properties (`data`, `data.sessionID`);
94
+ * a test wraps the envelope in a proxy whose other fields throw, proving the
95
+ * legacy field is never read.
96
+ */
97
+ export function readEventSessionID(envelope: unknown): string | null {
98
+ if (!isRecord(envelope)) return null
99
+ const data = envelope.data
100
+ if (!isRecord(data)) return null
101
+ const sessionID = data.sessionID
102
+ if (typeof sessionID !== 'string') return null
103
+ const trimmed = sessionID.trim()
104
+ return trimmed.length > 0 ? trimmed : null
105
+ }
106
+
107
+ /**
108
+ * Consume an event stream under the contract above.
109
+ *
110
+ * The returned summary is diagnostic only; nothing in it changes admission.
111
+ * A missing session carrier is counted, never guessed.
112
+ */
113
+ export async function consumeDecisionEvents(
114
+ source: DecisionEventSource,
115
+ options: EventConsumptionOptions,
116
+ ): Promise<EventConsumptionSummary> {
117
+ const signal = options.signal
118
+ if (signal.aborted) return emptySummary({ aborted: true })
119
+
120
+ const wanted = new Set(options.types.filter((type) => TOKEN.test(type)))
121
+ const maxEvents =
122
+ options.maxEvents !== undefined && Number.isInteger(options.maxEvents) && options.maxEvents > 0
123
+ ? options.maxEvents
124
+ : DEFAULT_MAX_EVENTS
125
+
126
+ let stream: AsyncIterable<HostEventEnvelope>
127
+ try {
128
+ stream = source.subscribe({ signal })
129
+ } catch {
130
+ return emptySummary({ failure: 'SUBSCRIBE_FAILED' })
131
+ }
132
+
133
+ let delivered = 0
134
+ let matched = 0
135
+ let skippedType = 0
136
+ let skippedMissingSession = 0
137
+ let handlerErrors = 0
138
+ let aborted = false
139
+ let failure: EventConsumptionFailure | null = null
140
+
141
+ try {
142
+ for await (const envelope of stream) {
143
+ if (signal.aborted) {
144
+ aborted = true
145
+ break
146
+ }
147
+ delivered += 1
148
+ const type = isRecord(envelope) ? envelope.type : undefined
149
+ if (typeof type !== 'string' || !wanted.has(type)) {
150
+ skippedType += 1
151
+ } else {
152
+ const sessionID = readEventSessionID(envelope)
153
+ if (sessionID === null) {
154
+ skippedMissingSession += 1
155
+ } else {
156
+ matched += 1
157
+ try {
158
+ options.onEvent(Object.freeze({ type, sessionID }))
159
+ } catch {
160
+ handlerErrors += 1
161
+ }
162
+ }
163
+ }
164
+ if (delivered >= maxEvents) break
165
+ }
166
+ } catch {
167
+ if (signal.aborted) aborted = true
168
+ else failure = 'STREAM_FAILED'
169
+ }
170
+
171
+ return emptySummary({
172
+ delivered,
173
+ matched,
174
+ skippedType,
175
+ skippedMissingSession,
176
+ handlerErrors,
177
+ aborted,
178
+ failure,
179
+ })
180
+ }