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

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,260 +0,0 @@
1
- /**
2
- * Private per-turn provider runner.
3
- *
4
- * Egress boundary: this module never accepts a fetch implementation, base URL,
5
- * environment, configuration, or ledger from a caller. It reads the user-level
6
- * configuration and ledger itself, uses fixed endpoints, and performs at most
7
- * one POST with no redirect, retry, failover, or fan-out.
8
- *
9
- * The user-level configuration is the source of truth: `enabled`,
10
- * `egress_consent`, one cap-valid candidate, a confirmed period, and positive
11
- * caps. The only caller-provided capability is the host's kill-switch
12
- * (`ctx.permission.assert`), which is asked after the config gate passes and
13
- * must not deny. A missing or denying gate means no network call at all.
14
- */
15
- import {
16
- openLocalDecisionBudgetLedger,
17
- resolveLocalDecisionBudgetDbPath,
18
- } from './local-decision-budget.ts'
19
- import {
20
- assertDecisionEgressPermission,
21
- buildDecisionEgressRequest,
22
- type PermissionAssert,
23
- resolveDecisionEgressConsent,
24
- } from './local-decision-egress-gate.ts'
25
- import {
26
- type DecisionProviderId,
27
- PROVIDER_MAX_RESPONSE_BYTES,
28
- PROVIDER_REQUEST_TIMEOUT_MS,
29
- } from './local-decision-provider-matrix.ts'
30
- import {
31
- buildProviderRequest,
32
- type DecisionPayload,
33
- parseProviderDecision,
34
- } from './local-decision-provider-protocol.ts'
35
- import { verifyProviderUsageForReservation } from './local-decision-usage-evidence.internal.ts'
36
-
37
- export type {
38
- DecisionProtocol,
39
- DecisionProviderAdapter,
40
- DecisionProviderId,
41
- } from './local-decision-provider-matrix.ts'
42
- export { DECISION_PROVIDER_ADAPTERS } from './local-decision-provider-matrix.ts'
43
- export type {
44
- DecisionPayload,
45
- DecisionPayloadInput,
46
- } from './local-decision-provider-protocol.ts'
47
- export {
48
- buildDecisionPayload,
49
- parseProviderDecision,
50
- } from './local-decision-provider-protocol.ts'
51
-
52
- export type ProviderRunReason =
53
- | 'PROVIDER_RECOMMENDATION'
54
- | 'PROVIDER_ABSTAIN'
55
- | 'DISABLED'
56
- | 'CONFIG_UNAVAILABLE'
57
- | 'CONSENT_MISSING'
58
- | 'NO_ELIGIBLE_CANDIDATE'
59
- | 'CAP_OR_PERIOD_DENIED'
60
- | 'PERMISSION_UNAVAILABLE'
61
- | 'PERMISSION_DENIED'
62
- | 'CREDENTIAL_MISSING'
63
- | 'RESERVATION_DENIED'
64
- | 'TRANSPORT_FAILED'
65
- | 'USAGE_UNRECONCILED'
66
- | 'INVALID_PROVIDER_RESPONSE'
67
-
68
- export interface ProviderRunResult {
69
- status: 'decided' | 'abstain' | 'fallback'
70
- skillIds: string[]
71
- agent: string | null
72
- provider: DecisionProviderId | null
73
- reasonCode: ProviderRunReason
74
- }
75
-
76
- export interface ProviderRunInput {
77
- payload: DecisionPayload | null
78
- /** Host capability only; never a fetch, config, env, or ledger injection. */
79
- permissionAssert?: PermissionAssert | undefined
80
- sessionID: string
81
- messageID: string
82
- }
83
-
84
- function fallback(reasonCode: ProviderRunReason): ProviderRunResult {
85
- return { status: 'fallback', skillIds: [], agent: null, provider: null, reasonCode }
86
- }
87
-
88
- /**
89
- * Run the one-and-only authorized provider decision for a turn. Any missing
90
- * gate, cap, credential, usage proof, or valid response falls back to local.
91
- */
92
- export async function runProviderDecision(input: ProviderRunInput): Promise<ProviderRunResult> {
93
- if (
94
- input.payload === null ||
95
- typeof input.sessionID !== 'string' ||
96
- input.sessionID.trim().length === 0 ||
97
- typeof input.messageID !== 'string' ||
98
- input.messageID.trim().length === 0
99
- ) {
100
- return fallback('CONFIG_UNAVAILABLE')
101
- }
102
-
103
- // Config first: an invalid configuration is not worth an interactive host
104
- // prompt, and the host must never be asked to approve what the user's own
105
- // configuration already forbids.
106
- const consent = resolveDecisionEgressConsent()
107
- if (!consent.ok) return fallback(consent.reasonCode)
108
- const { provider, adapter } = consent.selected
109
-
110
- if (typeof input.permissionAssert !== 'function') return fallback('PERMISSION_UNAVAILABLE')
111
- const assertion = await assertDecisionEgressPermission(
112
- input.permissionAssert,
113
- buildDecisionEgressRequest({
114
- sessionID: input.sessionID,
115
- messageID: input.messageID,
116
- endpoint: adapter.endpoint,
117
- }),
118
- )
119
- if (assertion === 'deny') return fallback('PERMISSION_DENIED')
120
-
121
- const credential = readCredential(adapter.credentialEnv)
122
- if (credential === null) return fallback('CREDENTIAL_MISSING')
123
- if (typeof globalThis.fetch !== 'function') return fallback('TRANSPORT_FAILED')
124
-
125
- const body = buildProviderRequest(provider, input.payload)
126
- if (body === null) return fallback('NO_ELIGIBLE_CANDIDATE')
127
-
128
- const ledger = openLocalDecisionBudgetLedger({ dbPath: resolveLocalDecisionBudgetDbPath() })
129
- try {
130
- let reservation: ReturnType<typeof ledger.reserve>
131
- try {
132
- reservation = ledger.reserve(adapter.accountingProvider, adapter.model)
133
- } catch {
134
- return fallback('RESERVATION_DENIED')
135
- }
136
- if (reservation.status !== 'reserved') return fallback('RESERVATION_DENIED')
137
-
138
- let response: Response
139
- try {
140
- response = await globalThis.fetch(adapter.endpoint, {
141
- method: 'POST',
142
- headers: {
143
- authorization: `Bearer ${credential}`,
144
- 'content-type': 'application/json',
145
- },
146
- body: JSON.stringify(body),
147
- redirect: 'error',
148
- referrerPolicy: 'no-referrer',
149
- signal: AbortSignal.timeout(PROVIDER_REQUEST_TIMEOUT_MS),
150
- })
151
- } catch {
152
- return fallback('TRANSPORT_FAILED')
153
- }
154
- if (!response.ok) return fallback('TRANSPORT_FAILED')
155
-
156
- let responseBody: unknown
157
- try {
158
- responseBody = await readBoundedResponseJson(response)
159
- } catch {
160
- return fallback('TRANSPORT_FAILED')
161
- }
162
-
163
- const evidence = verifyProviderUsageForReservation(
164
- {
165
- reservationId: reservation.reservationId,
166
- provider: adapter.accountingProvider,
167
- model: adapter.model,
168
- period: reservation.period,
169
- },
170
- responseBody,
171
- )
172
- if (evidence === null) return fallback('USAGE_UNRECONCILED')
173
- const reconciliation = ledger.reconcileVerified(reservation.reservationId, evidence)
174
- if (reconciliation.status !== 'reconciled' || reconciliation.frozen) {
175
- return fallback('USAGE_UNRECONCILED')
176
- }
177
-
178
- const decision = parseProviderDecision(provider, responseBody, input.payload)
179
- if (decision.status === 'invalid') return fallback('INVALID_PROVIDER_RESPONSE')
180
- if (decision.status === 'abstain') {
181
- return {
182
- status: 'abstain',
183
- skillIds: [],
184
- agent: null,
185
- provider,
186
- reasonCode: 'PROVIDER_ABSTAIN',
187
- }
188
- }
189
- return {
190
- status: 'decided',
191
- skillIds: decision.skillIds,
192
- agent: decision.agent,
193
- provider,
194
- reasonCode: 'PROVIDER_RECOMMENDATION',
195
- }
196
- } finally {
197
- ledger.close()
198
- }
199
- }
200
-
201
- function readCredential(name: string): string | null {
202
- try {
203
- const credential = process.env[name]
204
- return typeof credential === 'string' &&
205
- credential.length > 0 &&
206
- credential.trim() === credential
207
- ? credential
208
- : null
209
- } catch {
210
- return null
211
- }
212
- }
213
-
214
- async function readBoundedResponseJson(response: Response): Promise<unknown> {
215
- const body = response.body
216
- const contentLength = response.headers.get('content-length')
217
- if (contentLength !== null) {
218
- const parsedLength = Number(contentLength)
219
- if (
220
- !/^\d+$/.test(contentLength) ||
221
- !Number.isSafeInteger(parsedLength) ||
222
- parsedLength > PROVIDER_MAX_RESPONSE_BYTES
223
- ) {
224
- await body?.cancel(new RangeError('Provider response exceeds the size limit')).catch(() => {})
225
- throw new RangeError('Provider response exceeds the size limit')
226
- }
227
- }
228
- if (body === null) throw new TypeError('Provider response body is missing')
229
-
230
- const reader = body.getReader()
231
- const chunks: Uint8Array[] = []
232
- let totalBytes = 0
233
- try {
234
- while (true) {
235
- const { done, value } = await reader.read()
236
- if (done) break
237
- totalBytes += value.byteLength
238
- if (totalBytes > PROVIDER_MAX_RESPONSE_BYTES) {
239
- const error = new RangeError('Provider response exceeds the size limit')
240
- await reader.cancel(error).catch(() => {})
241
- throw error
242
- }
243
- chunks.push(value)
244
- }
245
- } catch (error) {
246
- await reader.cancel(error).catch(() => {})
247
- throw error
248
- } finally {
249
- reader.releaseLock()
250
- }
251
-
252
- const bytes = new Uint8Array(totalBytes)
253
- let offset = 0
254
- for (const chunk of chunks) {
255
- bytes.set(chunk, offset)
256
- offset += chunk.byteLength
257
- }
258
- const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
259
- return JSON.parse(text) as unknown
260
- }