xpenvo 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Xpenvo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,37 @@
1
- # Temporary Holding Version
1
+ # xpenvo
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Hard spending limits for AI agents. This is the small helper library for
4
+ [Xpenvo Agents](https://agents.xpenvo.com): it points your existing provider SDK at Xpenvo, adds your
5
+ agent key, waits for approvals and tells you why a request was stopped.
6
+
7
+ You keep using your provider's own SDK (OpenAI, Anthropic, Gemini, Mistral, OpenRouter, Azure OpenAI,
8
+ Amazon Bedrock). No dependencies. Node 18+, Deno, Bun and Cloudflare Workers.
9
+
10
+ ```sh
11
+ npm install xpenvo
12
+ ```
13
+
14
+ ```js
15
+ import OpenAI from 'openai'
16
+ import { xpenvo, newRunId } from 'xpenvo'
17
+
18
+ const x = xpenvo({ key: process.env.XPENVO_KEY, run: newRunId(), customer: 'customer-42' })
19
+ const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, baseURL: x.baseURL('openai'), fetch: x.fetch })
20
+ ```
21
+
22
+ What it does:
23
+
24
+ 1. gives the Xpenvo address for each provider (`x.baseURL('anthropic')`, `x.baseURL('azure', 'my-resource')` ...),
25
+ 2. adds your agent key and the optional run, step and end-customer labels,
26
+ 3. waits for a person to approve a big request, then sends it again,
27
+ 4. tells you, in plain words, why Xpenvo stopped a request (`reason(err)`, `REASONS`),
28
+ 5. names cheaper fallback models and chooses fail-open or fail-closed,
29
+ 6. checks and records spending that is not a model call, such as tools and search APIs (`x.spend`),
30
+ 7. tells you how much the key can still spend (`x.status()`).
31
+
32
+ Your prompts and answers go only to Xpenvo and your provider, exactly as before. Never put an email
33
+ address or other personal data in run, step or customer labels; use your own ids.
34
+
35
+ Setup guide: https://agents.xpenvo.com/docs · Security: https://agents.xpenvo.com/security
36
+
37
+ Xpenvo Agents is in a free private beta: https://agents.xpenvo.com
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "xpenvo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Hard spending limits for AI agents: helpers for the Xpenvo Agents proxy (OpenAI, Anthropic, Gemini, Mistral, OpenRouter, Azure OpenAI, Amazon Bedrock).",
5
+ "type": "module",
6
+ "main": "xpenvo.mjs",
7
+ "types": "xpenvo.d.mts",
8
+ "exports": { ".": { "types": "./xpenvo.d.mts", "default": "./xpenvo.mjs" } },
9
+ "files": ["xpenvo.mjs", "xpenvo.d.mts", "README.md", "LICENSE"],
10
+ "sideEffects": false,
11
+ "engines": { "node": ">=18" },
12
+ "keywords": ["ai", "agents", "llm", "budget", "spending-limit", "cost", "openai", "anthropic", "gemini", "mistral", "openrouter", "bedrock", "azure-openai", "guardrails"],
13
+ "homepage": "https://agents.xpenvo.com/docs",
14
+ "repository": { "type": "git", "url": "git+https://github.com/Joel-hub-dotcom/xpenvo-agents-sdk.git", "directory": "js" },
15
+ "bugs": { "email": "agents@xpenvo.com" },
16
+ "author": "Xpenvo (https://agents.xpenvo.com)",
17
+ "license": "MIT"
18
+ }
package/xpenvo.d.mts ADDED
@@ -0,0 +1,82 @@
1
+ export declare const DEFAULT_BASE: string
2
+
3
+ export type Provider = 'openai' | 'anthropic' | 'gemini' | 'mistral' | 'openrouter' | 'azure' | 'bedrock'
4
+
5
+ export type Reason =
6
+ | 'over_budget' | 'request_limit' | 'customer_limit' | 'run_limit' | 'hourly_limit'
7
+ | 'billing_inactive' | 'kill_switch' | 'key_paused' | 'budget_paused'
8
+ | 'policy_provider' | 'policy_model' | 'policy_time' | 'customer_required'
9
+ | 'rate_limit' | 'loop_detected' | 'spend_spike'
10
+ | 'approval_required' | 'approval_pending' | 'approval_denied' | 'approval_limit'
11
+
12
+ export type ApprovalState = 'pending' | 'approved' | 'denied' | 'expired' | 'used'
13
+
14
+ export interface XpenvoOptions {
15
+ /** Your Xpenvo agent key (xpv_...). Keep it in an environment variable. */
16
+ key: string
17
+ /** Default https://agents.xpenvo.com */
18
+ base?: string
19
+ /** Run id: every request with the same id is one run in the Flight Recorder. */
20
+ run?: string
21
+ /** A label for the current step of the run. */
22
+ step?: string
23
+ /** Your own id for the end customer (never an email address). */
24
+ customer?: string
25
+ /** Wait for a person to approve a big request, then resend it. Default true. */
26
+ waitForApproval?: boolean
27
+ /** Give up waiting for approval after this long. Default 10 minutes. */
28
+ approvalTimeoutMs?: number
29
+ /** How often to check an approval. Default 5000, at least 1000. */
30
+ pollMs?: number
31
+ /** Cheaper model(s) to use when a money limit would block the request (up to three, in order). */
32
+ fallbackModel?: string | string[]
33
+ /** If Xpenvo cannot check the budget or cannot be reached, send straight to the provider, unmetered. Default false. */
34
+ failOpen?: boolean
35
+ /** Called whenever a request went out unmetered because of failOpen. */
36
+ onUnmetered?: (info: { reason: string; url: string }) => void
37
+ /** The fetch to use underneath. Default globalThis.fetch. */
38
+ fetch?: typeof fetch
39
+ }
40
+
41
+ export type SpendInput =
42
+ | { label: string; usd: number }
43
+ | { label: string; maxUsd: number; ttlMinutes?: number }
44
+
45
+ export interface SpendResult {
46
+ id: string
47
+ state: 'settled' | 'held' | 'released'
48
+ chargedUsd?: number
49
+ heldUsd?: number
50
+ expiresAt?: string
51
+ overHold?: boolean
52
+ }
53
+
54
+ export interface KeyStatus {
55
+ key: string
56
+ canSpend: boolean
57
+ paused: boolean
58
+ killSwitch: boolean
59
+ leftUsd: number
60
+ budgets: { name: string; period: string; timeZone: string; limitUsd: number; leftUsd: number; paused: boolean }[]
61
+ }
62
+
63
+ export interface Xpenvo {
64
+ baseURL(provider: 'azure', resource: string): string
65
+ baseURL(provider: 'bedrock', region: string): string
66
+ baseURL(provider: Exclude<Provider, 'azure' | 'bedrock'>): string
67
+ headers(extra?: Record<string, string>): Record<string, string>
68
+ with(change: Partial<XpenvoOptions>): Xpenvo
69
+ approvalStatus(id: string): Promise<ApprovalState>
70
+ waitForApproval(id: string, timeoutMs?: number): Promise<boolean>
71
+ fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>
72
+ withApproval<T>(call: () => Promise<T>): Promise<T>
73
+ spend(input: SpendInput): Promise<SpendResult>
74
+ settle(id: string, usd: number): Promise<SpendResult>
75
+ release(id: string): Promise<SpendResult>
76
+ status(): Promise<KeyStatus>
77
+ }
78
+
79
+ export declare function xpenvo(options: XpenvoOptions): Xpenvo
80
+ export declare function reason(errOrResponse: unknown): Reason | string | null
81
+ export declare const REASONS: Record<Reason, string>
82
+ export declare function newRunId(prefix?: string): string
package/xpenvo.mjs ADDED
@@ -0,0 +1,306 @@
1
+ /**
2
+ * Xpenvo Agents for JavaScript and TypeScript. No dependencies; works in Node 18+, Deno, Bun,
3
+ * Cloudflare Workers and browsers' server-side runtimes.
4
+ *
5
+ * It does a few small things for an agent that already uses a provider's own SDK:
6
+ * 1. gives the Xpenvo address for each provider (baseURL),
7
+ * 2. adds your agent key and the optional run, step and end-customer labels (headers),
8
+ * 3. waits for a person to approve a big request, then sends it again (fetch / withApproval),
9
+ * 4. tells you why Xpenvo stopped a request (reason),
10
+ * 5. names cheaper models to fall back to when money runs short (fallbackModel),
11
+ * 6. optionally keeps your agent running if Xpenvo itself is down (failOpen),
12
+ * 7. checks and records spending that is not a model call: tools, search APIs (spend),
13
+ * 8. tells you how much this key can still spend (status).
14
+ *
15
+ * Privacy: it never reads, logs or sends your prompts anywhere except to Xpenvo, exactly as your
16
+ * agent would without it. Run, step and customer labels must be your own ids, never an email.
17
+ */
18
+
19
+ export const DEFAULT_BASE = 'https://agents.xpenvo.com'
20
+ const TAG = /^[A-Za-z0-9_.:-]{1,64}$/
21
+
22
+ /** Why Xpenvo stopped a request, as a short code (see REASONS), or null if it was not Xpenvo. */
23
+ export function reason(errOrResponse) {
24
+ const h = errOrResponse?.headers
25
+ if (!h) return null
26
+ const v = typeof h.get === 'function' ? h.get('x-xpenvo-error') : h['x-xpenvo-error']
27
+ return typeof v === 'string' && v ? v : null
28
+ }
29
+
30
+ /** Plain-language meaning of each reason code. */
31
+ export const REASONS = {
32
+ over_budget: 'A budget would go over its limit.',
33
+ request_limit: 'One request could cost more than the per-request limit.',
34
+ customer_limit: 'This end customer reached their limit.',
35
+ run_limit: 'This run reached its spending limit.',
36
+ hourly_limit: 'This key reached its hourly limit.',
37
+ billing_inactive: 'The organisation has no active plan.',
38
+ kill_switch: 'The kill switch is on.',
39
+ key_paused: 'This key is paused.',
40
+ budget_paused: 'The budget is paused.',
41
+ policy_provider: 'The budget does not allow this provider.',
42
+ policy_model: 'The budget does not allow this model.',
43
+ policy_time: 'The budget may not be used at this time.',
44
+ customer_required: 'The budget needs an end customer id on every request.',
45
+ rate_limit: 'Too many requests a minute. Retry shortly.',
46
+ loop_detected: 'The key sent the same request again and again, so it was paused.',
47
+ spend_spike: 'The key spent far faster than usual, so it was paused.',
48
+ approval_required: 'A person must approve this request first.',
49
+ approval_pending: 'Still waiting for approval.',
50
+ approval_denied: 'A person denied this request.',
51
+ approval_limit: 'Too many approvals are waiting.',
52
+ }
53
+
54
+ /** A random run id, for the Flight Recorder. */
55
+ export function newRunId(prefix = 'run') {
56
+ const b = crypto.getRandomValues(new Uint8Array(8))
57
+ return `${prefix}_${[...b].map(x => x.toString(16).padStart(2, '0')).join('')}`
58
+ }
59
+
60
+ function checkTag(name, v) {
61
+ if (v === undefined || v === null || v === '') return undefined
62
+ if (typeof v !== 'string' || !TAG.test(v) || v.includes('@')) {
63
+ throw new TypeError(`xpenvo: ${name} must be 1-64 letters, digits, _ . : or - (and never an email address)`)
64
+ }
65
+ return v
66
+ }
67
+
68
+ const sleep = ms => new Promise(r => setTimeout(r, ms))
69
+ const MODEL = /^[A-Za-z0-9_.:/-]{1,128}$/
70
+
71
+ function checkModels(v) {
72
+ if (v === undefined || v === null || v === '') return []
73
+ const list = (Array.isArray(v) ? v : String(v).split(',')).map(m => String(m).trim()).filter(Boolean)
74
+ if (list.length > 3 || list.some(m => !MODEL.test(m))) throw new TypeError('xpenvo: fallbackModel takes up to three model names')
75
+ return list
76
+ }
77
+
78
+ /**
79
+ * The provider's own address for a request that was meant for Xpenvo, used only by failOpen when
80
+ * Xpenvo cannot be reached. The Xpenvo headers are removed; your provider key goes as usual.
81
+ */
82
+ function directRequest(req, base) {
83
+ const u = new URL(req.url)
84
+ if (!req.url.startsWith(base)) return null
85
+ const p = u.pathname
86
+ let to = null
87
+ const fixed = {
88
+ '/v1/chat/completions': 'https://api.openai.com/v1/chat/completions',
89
+ '/v1/responses': 'https://api.openai.com/v1/responses',
90
+ '/v1/messages': 'https://api.anthropic.com/v1/messages',
91
+ '/v1/messages/count_tokens': 'https://api.anthropic.com/v1/messages/count_tokens',
92
+ '/v1/gemini/chat/completions': 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions',
93
+ '/v1/mistral/chat/completions': 'https://api.mistral.ai/v1/chat/completions',
94
+ '/v1/openrouter/chat/completions': 'https://openrouter.ai/api/v1/chat/completions',
95
+ }
96
+ if (Object.hasOwn(fixed, p)) to = fixed[p]
97
+ let m = /^\/v1\/azure\/([a-z0-9][a-z0-9-]{1,62})\/(chat\/completions|responses)$/.exec(p)
98
+ if (m) to = `https://${m[1]}.openai.azure.com/openai/v1/${m[2]}`
99
+ m = /^\/v1\/bedrock\/([a-z]{2}(?:-gov)?-[a-z]+-\d)\/model\/([^/]{1,200})\/converse$/.exec(p)
100
+ if (m) to = `https://bedrock-runtime.${m[1]}.amazonaws.com/model/${m[2]}/converse`
101
+ if (!to) return null
102
+ const headers = new Headers(req.headers)
103
+ for (const k of [...headers.keys()]) if (k.toLowerCase().startsWith('x-xpenvo-')) headers.delete(k)
104
+ return new Request(to + u.search, { method: req.method, headers, body: req.body, duplex: 'half' })
105
+ }
106
+
107
+ /**
108
+ * @param {object} o
109
+ * @param {string} o.key your Xpenvo agent key (xpv_...). Keep it in an environment variable.
110
+ * @param {string} [o.base] Xpenvo address, default https://agents.xpenvo.com
111
+ * @param {string} [o.run] a run id: every request with the same id is one run in the Flight Recorder
112
+ * @param {string} [o.step] a label for the current step of the run
113
+ * @param {string} [o.customer] your own id for the end customer this request is for
114
+ * @param {boolean} [o.waitForApproval] wait for a person to approve a big request (default true)
115
+ * @param {number} [o.approvalTimeoutMs] give up waiting after this long (default 10 minutes)
116
+ * @param {number} [o.pollMs] how often to check an approval (default 5 seconds)
117
+ * @param {string|string[]} [o.fallbackModel] cheaper model(s) to use when a budget, run, customer or
118
+ * hourly limit would block the request (up to three, tried in order)
119
+ * @param {boolean} [o.failOpen] if Xpenvo cannot check the budget (or cannot be reached at all,
120
+ * when you use x.fetch), send the request straight to the provider,
121
+ * unmetered, instead of failing. Default false (fail closed).
122
+ * @param {(info: {reason: string, url: string}) => void} [o.onUnmetered] called whenever a request
123
+ * went out unmetered because of failOpen
124
+ * @param {typeof fetch} [o.fetch] the fetch to use underneath (default globalThis.fetch)
125
+ */
126
+ export function xpenvo(o) {
127
+ if (!o || typeof o.key !== 'string' || !o.key) throw new TypeError('xpenvo: key is required')
128
+ const base = (o.base ?? DEFAULT_BASE).replace(/\/+$/, '')
129
+ if (!/^https:\/\//.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(base)) throw new TypeError('xpenvo: base must be an https address')
130
+ const opts = {
131
+ key: o.key, base,
132
+ run: checkTag('run', o.run), step: checkTag('step', o.step), customer: checkTag('customer', o.customer),
133
+ waitForApproval: o.waitForApproval !== false,
134
+ approvalTimeoutMs: o.approvalTimeoutMs ?? 10 * 60_000,
135
+ pollMs: Math.max(1000, o.pollMs ?? 5000),
136
+ fetch: o.fetch ?? globalThis.fetch.bind(globalThis),
137
+ fallback: checkModels(o.fallbackModel),
138
+ failOpen: o.failOpen === true,
139
+ onUnmetered: typeof o.onUnmetered === 'function' ? o.onUnmetered : null,
140
+ }
141
+
142
+ /** POST or DELETE to an Xpenvo endpoint; throws an Error with .code and .status when refused. */
143
+ async function xcall(method, path, body) {
144
+ const headers = api.headers({ 'content-type': 'application/json' })
145
+ delete headers['X-Xpenvo-Fallback-Model']
146
+ delete headers['X-Xpenvo-Fail-Open']
147
+ const r = await opts.fetch(`${base}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) })
148
+ const text = await r.text()
149
+ let json = null
150
+ try { json = JSON.parse(text) } catch {}
151
+ if (!r.ok) {
152
+ const e = new Error(json?.error?.message ?? `Xpenvo answered ${r.status}`)
153
+ e.status = r.status
154
+ e.code = r.headers.get('x-xpenvo-error') ?? json?.error?.code ?? null
155
+ e.approvalId = r.headers.get('x-xpenvo-approval')
156
+ e.headers = r.headers
157
+ throw e
158
+ }
159
+ return json
160
+ }
161
+
162
+ const api = {
163
+ /** The base URL to give your provider's SDK. For Azure pass the resource name, for Bedrock the region. */
164
+ baseURL(provider, where) {
165
+ switch (provider) {
166
+ case 'openai': return `${base}/v1`
167
+ case 'anthropic': return base
168
+ case 'gemini': return `${base}/v1/gemini`
169
+ case 'mistral': return `${base}/v1/mistral`
170
+ case 'openrouter': return `${base}/v1/openrouter`
171
+ case 'azure':
172
+ if (!/^[a-z0-9][a-z0-9-]{1,62}$/.test(where ?? '')) throw new TypeError('xpenvo: give the Azure resource name, e.g. baseURL("azure", "my-resource")')
173
+ return `${base}/v1/azure/${where}`
174
+ case 'bedrock':
175
+ if (!/^[a-z]{2}(-gov)?-[a-z]+-\d$/.test(where ?? '')) throw new TypeError('xpenvo: give the AWS region, e.g. baseURL("bedrock", "us-east-1")')
176
+ return `${base}/v1/bedrock/${where}`
177
+ default: throw new TypeError(`xpenvo: unknown provider "${provider}"`)
178
+ }
179
+ },
180
+
181
+ /** Headers to add to every request (defaultHeaders in the OpenAI and Anthropic SDKs). */
182
+ headers(extra = {}) {
183
+ const h = { 'X-Xpenvo-Key': opts.key, ...extra }
184
+ if (opts.run) h['X-Xpenvo-Run'] = opts.run
185
+ if (opts.step) h['X-Xpenvo-Step'] = opts.step
186
+ if (opts.customer) h['X-Xpenvo-Customer'] = opts.customer
187
+ if (opts.fallback.length) h['X-Xpenvo-Fallback-Model'] = opts.fallback.join(',')
188
+ if (opts.failOpen) h['X-Xpenvo-Fail-Open'] = 'true'
189
+ return h
190
+ },
191
+
192
+ /** The same settings with a different run, step or customer. */
193
+ with(change) {
194
+ return xpenvo({ ...o, ...change })
195
+ },
196
+
197
+ /** Is approval `id` approved yet? Returns 'pending', 'approved', 'denied', 'expired' or 'used'. */
198
+ async approvalStatus(id) {
199
+ if (!/^apr_[0-9a-f]{16}$/.test(id)) throw new TypeError('xpenvo: not an approval id')
200
+ const r = await opts.fetch(`${base}/v1/xpenvo/approvals/${id}`, { headers: { 'X-Xpenvo-Key': opts.key } })
201
+ if (!r.ok) {
202
+ await r.body?.cancel?.()
203
+ return r.status === 404 ? 'expired' : 'pending'
204
+ }
205
+ return (await r.json()).state
206
+ },
207
+
208
+ /** Wait until approval `id` is decided. True when approved. */
209
+ async waitForApproval(id, timeoutMs = opts.approvalTimeoutMs) {
210
+ const until = Date.now() + timeoutMs
211
+ while (Date.now() < until) {
212
+ const s = await api.approvalStatus(id)
213
+ if (s === 'approved') return true
214
+ if (s !== 'pending') return false
215
+ await sleep(opts.pollMs)
216
+ }
217
+ return false
218
+ },
219
+
220
+ /**
221
+ * A fetch that adds the headers and, when Xpenvo asks for approval, waits for a person and then
222
+ * sends the exact same request again. Give it to the SDK: new OpenAI({ fetch: x.fetch, ... }).
223
+ */
224
+ async fetch(input, init) {
225
+ const req = new Request(input, init)
226
+ for (const [k, v] of Object.entries(api.headers())) if (!req.headers.has(k)) req.headers.set(k, v)
227
+ let first
228
+ try {
229
+ first = await opts.fetch(req.clone())
230
+ } catch (e) {
231
+ // Xpenvo could not be reached at all.
232
+ const direct = opts.failOpen ? directRequest(req, base) : null
233
+ if (!direct) throw e
234
+ opts.onUnmetered?.({ reason: 'xpenvo_unreachable', url: direct.url })
235
+ return opts.fetch(direct)
236
+ }
237
+ // A gateway error that did not come from Xpenvo's own code (no request id): Xpenvo is down.
238
+ if (opts.failOpen && first.status >= 500 && !first.headers.get('x-xpenvo-request-id')) {
239
+ const direct = directRequest(req, base)
240
+ if (direct) {
241
+ await first.body?.cancel?.()
242
+ opts.onUnmetered?.({ reason: 'xpenvo_unavailable', url: direct.url })
243
+ return opts.fetch(direct)
244
+ }
245
+ }
246
+ const unmetered = first.headers.get('x-xpenvo-unmetered')
247
+ if (unmetered) opts.onUnmetered?.({ reason: unmetered, url: req.url })
248
+ const id = first.status === 402 ? first.headers.get('x-xpenvo-approval') : null
249
+ const code = first.headers.get('x-xpenvo-error')
250
+ if (!opts.waitForApproval || !id || (code !== 'approval_required' && code !== 'approval_pending')) return first
251
+ if (!(await api.waitForApproval(id))) return first
252
+ await first.body?.cancel?.()
253
+ return opts.fetch(req)
254
+ },
255
+
256
+ /**
257
+ * Check and record spending that is not a model call (a search API, a browser session, a paid
258
+ * tool). The same budgets, run and customer limits, approvals and kill switch apply.
259
+ * await x.spend({ label: 'serpapi', usd: 0.005 }) charge a known price now
260
+ * const h = await x.spend({ label: 'browser', maxUsd: 0.5 }) hold the most it could cost
261
+ * await x.settle(h.id, 0.12) or await x.release(h.id)
262
+ * Throws an Error with .code (e.g. 'over_budget', 'run_limit') when the spending is refused.
263
+ */
264
+ spend(o) {
265
+ return xcall('POST', '/v1/xpenvo/spend', o)
266
+ },
267
+ /** Charge the real cost of a held spend and free the rest. */
268
+ settle(id, usd) {
269
+ return xcall('POST', `/v1/xpenvo/spend/${encodeURIComponent(id)}`, { usd })
270
+ },
271
+ /** The held spend did not happen: free it all. */
272
+ release(id) {
273
+ return xcall('DELETE', `/v1/xpenvo/spend/${encodeURIComponent(id)}`)
274
+ },
275
+ /** How much this key can still spend: { canSpend, leftUsd, paused, budgets: [...] }. */
276
+ async status() {
277
+ const r = await opts.fetch(`${base}/v1/xpenvo/status`, { headers: { 'X-Xpenvo-Key': opts.key } })
278
+ const json = await r.json().catch(() => null)
279
+ if (!r.ok) {
280
+ const e = new Error(json?.error?.message ?? `Xpenvo answered ${r.status}`)
281
+ e.status = r.status
282
+ e.code = r.headers.get('x-xpenvo-error')
283
+ throw e
284
+ }
285
+ return json
286
+ },
287
+
288
+ /**
289
+ * Run `call` (any SDK call); if Xpenvo asks for approval, wait for a person and run it again.
290
+ * Use this when you cannot pass a custom fetch to your SDK.
291
+ */
292
+ async withApproval(call) {
293
+ try {
294
+ return await call()
295
+ } catch (e) {
296
+ const h = e?.headers
297
+ const id = h ? (typeof h.get === 'function' ? h.get('x-xpenvo-approval') : h['x-xpenvo-approval']) : null
298
+ const code = reason(e)
299
+ if (!opts.waitForApproval || !id || (code !== 'approval_required' && code !== 'approval_pending')) throw e
300
+ if (!(await api.waitForApproval(id))) throw e
301
+ return call()
302
+ }
303
+ },
304
+ }
305
+ return api
306
+ }