pantheon-opencode 1.6.2-beta.2 → 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.
- package/CHANGELOG.md +48 -0
- package/README.md +56 -16
- package/bin/pantheon-init.mjs +68 -13
- package/package.json +10 -3
- package/plugin.json +1 -1
- package/prompts/README.md +58 -0
- package/prompts/debug-issue.prompt.md +46 -0
- package/prompts/dynamic/agora-generated.txt +38 -0
- package/prompts/dynamic/orchestrate-generated.txt +51 -0
- package/prompts/focus.prompt.md +42 -0
- package/prompts/implement-feature.prompt.md +39 -0
- package/prompts/optimize-database.prompt.md +58 -0
- package/prompts/orchestrate-with-zeus.prompt.md +441 -0
- package/prompts/plan-architecture.prompt.md +59 -0
- package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
- package/prompts/quick-plan-large-feature.prompt.md +197 -0
- package/prompts/semantic-summarize.md +50 -0
- package/prompts/sketch.prompt.md +91 -0
- package/prompts/subtask.prompt.md +131 -0
- package/pyproject.toml +1 -1
- package/scripts/decision-router-budget.mjs +781 -0
- package/scripts/decision-router.mjs +297 -0
- package/scripts/install/component-selection.mjs +9 -4
- package/scripts/install/decision-router-config.mjs +432 -0
- package/scripts/install/health-check.mjs +20 -11
- package/scripts/install/interactive.mjs +78 -14
- package/scripts/install/interrupt.mjs +4 -3
- package/scripts/install/migrate.mjs +123 -72
- package/scripts/install/opencode.mjs +162 -114
- package/scripts/install/plan.mjs +8 -1
- package/scripts/install/state.mjs +12 -0
- package/scripts/install/strings.mjs +10 -0
- package/scripts/install/venv.mjs +34 -17
- package/scripts/restore.mjs +22 -10
- package/scripts/test-opencode-v2-sandbox.sh +10 -6
- package/src/agents/zeus.md +12 -0
- package/src/pantheon/local-decision-agents.ts +170 -0
- package/src/pantheon/local-decision-budget.ts +1043 -0
- package/src/pantheon/local-decision-egress-gate.ts +264 -0
- package/src/pantheon/local-decision-prompt.ts +123 -0
- package/src/pantheon/local-decision-provider-matrix.ts +92 -0
- package/src/pantheon/local-decision-provider-protocol.ts +335 -0
- package/src/pantheon/local-decision-provider.internal.ts +260 -0
- package/src/pantheon/local-decision-router.ts +225 -0
- package/src/pantheon/local-decision-skills.ts +171 -0
- package/src/pantheon/local-decision-tool.ts +126 -0
- package/src/pantheon/local-decision-turn.ts +338 -0
- package/src/pantheon/local-decision-usage-evidence.internal.ts +207 -0
- package/src/pantheon/local-orchestration.ts +322 -0
- package/src/pantheon/pantheon-decision-catalog.ts +101 -0
- package/src/pantheon/v2-tools.ts +15 -14
- package/src/plugin-v2.ts +52 -19
- package/src/plugin.ts +4 -0
- package/src/plugins/tui/dist/tui-v2.js +3 -3
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/package-lock.json +2 -2
- package/src/plugins/tui/package.json +1 -1
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One advisory decision per turn.
|
|
3
|
+
*
|
|
4
|
+
* The selector is always local-first and at most one provider call is made per
|
|
5
|
+
* session/message pair. The decision is cached for the rest of the turn, so a
|
|
6
|
+
* repeated prompt hook cannot fan out or repeat egress.
|
|
7
|
+
*/
|
|
8
|
+
import {
|
|
9
|
+
isUserDecisionRouterEnabled,
|
|
10
|
+
readUserDecisionRouterConfig,
|
|
11
|
+
type UserDecisionRouterConfig,
|
|
12
|
+
} from '../../scripts/install/decision-router-config.mjs'
|
|
13
|
+
import {
|
|
14
|
+
hasDelegationSignal,
|
|
15
|
+
listEligibleDecisionAgents,
|
|
16
|
+
recommendLocalDecisionAgent,
|
|
17
|
+
} from './local-decision-agents.ts'
|
|
18
|
+
import {
|
|
19
|
+
assertDecisionEgressPermission,
|
|
20
|
+
buildDecisionEgressRequest,
|
|
21
|
+
isDecisionAssertionDenial,
|
|
22
|
+
type PermissionAssert,
|
|
23
|
+
resolveDecisionEgressConsent,
|
|
24
|
+
} from './local-decision-egress-gate.ts'
|
|
25
|
+
import {
|
|
26
|
+
buildDecisionPayload,
|
|
27
|
+
DECISION_PROVIDER_ADAPTERS,
|
|
28
|
+
type DecisionPayload,
|
|
29
|
+
type DecisionProviderId,
|
|
30
|
+
runProviderDecision,
|
|
31
|
+
} from './local-decision-provider.internal.ts'
|
|
32
|
+
import { selectPantheonSkills } from './local-decision-skills.ts'
|
|
33
|
+
import { type LocalDecisionPolicy, loadLocalDecisionPolicy } from './local-orchestration.ts'
|
|
34
|
+
import { PANTHEON_SKILL_CATALOG } from './pantheon-decision-catalog.ts'
|
|
35
|
+
|
|
36
|
+
export type TurnDecisionSource = 'local' | DecisionProviderId
|
|
37
|
+
|
|
38
|
+
export interface TurnDecision {
|
|
39
|
+
schemaVersion: 1
|
|
40
|
+
active: boolean
|
|
41
|
+
source: TurnDecisionSource
|
|
42
|
+
skillIds: string[]
|
|
43
|
+
agent: string | null
|
|
44
|
+
reasonCode: string
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
type PermissionOutcome = 'allowed' | 'denied'
|
|
48
|
+
|
|
49
|
+
interface TurnCacheEntry {
|
|
50
|
+
decision: TurnDecision
|
|
51
|
+
expiresAt: number
|
|
52
|
+
/**
|
|
53
|
+
* Assert outcome memoized per caller gate identity. The gate function is the
|
|
54
|
+
* only stable caller identity available here, so an interactive
|
|
55
|
+
* `permission.assert` is asked at most once per gate for a cached turn.
|
|
56
|
+
*/
|
|
57
|
+
permissions: WeakMap<PermissionAssert, PermissionOutcome>
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface TurnDecisionInput {
|
|
61
|
+
request: unknown
|
|
62
|
+
sessionID: unknown
|
|
63
|
+
messageID: unknown
|
|
64
|
+
permissionAssert?: PermissionAssert | undefined
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const MAX_REQUEST_LENGTH = 20_000
|
|
68
|
+
const CACHE_MAX_ENTRIES = 128
|
|
69
|
+
const CACHE_TTL_MS = 10 * 60_000
|
|
70
|
+
const turnCache = new Map<string, TurnCacheEntry>()
|
|
71
|
+
const inFlight = new Map<string, Promise<TurnDecision>>()
|
|
72
|
+
|
|
73
|
+
function inactive(reasonCode: string): TurnDecision {
|
|
74
|
+
return {
|
|
75
|
+
schemaVersion: 1,
|
|
76
|
+
active: false,
|
|
77
|
+
source: 'local',
|
|
78
|
+
skillIds: [],
|
|
79
|
+
agent: null,
|
|
80
|
+
reasonCode,
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function cacheKey(sessionID: string, messageID: string): string {
|
|
85
|
+
return `${sessionID}\u0000${messageID}`
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function readCache(key: string, now: number): TurnCacheEntry | undefined {
|
|
89
|
+
const entry = turnCache.get(key)
|
|
90
|
+
if (entry === undefined) return undefined
|
|
91
|
+
if (entry.expiresAt <= now) {
|
|
92
|
+
turnCache.delete(key)
|
|
93
|
+
return undefined
|
|
94
|
+
}
|
|
95
|
+
return entry
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function writeCache(key: string, entry: TurnCacheEntry, now: number): void {
|
|
99
|
+
if (turnCache.size >= CACHE_MAX_ENTRIES && !turnCache.has(key)) {
|
|
100
|
+
const oldest = turnCache.keys().next().value
|
|
101
|
+
if (oldest !== undefined) turnCache.delete(oldest)
|
|
102
|
+
}
|
|
103
|
+
entry.expiresAt = now + CACHE_TTL_MS
|
|
104
|
+
turnCache.set(key, entry)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Test-only cache reset. It cannot initiate a provider request. */
|
|
108
|
+
export function clearTurnDecisionCache(): void {
|
|
109
|
+
turnCache.clear()
|
|
110
|
+
inFlight.clear()
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function readConfig(): UserDecisionRouterConfig | undefined {
|
|
114
|
+
try {
|
|
115
|
+
return readUserDecisionRouterConfig()
|
|
116
|
+
} catch {
|
|
117
|
+
return undefined
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function localDecision(
|
|
122
|
+
request: string,
|
|
123
|
+
policy: LocalDecisionPolicy | undefined,
|
|
124
|
+
reasonCode: string,
|
|
125
|
+
): TurnDecision {
|
|
126
|
+
const skills = selectPantheonSkills(request)
|
|
127
|
+
const agent = hasDelegationSignal(request)
|
|
128
|
+
? recommendLocalDecisionAgent(request, policy).agent
|
|
129
|
+
: null
|
|
130
|
+
return {
|
|
131
|
+
schemaVersion: 1,
|
|
132
|
+
active: true,
|
|
133
|
+
source: 'local',
|
|
134
|
+
skillIds: skills.skillIds,
|
|
135
|
+
agent,
|
|
136
|
+
reasonCode,
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function buildPayload(
|
|
141
|
+
request: string,
|
|
142
|
+
eligibleAgents: readonly string[],
|
|
143
|
+
includeAgents: boolean,
|
|
144
|
+
): DecisionPayload | null {
|
|
145
|
+
return buildDecisionPayload({
|
|
146
|
+
request,
|
|
147
|
+
skillIds: PANTHEON_SKILL_CATALOG.map((entry) => entry.id),
|
|
148
|
+
...(includeAgents && eligibleAgents.length > 0 ? { agentIds: eligibleAgents } : {}),
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* A cached/in-flight provider decision was minted under an earlier caller's
|
|
154
|
+
* permission assertion. Reuse therefore needs authority for *this* caller: the
|
|
155
|
+
* outcome is memoized per gate function identity, so the same (possibly
|
|
156
|
+
* interactive) gate is not prompted twice for one cached turn, while a
|
|
157
|
+
* different or missing gate is evaluated afresh. A missing or denying assertion
|
|
158
|
+
* downgrades the turn to inactive instead of handing out a remote
|
|
159
|
+
* recommendation (no new egress happens here).
|
|
160
|
+
*
|
|
161
|
+
* The config/consent gate is re-read on every reuse before the assertion: it is
|
|
162
|
+
* local (config file plus ledger reads, no network), and revoking consent,
|
|
163
|
+
* disabling the router, or dropping caps must take effect immediately rather
|
|
164
|
+
* than after the 10-minute cache expires.
|
|
165
|
+
*
|
|
166
|
+
* The assertion is the host's kill-switch; the user-level config remains the
|
|
167
|
+
* source of truth. A resolved non-denial is the host's allow path (`undefined`
|
|
168
|
+
* on the measured host), so it is treated as allowed. No allowance is minted or
|
|
169
|
+
* consumed: the v2.2.0 canary showed the evaluate hook runs on the allow path
|
|
170
|
+
* and is skipped for an explicit deny, so egress never depends on it.
|
|
171
|
+
*/
|
|
172
|
+
async function reuseDeniedReason(
|
|
173
|
+
entry: TurnCacheEntry,
|
|
174
|
+
permissionAssert: TurnDecisionInput['permissionAssert'],
|
|
175
|
+
sessionID: string,
|
|
176
|
+
messageID: string,
|
|
177
|
+
): Promise<string | null> {
|
|
178
|
+
if (entry.decision.source === 'local') return null
|
|
179
|
+
const adapter = DECISION_PROVIDER_ADAPTERS[entry.decision.source]
|
|
180
|
+
if (adapter === undefined || !adapter.egressEligible) return 'PERMISSION_DENIED'
|
|
181
|
+
const consent = resolveDecisionEgressConsent()
|
|
182
|
+
if (!consent.ok) return consent.reasonCode
|
|
183
|
+
if (typeof permissionAssert !== 'function') return 'PERMISSION_UNAVAILABLE'
|
|
184
|
+
const memo = entry.permissions.get(permissionAssert)
|
|
185
|
+
if (memo === 'denied') return 'PERMISSION_DENIED'
|
|
186
|
+
if (memo === 'allowed') return null
|
|
187
|
+
const outcome = await assertDecisionEgressPermission(
|
|
188
|
+
permissionAssert,
|
|
189
|
+
buildDecisionEgressRequest({ sessionID, messageID, endpoint: adapter.endpoint }),
|
|
190
|
+
)
|
|
191
|
+
if (outcome === 'deny') {
|
|
192
|
+
entry.permissions.set(permissionAssert, 'denied')
|
|
193
|
+
return 'PERMISSION_DENIED'
|
|
194
|
+
}
|
|
195
|
+
entry.permissions.set(permissionAssert, 'allowed')
|
|
196
|
+
return null
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Record the gate outcome for the computing caller so the in-flight path can
|
|
201
|
+
* reuse it instead of asserting a second time.
|
|
202
|
+
*/
|
|
203
|
+
function recordPermission(
|
|
204
|
+
entry: TurnCacheEntry,
|
|
205
|
+
permissionAssert: PermissionAssert,
|
|
206
|
+
): PermissionAssert {
|
|
207
|
+
return async (input) => {
|
|
208
|
+
let result: unknown
|
|
209
|
+
try {
|
|
210
|
+
result = await permissionAssert(input)
|
|
211
|
+
} catch (error) {
|
|
212
|
+
entry.permissions.set(permissionAssert, 'denied')
|
|
213
|
+
throw error
|
|
214
|
+
}
|
|
215
|
+
entry.permissions.set(
|
|
216
|
+
permissionAssert,
|
|
217
|
+
isDecisionAssertionDenial(result) ? 'denied' : 'allowed',
|
|
218
|
+
)
|
|
219
|
+
return result
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Compute (or reuse) the advisory turn decision. The request text is used only
|
|
225
|
+
* in memory and, when every gate passes, in the bounded provider payload.
|
|
226
|
+
*/
|
|
227
|
+
export async function decideForTurn(input: TurnDecisionInput): Promise<TurnDecision> {
|
|
228
|
+
const request = typeof input.request === 'string' ? input.request : ''
|
|
229
|
+
const sessionID = typeof input.sessionID === 'string' ? input.sessionID.trim() : ''
|
|
230
|
+
const messageID = typeof input.messageID === 'string' ? input.messageID.trim() : ''
|
|
231
|
+
if (
|
|
232
|
+
request.trim().length === 0 ||
|
|
233
|
+
request.length > MAX_REQUEST_LENGTH ||
|
|
234
|
+
sessionID.length === 0 ||
|
|
235
|
+
messageID.length === 0
|
|
236
|
+
) {
|
|
237
|
+
return inactive('INVALID_INPUT')
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const config = readConfig()
|
|
241
|
+
if (config === undefined || !isUserDecisionRouterEnabled(config)) return inactive('DISABLED')
|
|
242
|
+
|
|
243
|
+
const key = cacheKey(sessionID, messageID)
|
|
244
|
+
const cached = readCache(key, Date.now())
|
|
245
|
+
if (cached !== undefined) {
|
|
246
|
+
const denied = await reuseDeniedReason(cached, input.permissionAssert, sessionID, messageID)
|
|
247
|
+
return denied === null ? cached.decision : inactive(denied)
|
|
248
|
+
}
|
|
249
|
+
const pending = inFlight.get(key)
|
|
250
|
+
if (pending !== undefined) {
|
|
251
|
+
const decision = await pending
|
|
252
|
+
const settled = readCache(key, Date.now())
|
|
253
|
+
const entry = settled ?? { decision, expiresAt: 0, permissions: new WeakMap() }
|
|
254
|
+
const denied = await reuseDeniedReason(entry, input.permissionAssert, sessionID, messageID)
|
|
255
|
+
return denied === null ? decision : inactive(denied)
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const entry: TurnCacheEntry = {
|
|
259
|
+
decision: inactive('INVALID_INPUT'),
|
|
260
|
+
expiresAt: 0,
|
|
261
|
+
permissions: new WeakMap(),
|
|
262
|
+
}
|
|
263
|
+
const computation = computeTurn(input, request, sessionID, messageID, key, config, entry).finally(
|
|
264
|
+
() => inFlight.delete(key),
|
|
265
|
+
)
|
|
266
|
+
inFlight.set(key, computation)
|
|
267
|
+
return computation
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function computeTurn(
|
|
271
|
+
input: TurnDecisionInput,
|
|
272
|
+
request: string,
|
|
273
|
+
sessionID: string,
|
|
274
|
+
messageID: string,
|
|
275
|
+
key: string,
|
|
276
|
+
config: UserDecisionRouterConfig,
|
|
277
|
+
entry: TurnCacheEntry,
|
|
278
|
+
): Promise<TurnDecision> {
|
|
279
|
+
const policy = await loadLocalDecisionPolicy().catch(() => undefined)
|
|
280
|
+
const local = localDecision(request, policy, 'LOCAL_SELECTION')
|
|
281
|
+
|
|
282
|
+
const delegationSignal = hasDelegationSignal(request)
|
|
283
|
+
const eligibleAgents = delegationSignal ? listEligibleDecisionAgents(policy) : []
|
|
284
|
+
|
|
285
|
+
if (config.selection.mode === 'local' || !config.egress_consent) {
|
|
286
|
+
entry.decision = local
|
|
287
|
+
writeCache(key, entry, Date.now())
|
|
288
|
+
return local
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const payload = buildPayload(request, eligibleAgents, delegationSignal)
|
|
292
|
+
const permissionAssert =
|
|
293
|
+
typeof input.permissionAssert === 'function'
|
|
294
|
+
? recordPermission(entry, input.permissionAssert)
|
|
295
|
+
: undefined
|
|
296
|
+
const provider = await runProviderDecision({
|
|
297
|
+
payload,
|
|
298
|
+
permissionAssert,
|
|
299
|
+
sessionID,
|
|
300
|
+
messageID,
|
|
301
|
+
}).catch(() => null)
|
|
302
|
+
|
|
303
|
+
const providerAgent = provider?.status === 'decided' ? provider.agent : null
|
|
304
|
+
const providerSkills =
|
|
305
|
+
providerAgent !== null
|
|
306
|
+
? (provider?.skillIds ?? []).filter((skill) =>
|
|
307
|
+
(policy?.agents[providerAgent]?.skills ?? []).includes(skill),
|
|
308
|
+
)
|
|
309
|
+
: (provider?.skillIds ?? [])
|
|
310
|
+
|
|
311
|
+
const decision: TurnDecision =
|
|
312
|
+
provider !== null && provider.status === 'decided'
|
|
313
|
+
? {
|
|
314
|
+
schemaVersion: 1,
|
|
315
|
+
active: true,
|
|
316
|
+
source: provider.provider ?? 'local',
|
|
317
|
+
skillIds: providerSkills.length > 0 ? providerSkills : local.skillIds,
|
|
318
|
+
agent: provider.agent,
|
|
319
|
+
reasonCode: provider.reasonCode,
|
|
320
|
+
}
|
|
321
|
+
: provider !== null && provider.status === 'abstain'
|
|
322
|
+
? {
|
|
323
|
+
schemaVersion: 1,
|
|
324
|
+
active: true,
|
|
325
|
+
source: provider.provider ?? 'local',
|
|
326
|
+
skillIds: local.skillIds,
|
|
327
|
+
agent: null,
|
|
328
|
+
reasonCode: provider.reasonCode,
|
|
329
|
+
}
|
|
330
|
+
: {
|
|
331
|
+
...local,
|
|
332
|
+
reasonCode: provider?.reasonCode ?? 'LOCAL_FALLBACK',
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
entry.decision = decision
|
|
336
|
+
writeCache(key, entry, Date.now())
|
|
337
|
+
return decision
|
|
338
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal, parser-issued usage capabilities. This module is deliberately not
|
|
3
|
+
* exported from the package entrypoints; callers cannot provide a cost value.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export type ReconciliableUsageProvider = 'openai-decisions' | 'typesafe-jev'
|
|
7
|
+
|
|
8
|
+
export interface UsageReservationBinding {
|
|
9
|
+
reservationId: string
|
|
10
|
+
provider: ReconciliableUsageProvider
|
|
11
|
+
model: string
|
|
12
|
+
period: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
declare const verifiedUsageEvidenceBrand: unique symbol
|
|
16
|
+
export type VerifiedUsageEvidence = {
|
|
17
|
+
readonly [verifiedUsageEvidenceBrand]: true
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ParsedUsageCounts {
|
|
21
|
+
provider: ReconciliableUsageProvider
|
|
22
|
+
model: string
|
|
23
|
+
inputTokens: number
|
|
24
|
+
outputTokens: number
|
|
25
|
+
cachedInputTokens: number
|
|
26
|
+
cacheWriteInputTokens: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface VerifiedUsageEvidenceDetails extends ParsedUsageCounts {
|
|
30
|
+
reservationId: string
|
|
31
|
+
period: string
|
|
32
|
+
actualCostMicros: number
|
|
33
|
+
pricingSnapshot: '2026-10-30'
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const MODEL_IDS: Readonly<Record<ReconciliableUsageProvider, string>> = Object.freeze({
|
|
37
|
+
'openai-decisions': 'gpt-6-luna',
|
|
38
|
+
'typesafe-jev': 'jev-1.14.0',
|
|
39
|
+
})
|
|
40
|
+
const RESERVATION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
|
|
41
|
+
const UTC_PERIOD = /^\d{4}-(0[1-9]|1[0-2])$/
|
|
42
|
+
const evidenceDetails = new WeakMap<object, VerifiedUsageEvidenceDetails>()
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Validate only official usage fields for providers with a documented price
|
|
46
|
+
* snapshot, then mint an opaque capability bound to one reservation identity.
|
|
47
|
+
* Console models and zero-cost results deliberately produce no capability.
|
|
48
|
+
*/
|
|
49
|
+
export function verifyProviderUsageForReservation(
|
|
50
|
+
bindingInput: unknown,
|
|
51
|
+
response: unknown,
|
|
52
|
+
): VerifiedUsageEvidence | null {
|
|
53
|
+
try {
|
|
54
|
+
if (
|
|
55
|
+
!isPlainRecord(bindingInput) ||
|
|
56
|
+
!hasExactKeys(bindingInput, ['model', 'period', 'provider', 'reservationId'])
|
|
57
|
+
) {
|
|
58
|
+
return null
|
|
59
|
+
}
|
|
60
|
+
const provider = bindingInput.provider
|
|
61
|
+
const model = bindingInput.model
|
|
62
|
+
const reservationId = bindingInput.reservationId
|
|
63
|
+
const period = bindingInput.period
|
|
64
|
+
if (
|
|
65
|
+
!isReconciliableProvider(provider) ||
|
|
66
|
+
model !== MODEL_IDS[provider] ||
|
|
67
|
+
typeof reservationId !== 'string' ||
|
|
68
|
+
!RESERVATION_ID.test(reservationId) ||
|
|
69
|
+
typeof period !== 'string' ||
|
|
70
|
+
!UTC_PERIOD.test(period)
|
|
71
|
+
) {
|
|
72
|
+
return null
|
|
73
|
+
}
|
|
74
|
+
const parsed = parseProviderUsageCounts(provider, response)
|
|
75
|
+
if (!parsed || parsed.model !== model) return null
|
|
76
|
+
if (parsed.cachedInputTokens !== 0 || parsed.cacheWriteInputTokens !== 0) return null
|
|
77
|
+
const actualCostMicros = priceUsageMicros(parsed)
|
|
78
|
+
if (actualCostMicros === null || actualCostMicros <= 0) return null
|
|
79
|
+
|
|
80
|
+
const evidence = Object.freeze(Object.create(null)) as VerifiedUsageEvidence
|
|
81
|
+
evidenceDetails.set(
|
|
82
|
+
evidence,
|
|
83
|
+
Object.freeze({
|
|
84
|
+
...parsed,
|
|
85
|
+
reservationId,
|
|
86
|
+
period,
|
|
87
|
+
actualCostMicros,
|
|
88
|
+
pricingSnapshot: '2026-10-30',
|
|
89
|
+
}),
|
|
90
|
+
)
|
|
91
|
+
return evidence
|
|
92
|
+
} catch {
|
|
93
|
+
return null
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Ledger-only runtime check: plain objects and serialized capabilities fail. */
|
|
98
|
+
export function getVerifiedUsageEvidenceDetails(
|
|
99
|
+
value: unknown,
|
|
100
|
+
): Readonly<VerifiedUsageEvidenceDetails> | null {
|
|
101
|
+
if ((typeof value !== 'object' && typeof value !== 'function') || value === null) return null
|
|
102
|
+
return evidenceDetails.get(value as object) ?? null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Shared strict usage parser used by the isolated provider-contract tests. */
|
|
106
|
+
export function parseProviderUsageCounts(
|
|
107
|
+
provider: unknown,
|
|
108
|
+
response: unknown,
|
|
109
|
+
): ParsedUsageCounts | null {
|
|
110
|
+
try {
|
|
111
|
+
if (
|
|
112
|
+
!isReconciliableProvider(provider) ||
|
|
113
|
+
!isPlainRecord(response) ||
|
|
114
|
+
response.model !== MODEL_IDS[provider] ||
|
|
115
|
+
!isPlainRecord(response.usage)
|
|
116
|
+
) {
|
|
117
|
+
return null
|
|
118
|
+
}
|
|
119
|
+
const usage = response.usage
|
|
120
|
+
if (provider === 'openai-decisions') {
|
|
121
|
+
if (
|
|
122
|
+
!hasExactKeys(usage, [
|
|
123
|
+
'input_tokens',
|
|
124
|
+
'input_tokens_details',
|
|
125
|
+
'output_tokens',
|
|
126
|
+
'output_tokens_details',
|
|
127
|
+
'total_tokens',
|
|
128
|
+
]) ||
|
|
129
|
+
!isPlainRecord(usage.input_tokens_details) ||
|
|
130
|
+
!hasExactKeys(usage.input_tokens_details, ['cache_write_tokens', 'cached_tokens']) ||
|
|
131
|
+
!isPlainRecord(usage.output_tokens_details) ||
|
|
132
|
+
!hasExactKeys(usage.output_tokens_details, ['reasoning_tokens']) ||
|
|
133
|
+
!isNonNegativeSafeInteger(usage.input_tokens) ||
|
|
134
|
+
!isNonNegativeSafeInteger(usage.output_tokens) ||
|
|
135
|
+
!isNonNegativeSafeInteger(usage.total_tokens) ||
|
|
136
|
+
!isNonNegativeSafeInteger(usage.input_tokens_details.cache_write_tokens) ||
|
|
137
|
+
!isNonNegativeSafeInteger(usage.input_tokens_details.cached_tokens) ||
|
|
138
|
+
!isNonNegativeSafeInteger(usage.output_tokens_details.reasoning_tokens) ||
|
|
139
|
+
!Number.isSafeInteger(usage.input_tokens + usage.output_tokens) ||
|
|
140
|
+
usage.input_tokens + usage.output_tokens !== usage.total_tokens ||
|
|
141
|
+
usage.input_tokens_details.cache_write_tokens + usage.input_tokens_details.cached_tokens >
|
|
142
|
+
usage.input_tokens ||
|
|
143
|
+
usage.output_tokens_details.reasoning_tokens > usage.output_tokens
|
|
144
|
+
) {
|
|
145
|
+
return null
|
|
146
|
+
}
|
|
147
|
+
} else if (
|
|
148
|
+
!hasExactKeys(usage, ['input_tokens', 'output_tokens']) ||
|
|
149
|
+
!isNonNegativeSafeInteger(usage.input_tokens) ||
|
|
150
|
+
!isNonNegativeSafeInteger(usage.output_tokens)
|
|
151
|
+
) {
|
|
152
|
+
return null
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
provider,
|
|
156
|
+
model: MODEL_IDS[provider],
|
|
157
|
+
inputTokens: usage.input_tokens as number,
|
|
158
|
+
outputTokens: usage.output_tokens as number,
|
|
159
|
+
cachedInputTokens:
|
|
160
|
+
provider === 'openai-decisions'
|
|
161
|
+
? ((usage.input_tokens_details as Record<string, number>).cached_tokens as number)
|
|
162
|
+
: 0,
|
|
163
|
+
cacheWriteInputTokens:
|
|
164
|
+
provider === 'openai-decisions'
|
|
165
|
+
? ((usage.input_tokens_details as Record<string, number>).cache_write_tokens as number)
|
|
166
|
+
: 0,
|
|
167
|
+
}
|
|
168
|
+
} catch {
|
|
169
|
+
return null
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function priceUsageMicros(usage: ParsedUsageCounts): number | null {
|
|
174
|
+
// Snapshot: GPT-6 Luna standard rates are $0.10/M input and $0.50/M output;
|
|
175
|
+
// TypeSafe Jev 1.14 is $0.042/M input and $0 output. Discounts are not applied.
|
|
176
|
+
const numerator =
|
|
177
|
+
usage.provider === 'openai-decisions'
|
|
178
|
+
? BigInt(usage.inputTokens) + 5n * BigInt(usage.outputTokens)
|
|
179
|
+
: 42n * BigInt(usage.inputTokens)
|
|
180
|
+
const denominator = usage.provider === 'openai-decisions' ? 10n : 1_000n
|
|
181
|
+
const roundedMicros = (numerator + denominator - 1n) / denominator
|
|
182
|
+
if (roundedMicros <= 0n || roundedMicros > BigInt(Number.MAX_SAFE_INTEGER)) return null
|
|
183
|
+
return Number(roundedMicros)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function isReconciliableProvider(value: unknown): value is ReconciliableUsageProvider {
|
|
187
|
+
return value === 'openai-decisions' || value === 'typesafe-jev'
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function isNonNegativeSafeInteger(value: unknown): value is number {
|
|
191
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
195
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
|
|
196
|
+
const prototype = Object.getPrototypeOf(value)
|
|
197
|
+
return prototype === Object.prototype || prototype === null
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function hasExactKeys(value: Record<string, unknown>, expectedKeys: readonly string[]): boolean {
|
|
201
|
+
const actualKeys = Object.keys(value).sort()
|
|
202
|
+
const expected = [...expectedKeys].sort()
|
|
203
|
+
return (
|
|
204
|
+
actualKeys.length === expected.length &&
|
|
205
|
+
actualKeys.every((key, index) => key === expected[index])
|
|
206
|
+
)
|
|
207
|
+
}
|