pantheon-opencode 1.6.2-beta.3 → 1.6.2-beta.4

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 (35) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +38 -1
  3. package/bin/pantheon-init.mjs +17 -0
  4. package/package.json +9 -3
  5. package/plugin.json +1 -1
  6. package/pyproject.toml +1 -1
  7. package/scripts/decision-router-budget.mjs +781 -0
  8. package/scripts/decision-router.mjs +297 -0
  9. package/scripts/install/decision-router-config.mjs +432 -0
  10. package/scripts/install/interactive.mjs +76 -5
  11. package/scripts/install/opencode.mjs +12 -0
  12. package/scripts/install/state.mjs +5 -0
  13. package/scripts/install/strings.mjs +4 -0
  14. package/src/agents/zeus.md +12 -0
  15. package/src/pantheon/local-decision-agents.ts +170 -0
  16. package/src/pantheon/local-decision-budget.ts +1043 -0
  17. package/src/pantheon/local-decision-egress-gate.ts +264 -0
  18. package/src/pantheon/local-decision-prompt.ts +123 -0
  19. package/src/pantheon/local-decision-provider-matrix.ts +92 -0
  20. package/src/pantheon/local-decision-provider-protocol.ts +335 -0
  21. package/src/pantheon/local-decision-provider.internal.ts +260 -0
  22. package/src/pantheon/local-decision-router.ts +225 -0
  23. package/src/pantheon/local-decision-skills.ts +171 -0
  24. package/src/pantheon/local-decision-tool.ts +126 -0
  25. package/src/pantheon/local-decision-turn.ts +338 -0
  26. package/src/pantheon/local-decision-usage-evidence.internal.ts +207 -0
  27. package/src/pantheon/local-orchestration.ts +322 -0
  28. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  29. package/src/pantheon/v2-tools.ts +15 -14
  30. package/src/plugin-v2.ts +52 -19
  31. package/src/plugin.ts +4 -0
  32. package/src/plugins/tui/dist/tui-v2.js +3 -3
  33. package/src/plugins/tui/dist/tui.js +1 -1
  34. package/src/plugins/tui/package-lock.json +2 -2
  35. package/src/plugins/tui/package.json +1 -1
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Private provider protocol: payload construction, fixed request bodies, and
3
+ * strict response decoding. This module performs no network I/O and accepts no
4
+ * fetch, env, config, or ledger.
5
+ */
6
+ import {
7
+ DECISION_PROVIDER_ADAPTERS,
8
+ type DecisionProtocol,
9
+ type DecisionProviderId,
10
+ } from './local-decision-provider-matrix.ts'
11
+ import {
12
+ agentCatalogSubset,
13
+ isPantheonAgentId,
14
+ isPantheonSkillId,
15
+ skillCatalogSubset,
16
+ } from './pantheon-decision-catalog.ts'
17
+
18
+ const MAX_REQUEST_LENGTH = 12_000
19
+ const MIN_CONFIDENCE = 0.8
20
+ /**
21
+ * Best-effort rejection of high-confidence credential shapes. This is a
22
+ * denylist, not a secret scanner: an unrecognized credential can still be sent
23
+ * with the request text, so prompts must not contain secrets in the first
24
+ * place. The `sk-` family requires a token boundary and a structured prefix
25
+ * (`sk-proj-`, `sk-svcacct-`, `sk-admin-`, `sk-ant-…-`) or a long bare token, so
26
+ * prose such as `task-force-…`, `risk-based-…`, `disk-usage-…`,
27
+ * `desk-organization-…`, or `mask-generation-…` is not mistaken for a key.
28
+ * Also covers Stripe, cloud/SaaS tokens, JWTs, bearer values, and
29
+ * `password=`/`api_key=` assignments.
30
+ */
31
+ const SECRET_PATTERN = new RegExp(
32
+ [
33
+ '(?<![A-Za-z0-9])sk-(?:proj-|svcacct-|admin-|ant-[a-z0-9]+-)?[A-Za-z0-9]{20,}',
34
+ 'sk_live_[A-Za-z0-9]{20,}',
35
+ 'sk_test_[A-Za-z0-9]{20,}',
36
+ 'rk_live_[A-Za-z0-9]{20,}',
37
+ 'AKIA[0-9A-Z]{16}',
38
+ 'gh[pousr]_[A-Za-z0-9_]{36,}',
39
+ 'glpat-[A-Za-z0-9_-]{20}',
40
+ 'xox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24}',
41
+ 'bearer[ \t]+[A-Za-z0-9_.-]{20,}',
42
+ 'eyJ[A-Za-z0-9_-]*\\.eyJ[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]*',
43
+ '(?:password|passwd|pwd|api[_-]?key|apikey|client[_-]?secret|secret[_-]?key|access[_-]?token|auth[_-]?token)[ \\t]*[:=][ \\t]*[\'"]?[^\\s\'"&]{8,}',
44
+ ].join('|'),
45
+ 'i',
46
+ )
47
+ export interface DecisionPayload {
48
+ request: string
49
+ skills: Array<{ id: string; description: string }>
50
+ agents?: Array<{ id: string; description: string }>
51
+ }
52
+
53
+ export interface DecisionPayloadInput {
54
+ request: unknown
55
+ skillIds: readonly string[]
56
+ agentIds?: readonly string[]
57
+ }
58
+
59
+ /**
60
+ * Build the only authorized provider payload: the current user request plus a
61
+ * short allowlisted skill catalog, and eligible agent IDs only when delegation
62
+ * is under consideration. Transcripts, files, paths, memory, and instructions
63
+ * are rejected by construction.
64
+ */
65
+ export function buildDecisionPayload(input: DecisionPayloadInput): DecisionPayload | null {
66
+ try {
67
+ const request =
68
+ typeof input.request === 'string' && input.request.trim().length > 0
69
+ ? input.request.trim()
70
+ : ''
71
+ if (request.length === 0 || request.length > MAX_REQUEST_LENGTH) return null
72
+ if (SECRET_PATTERN.test(request)) return null
73
+ if (!Array.isArray(input.skillIds) || input.skillIds.length === 0) return null
74
+ if (new Set(input.skillIds).size !== input.skillIds.length) return null
75
+ if (!input.skillIds.every((id) => isPantheonSkillId(id))) return null
76
+ const skills = skillCatalogSubset(input.skillIds)
77
+ if (skills.length !== input.skillIds.length) return null
78
+
79
+ if (input.agentIds === undefined) return { request, skills }
80
+ if (!Array.isArray(input.agentIds) || input.agentIds.length === 0) return null
81
+ if (new Set(input.agentIds).size !== input.agentIds.length) return null
82
+ if (!input.agentIds.every((id) => id !== 'zeus' && isPantheonAgentId(id))) return null
83
+ const agents = agentCatalogSubset(input.agentIds)
84
+ if (agents.length !== input.agentIds.length) return null
85
+ return { request, skills, agents }
86
+ } catch {
87
+ return null
88
+ }
89
+ }
90
+
91
+ interface ChoiceQuestion {
92
+ name: 'skill' | 'agent'
93
+ choices: string[]
94
+ }
95
+
96
+ function createQuestions(payload: DecisionPayload): ChoiceQuestion[] {
97
+ const questions: ChoiceQuestion[] = [
98
+ { name: 'skill', choices: [...payload.skills.map((skill) => skill.id), 'abstain'] },
99
+ ]
100
+ if (payload.agents !== undefined) {
101
+ questions.push({
102
+ name: 'agent',
103
+ choices: [...payload.agents.map((agent) => agent.id), 'abstain'],
104
+ })
105
+ }
106
+ return questions
107
+ }
108
+
109
+ /** Build the fixed provider request body for one adapter. */
110
+ export function buildProviderRequest(
111
+ provider: DecisionProviderId,
112
+ payload: DecisionPayload,
113
+ ): Record<string, unknown> | null {
114
+ const adapter = DECISION_PROVIDER_ADAPTERS[provider]
115
+ if (adapter === undefined || !adapter.egressEligible) return null
116
+ const questions = createQuestions(payload)
117
+ if (questions.length === 0) return null
118
+
119
+ if (adapter.protocol === 'openai') {
120
+ return {
121
+ model: adapter.model,
122
+ input: [
123
+ {
124
+ role: 'user',
125
+ content: [{ type: 'input_json', data: payload }],
126
+ },
127
+ ],
128
+ questions: questions.map((question) => ({
129
+ type: 'choice',
130
+ name: question.name,
131
+ instructions:
132
+ question.name === 'skill'
133
+ ? 'Choose one supplied skill ID, or choose abstain.'
134
+ : 'Choose one supplied specialist ID, or choose abstain.',
135
+ choices: question.choices.map((value) => ({ value, description: value })),
136
+ })),
137
+ }
138
+ }
139
+
140
+ return {
141
+ model: adapter.model,
142
+ state: payload,
143
+ questions: Object.fromEntries(
144
+ questions.map((question) => [
145
+ question.name,
146
+ {
147
+ type: 'choice',
148
+ instructions:
149
+ question.name === 'skill'
150
+ ? 'Choose one supplied skill ID, or choose abstain.'
151
+ : 'Choose one supplied specialist ID, or choose abstain.',
152
+ criteria: Object.fromEntries(question.choices.map((choice) => [choice, choice])),
153
+ },
154
+ ]),
155
+ ),
156
+ }
157
+ }
158
+
159
+ export type ProviderDecision =
160
+ | { status: 'decided'; skillIds: string[]; agent: string | null }
161
+ | { status: 'abstain'; reasonCode: 'PROVIDER_ABSTAIN' }
162
+ | { status: 'invalid'; reasonCode: 'INVALID_PROVIDER_RESPONSE' }
163
+
164
+ interface DecodedAnswer {
165
+ choice: string | null
166
+ }
167
+
168
+ function parseProbabilities(
169
+ value: unknown,
170
+ choices: readonly string[],
171
+ protocol: DecisionProtocol,
172
+ ): { selected: string; max: number } | null {
173
+ let entries: Array<[string, unknown]>
174
+ if (protocol === 'openai' && Array.isArray(value)) {
175
+ if (value.length !== choices.length) return null
176
+ const seen = new Set<string>()
177
+ entries = []
178
+ for (const item of value) {
179
+ if (!isPlainRecord(item) || !hasExactKeys(item, ['probability', 'value'])) return null
180
+ if (typeof item.value !== 'string' || !choices.includes(item.value) || seen.has(item.value)) {
181
+ return null
182
+ }
183
+ seen.add(item.value)
184
+ entries.push([item.value, item.probability])
185
+ }
186
+ if (seen.size !== choices.length) return null
187
+ } else if (protocol === 'systemone' && isPlainRecord(value)) {
188
+ const keys = Object.keys(value).sort()
189
+ const expected = [...choices].sort()
190
+ if (keys.length !== expected.length || keys.some((key, index) => key !== expected[index])) {
191
+ return null
192
+ }
193
+ entries = keys.map((key) => [key, value[key]])
194
+ } else {
195
+ return null
196
+ }
197
+
198
+ let total = 0
199
+ let selected = ''
200
+ let maximum = -1
201
+ let maximumCount = 0
202
+ for (const [choice, probability] of entries) {
203
+ if (
204
+ typeof probability !== 'number' ||
205
+ !Number.isFinite(probability) ||
206
+ probability < 0 ||
207
+ probability > 1
208
+ ) {
209
+ return null
210
+ }
211
+ total += probability
212
+ if (probability > maximum) {
213
+ maximum = probability
214
+ selected = choice
215
+ maximumCount = 1
216
+ } else if (probability === maximum) {
217
+ maximumCount += 1
218
+ }
219
+ }
220
+ if (Math.abs(total - 1) > 1e-6 || maximumCount !== 1) return null
221
+ return { selected, max: maximum }
222
+ }
223
+
224
+ function decodeAnswer(
225
+ value: unknown,
226
+ question: ChoiceQuestion,
227
+ protocol: DecisionProtocol,
228
+ ): DecodedAnswer | null {
229
+ if (!isPlainRecord(value)) return null
230
+ if (value.type === 'refusal') {
231
+ if (protocol !== 'openai' || !hasExactKeys(value, ['name', 'type'])) return null
232
+ return value.name === question.name ? { choice: null } : null
233
+ }
234
+ const keys =
235
+ protocol === 'openai'
236
+ ? ['choice', 'confidence', 'name', 'probabilities', 'type']
237
+ : ['choice', 'confidence', 'probabilities', 'type']
238
+ if (
239
+ !hasExactKeys(value, keys) ||
240
+ value.type !== 'choice' ||
241
+ (protocol === 'openai' && value.name !== question.name) ||
242
+ typeof value.choice !== 'string' ||
243
+ !question.choices.includes(value.choice) ||
244
+ typeof value.confidence !== 'number' ||
245
+ !Number.isFinite(value.confidence) ||
246
+ value.confidence < 0 ||
247
+ value.confidence > 1
248
+ ) {
249
+ return null
250
+ }
251
+ const distribution = parseProbabilities(value.probabilities, question.choices, protocol)
252
+ if (distribution === null || distribution.selected !== value.choice) return null
253
+ if (value.choice === 'abstain') return { choice: null }
254
+ if (value.confidence < MIN_CONFIDENCE || distribution.max < MIN_CONFIDENCE) {
255
+ return { choice: null }
256
+ }
257
+ return { choice: value.choice }
258
+ }
259
+
260
+ /**
261
+ * Decode only documented answer fields. IDs must be exactly the supplied
262
+ * candidates; the model cannot introduce, grant, or dispatch anything.
263
+ */
264
+ export function parseProviderDecision(
265
+ provider: DecisionProviderId,
266
+ response: unknown,
267
+ payload: DecisionPayload,
268
+ ): ProviderDecision {
269
+ try {
270
+ const adapter = DECISION_PROVIDER_ADAPTERS[provider]
271
+ if (adapter === undefined || !isPlainRecord(response) || response.model !== adapter.model) {
272
+ return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
273
+ }
274
+ const questions = createQuestions(payload)
275
+ const answers = new Map<ChoiceQuestion['name'], DecodedAnswer>()
276
+
277
+ if (adapter.protocol === 'openai') {
278
+ const rawAnswers = response.answers
279
+ if (!Array.isArray(rawAnswers) || rawAnswers.length !== questions.length) {
280
+ return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
281
+ }
282
+ for (const [index, question] of questions.entries()) {
283
+ const decoded = decodeAnswer(rawAnswers[index], question, 'openai')
284
+ if (decoded === null) return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
285
+ answers.set(question.name, decoded)
286
+ }
287
+ } else {
288
+ const rawAnswers = response.answers
289
+ if (
290
+ !isPlainRecord(rawAnswers) ||
291
+ !hasExactKeys(
292
+ rawAnswers,
293
+ questions.map((question) => question.name),
294
+ )
295
+ ) {
296
+ return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
297
+ }
298
+ for (const question of questions) {
299
+ const decoded = decodeAnswer(rawAnswers[question.name], question, 'systemone')
300
+ if (decoded === null) return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
301
+ answers.set(question.name, decoded)
302
+ }
303
+ }
304
+
305
+ const skill = answers.get('skill')?.choice ?? null
306
+ const agent = answers.get('agent')?.choice ?? null
307
+ if (skill !== null && !payload.skills.some((entry) => entry.id === skill)) {
308
+ return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
309
+ }
310
+ if (agent !== null && !(payload.agents ?? []).some((entry) => entry.id === agent)) {
311
+ return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
312
+ }
313
+ if (skill === null && agent === null) {
314
+ return { status: 'abstain', reasonCode: 'PROVIDER_ABSTAIN' }
315
+ }
316
+ return { status: 'decided', skillIds: skill === null ? [] : [skill], agent }
317
+ } catch {
318
+ return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
319
+ }
320
+ }
321
+
322
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
323
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
324
+ const prototype = Object.getPrototypeOf(value)
325
+ return prototype === Object.prototype || prototype === null
326
+ }
327
+
328
+ function hasExactKeys(value: Record<string, unknown>, expectedKeys: readonly string[]): boolean {
329
+ const actualKeys = Object.keys(value).sort()
330
+ const expected = [...expectedKeys].sort()
331
+ return (
332
+ actualKeys.length === expected.length &&
333
+ actualKeys.every((key, index) => key === expected[index])
334
+ )
335
+ }
@@ -0,0 +1,260 @@
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
+ }