diff --git a/CHANGELOG.md b/CHANGELOG.md index e53bb744..59526769 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,37 @@ # Changelog +## Franklin Agent 3.49.29 — Modal: no signing without a price, the real charge in the result, terminate refunds nothing + +Upgrade if you use Modal sandboxes. Follow-ups to 3.49.28. + +- **ModalTerminate no longer implies it saves money.** Its tool text said Modal + bills GPU time until the sandbox is terminated. ModalCreate charges the whole + requested `timeout` upfront and terminating early refunds nothing, so a model + reading the old text could pick a 24 h lifetime expecting to stop the meter + early. It now says terminate stops the sandbox and frees resources, refunds + nothing, and that the timeout should be chosen at create. It also no longer + claims that sandboxes are terminated automatically at session end. +- **`gpu: ""` cannot bypass the quote check.** An empty gpu priced as nothing: + the confirm dialog crashed, and with no dialog the call went out with no + wallet reservation and no quote ceiling. A blank gpu now means CPU, and any + other value must name a GPU tier. Every Modal call now refuses to sign when + Franklin cannot compute the expected price, instead of signing whatever the + gateway asks. +- **The "charged:" line shows what was paid.** It showed Franklin's list price, + which is the Solana rate; the Base gateway's hourly rates are lower (A100 for + 600 s: $0.667667 on Base, shown as $1.17). Franklin now reports the gateway's + stated charge, or else the exact quote it signed, and labels the list price + as an estimate when neither is available. `franklin stats` records the same + figure. +- **Exec, status and terminate reserve what they may sign**: the price plus the + Base $0.001 fee, as create already did. +- **"flat floor" wording.** A large or long create whose hourly price is below + the flat rate now says it is charged the flat floor, instead of quoting the + flat-rate conditions it does not meet. +- **A refused ModalTerminate is an error.** When the quote check refuses a + terminate, or the gateway answers 5xx, the result is an error and the + sandbox stays in the session's list instead of being reported as done. + ## Franklin Agent 3.49.28 — Modal sandboxes can live up to 24 hours, and Franklin never signs more than it expected Upgrade if you use Modal sandboxes. diff --git a/package-lock.json b/package-lock.json index 7f4ee415..15d9c466 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@blockrun/franklin", - "version": "3.49.28", + "version": "3.49.29", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@blockrun/franklin", - "version": "3.49.28", + "version": "3.49.29", "license": "Apache-2.0", "workspaces": [ "apps/desktop" diff --git a/package.json b/package.json index d7201a9e..c35c07f7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@blockrun/franklin", - "version": "3.49.28", + "version": "3.49.29", "description": "Franklin Agent — The AI agent with a wallet. Spends USDC autonomously to get real work done. Pay per action, no subscriptions.", "type": "module", "exports": { diff --git a/src/agent/tool-guard.ts b/src/agent/tool-guard.ts index 7741eb0b..3ca22c76 100644 --- a/src/agent/tool-guard.ts +++ b/src/agent/tool-guard.ts @@ -377,10 +377,11 @@ export class SessionToolGuard { scope: ExecutionScope ): Promise { // Hard-block tools that have failed too many times this session. - // Modal lifecycle tools are exempt: orphan sandboxes keep billing - // GPU time, and ModalTerminate is the only way to recover from - // agent-side. Auto-disabling it after 3 transient errors would - // strand a $0.40/hr H100 until the session ends. Same logic for + // Modal lifecycle tools are exempt: ModalTerminate is the only way to + // stop a sandbox agent-side. A sandbox's whole lifetime is charged + // upfront at create (terminating refunds nothing), but auto-disabling + // ModalTerminate after 3 transient errors would leave a GPU sandbox + // running, holding resources, until its timeout. Same logic for // media-gen tools: failures are usually transient (gateway hiccup, // prompt rejection) and the user often wants to retry. const FAILURE_EXEMPT = new Set([ diff --git a/src/tools/modal.ts b/src/tools/modal.ts index d321b8de..87341641 100644 --- a/src/tools/modal.ts +++ b/src/tools/modal.ts @@ -26,11 +26,15 @@ * - No upload/download endpoints — files in/out via exec heredoc / curl. * * Lifecycle: - * ModalCreate → returns sandbox_id, charged at GPU tier + * ModalCreate → returns sandbox_id; the whole requested lifetime is charged + * here, upfront * ModalExec → sync, returns { stdout, stderr, exit_code } * ModalStatus → check running/terminated - * ModalTerminate → release; called automatically at session end via - * the SessionSandboxTracker registry. + * ModalTerminate → stops the sandbox and frees its resources. It refunds + * nothing: the lifetime was paid at create. Nothing calls + * it automatically today (terminateAllSessionSandboxes has + * no caller), so an unterminated sandbox runs until its + * timeout — already paid for, so no further charge. */ import { @@ -51,6 +55,7 @@ import { recordUsage } from '../stats/tracker.js'; import { logger } from '../logger.js'; import { noChargeNote } from '../payments/billing-copy.js'; import { GATEWAY_TRANSACTION_FEE_USD } from '../gateway-models.js'; +import { chargeFromResponse } from '../payments/price-catalog.js'; // ─── Pricing table (probed from /.well-known/x402 + 402 responses) ───────── const CREATE_PRICE_USD: Record = { @@ -94,6 +99,12 @@ export interface ModalCreatePricing { model: 'flat' | 'hourly'; /** Set when model === 'hourly'. */ hourlyRateUsd?: number; + /** + * True when the request is NOT flat-eligible (lifetime > 300 s, cpu > 1 or + * memory > 1024 MB) but its hourly price is below the flat rate, so the flat + * rate applies as a floor. The flat-eligibility rule does not describe it. + */ + flatFloor?: boolean; } /** @@ -108,6 +119,11 @@ export function modalCreatePricing( memory?: number, timeoutSeconds: number = DEFAULT_TIMEOUT_SECONDS, ): ModalCreatePricing { + // Fail closed: an unknown tier has no price, and an undefined price would + // reach the reservation and the quote ceiling as NaN. + if (!Object.prototype.hasOwnProperty.call(CREATE_PRICE_USD, tier)) { + throw new RangeError(`no Modal price for tier ${JSON.stringify(tier)}`); + } const flat = CREATE_PRICE_USD[tier]; const flatEligible = timeoutSeconds <= FLAT_RATE_MAX_SECONDS && @@ -117,6 +133,7 @@ export function modalCreatePricing( const hourlyRateUsd = HOURLY_PRICE_USD[tier]; const hourlyPrice = hourlyRateUsd * (timeoutSeconds / 3600); if (hourlyPrice > flat) return { priceUsd: hourlyPrice, model: 'hourly', hourlyRateUsd }; + return { priceUsd: flat, model: 'flat', flatFloor: true }; } return { priceUsd: flat, model: 'flat' }; } @@ -137,6 +154,11 @@ export function modalCreatePriceUsd( * in atomic units (1 USDC = 1_000_000). */ export function maxSignableAtomic(listPriceUsd: number): bigint { + // Fail closed on a price that is not a real number: NaN would otherwise + // throw deep inside BigInt() where a caller may swallow it. + if (typeof listPriceUsd !== 'number' || !Number.isFinite(listPriceUsd) || listPriceUsd < 0) { + throw new RangeError(`no quote ceiling for list price ${String(listPriceUsd)}`); + } // Round the micro-dollar figure to 3 places first so float noise // (0.1 + 0.001 = 0.10100000000000001) does not ceil an exact figure up a unit. const micro = Math.ceil(Number(((listPriceUsd + QUOTE_FEE_ALLOWANCE_USD) * 1e6).toFixed(3))); @@ -155,12 +177,13 @@ const TERMINATE_PRICE_USD = 0.001; const VALID_GPUS = new Set(Object.keys(CREATE_PRICE_USD).filter(g => g !== 'cpu')); // ─── Session sandbox tracker ─────────────────────────────────────────────── -// In-memory registry of sandboxes created in the current session. Used by -// (1) the cleanup hook in vscode-session.ts to terminate orphans on session -// end, (2) the extension UI's "active sandboxes" badge. +// In-memory registry of sandboxes created in the current session, for +// terminateAllSessionSandboxes (no caller today; the VS Code session hook it +// was written for no longer exists). // // NOT persisted — sandboxes outlive the Franklin process via Modal's own -// timeout, so a missed cleanup is bounded by the user-set `timeout`. +// timeout. That lifetime was charged in full at create, so a missed cleanup +// costs no extra money; it only leaves the sandbox running until `timeout`. export interface SandboxRecord { id: string; @@ -314,22 +337,37 @@ function atomicToUsd(n: bigint): string { * already aborted before dispatch, DNS / connection-refused) are NOT * ambiguous and release normally. * - * `maxPriceUsd` is the list price this client expects for the call. When set, - * the 402's quote is checked BEFORE anything is signed: above - * maxSignableAtomic(maxPriceUsd), or unreadable, and nothing is signed or - * sent — the call returns 402 with `quote_exceeds_expected`. Without it a + * `maxPriceUsd` is the list price this client expects for the call, and it is + * required: the 402's quote is checked BEFORE anything is signed. A quote above + * maxSignableAtomic(maxPriceUsd), an unreadable quote, or a maxPriceUsd that is + * missing or not a finite non-negative number, and nothing is signed or sent — + * the call returns 402 with `quote_exceeds_expected`. Without the check a * gateway quoting a long-lifetime create at $216 would be signed blind while * the reservation held a fraction of that. + * + * `chargedUsd` / `signedUsd` report what this call actually cost, for the + * caller's "charged:" line and recordUsage (see modalCharge). */ +export interface ModalPostResult { + ok: boolean; + status: number; + body: Record; + raw: string; + /** The gateway's own statement of the charge (`x-blockrun-cost-usd`), or null. */ + chargedUsd: number | null; + /** The 402 quote this client signed and sent, in USD; null when nothing was signed. */ + signedUsd: number | null; +} + export async function postWithPayment( endpoint: string, body: Record, resourceDescription: string, abortSignal: AbortSignal, timeoutMs: number, - reservation?: ReservationToken | null, - maxPriceUsd?: number, -): Promise<{ ok: boolean; status: number; body: Record; raw: string }> { + reservation: ReservationToken | null, + maxPriceUsd: number, +): Promise { const chain = loadChain(); const headers: Record = { ...gatewayHeaders(), @@ -341,28 +379,44 @@ export async function postWithPayment( abortSignal.addEventListener('abort', onParentAbort, { once: true }); const timer = setTimeout(() => ctrl.abort(), timeoutMs); let paymentDispatched = false; + let signedUsd: number | null = null; + const refuse = (error: string): ModalPostResult => { + logger.warn(`[franklin] Modal ${endpoint}: ${error}`); + return { ok: false, status: 402, body: { error }, raw: '', chargedUsd: null, signedUsd: null }; + }; try { const payload = JSON.stringify(body); let response = await fetch(endpoint, { method: 'POST', signal: ctrl.signal, headers, body: payload }); if (response.status === 402 && walletMayPay(headers)) { - if (maxPriceUsd !== undefined) { - const quoted = await quotedAtomic(response, chain); - const ceiling = maxSignableAtomic(maxPriceUsd); - if (quoted === null || quoted > ceiling) { - const error = quoted === null - ? 'quote_exceeds_expected: the 402 carried no readable amount, so nothing was signed' - : `quote_exceeds_expected: the gateway asked ${atomicToUsd(quoted)}, above the ` + - `${atomicToUsd(ceiling)} this client expected, so nothing was signed`; - logger.warn(`[franklin] Modal ${endpoint}: ${error}`); - return { ok: false, status: 402, body: { error }, raw: '' }; - } + // Fail closed: no computable ceiling means no signature, never a blind one. + let ceiling: bigint; + try { + ceiling = maxSignableAtomic(maxPriceUsd); + } catch { + return refuse( + `quote_exceeds_expected: this client has no expected price for the call ` + + `(${String(maxPriceUsd)}), so nothing was signed`, + ); + } + const quoted = await quotedAtomic(response, chain); + if (quoted === null) { + return refuse('quote_exceeds_expected: the 402 carried no readable amount, so nothing was signed'); + } + if (quoted > ceiling) { + return refuse( + `quote_exceeds_expected: the gateway asked ${atomicToUsd(quoted)}, above the ` + + `${atomicToUsd(ceiling)} this client expected, so nothing was signed`, + ); } const paymentHeaders = await paymentSigner(response, chain, endpoint, resourceDescription); if (!paymentHeaders) { - return { ok: false, status: 402, body: { error: 'payment signing failed' }, raw: '' }; + return { ok: false, status: 402, body: { error: 'payment signing failed' }, raw: '', chargedUsd: null, signedUsd: null }; } + // signPayment signs the amount quotedAtomic just read (same option + // selection), so this is the figure the settlement moves. + signedUsd = Number(quoted) / 1e6; // Signing can take a while (wallet load, Solana RPC). If the budget // expired meanwhile, fetch rejects before writing a byte — that is a // definite non-payment, not an ambiguous one. @@ -387,7 +441,14 @@ export async function postWithPayment( } let parsed: Record = {}; try { parsed = raw ? JSON.parse(raw) : {}; } catch { /* leave as {} */ } - return { ok: response.ok, status: response.status, body: parsed, raw }; + return { + ok: response.ok, + status: response.status, + body: parsed, + raw, + chargedUsd: chargeFromResponse(response), + signedUsd, + }; } catch (err) { if (paymentDispatched && reservation && !definitelyNotSent(err)) { // Signed request went out; abort/timeout hit before we saw the result. @@ -407,6 +468,35 @@ export async function postWithPayment( } } +/** + * What a successful Modal call cost, for the "charged:" line and recordUsage. + * The gateway's `x-blockrun-cost-usd` wins; next the 402 quote this client + * signed (an exact-scheme payment settles that amount); otherwise the client's + * list price, flagged as an estimate. The list price is the sol/arc/nano rate + * and the Base gateway's hourly rates are lower, so presenting it as the + * settled amount overstated Base hourly creates by up to ~2.5x. + */ +export function modalCharge( + res: Pick, + listPriceUsd: number, +): { usd: number; estimated: boolean } { + if (typeof res.chargedUsd === 'number') return { usd: res.chargedUsd, estimated: false }; + if (typeof res.signedUsd === 'number') return { usd: res.signedUsd, estimated: false }; + return { usd: listPriceUsd, estimated: true }; +} + +/** A settled amount to the micro-dollar, trailing zeros trimmed, at least 2 places. */ +function fmtUsdExact(n: number): string { + const [whole, frac = ''] = n.toFixed(6).split('.'); + return `$${whole}.${frac.replace(/0+$/, '').padEnd(2, '0')}`; +} + +function describeCharge(charge: { usd: number; estimated: boolean }): string { + return charge.estimated + ? `~${fmtUsd(charge.usd)} estimated (list price; the gateway did not report the settled amount)` + : fmtUsdExact(charge.usd); +} + // ─── Helpers ───────────────────────────────────────────────────────────── /** Explain why hold() refused, so the agent does not loop on "wait". */ @@ -541,16 +631,23 @@ export const modalCreateCapability: CapabilityHandler = { // 400s on either, leaving the agent confused (it sees "Invalid // request body" with no actionable hint). Fix the obvious mistakes // before they leave the client. - let gpu = raw.gpu; - if (typeof gpu === 'string') { - const matched = [...VALID_GPUS].find(g => g.toLowerCase() === gpu!.toLowerCase()); - if (matched) gpu = matched; - } - if (gpu && !VALID_GPUS.has(gpu)) { - return { - output: `Error: invalid gpu "${gpu}". Allowed: ${[...VALID_GPUS].join(', ')} (or omit for CPU).`, - isError: true, - }; + // An absent, null or blank gpu means CPU. Anything else must name a GPU + // tier exactly (after case/whitespace folding): `gpu: ""` used to fall + // through as tier "" with no price, which crashed the confirm dialog and, + // headless, skipped both the reservation and the quote ceiling. + const rawGpu: unknown = raw.gpu; + let gpu: string | undefined; + if (rawGpu === undefined || rawGpu === null || (typeof rawGpu === 'string' && rawGpu.trim() === '')) { + gpu = undefined; + } else { + const wanted = typeof rawGpu === 'string' ? rawGpu.trim().toLowerCase() : null; + gpu = wanted === null ? undefined : [...VALID_GPUS].find(g => g.toLowerCase() === wanted); + if (!gpu) { + return { + output: `Error: invalid gpu ${JSON.stringify(rawGpu)}. Allowed: ${[...VALID_GPUS].join(', ')} (or omit for CPU).`, + isError: true, + }; + } } const tier = gpu ?? 'cpu'; @@ -593,16 +690,31 @@ export const modalCreateCapability: CapabilityHandler = { return { output: `Error: cpu must be at least ${MODAL_MIN_CPU}, got ${cpuCoerced}.`, isError: true }; } - const pricing = modalCreatePricing( - tier, - typeof cpuCoerced === 'number' ? cpuCoerced : undefined, - typeof memoryCoerced === 'number' ? memoryCoerced : undefined, - timeoutSec, - ); + // Fail closed: no price or no ceiling means no request at all. Both are + // computed here, before the dialog, the reservation or any network call, + // so nothing downstream can run with an undefined price. + let pricing: ModalCreatePricing; + let ceilingUsd: number; + try { + pricing = modalCreatePricing( + tier, + typeof cpuCoerced === 'number' ? cpuCoerced : undefined, + typeof memoryCoerced === 'number' ? memoryCoerced : undefined, + timeoutSec, + ); + ceilingUsd = maxSignableUsd(pricing.priceUsd); + } catch (err) { + return { + output: `Error: could not price this ModalCreate (${(err as Error).message}); nothing was sent or charged.`, + isError: true, + }; + } const price = pricing.priceUsd; const billingLine = pricing.model === 'hourly' ? `hourly: ${fmtUsd(pricing.hourlyRateUsd ?? 0)}/h x ${(timeoutSec / 3600).toFixed(2)} h, upfront, no refund on early terminate` - : 'flat (timeout <= 300 s, cpu <= 1, memory <= 1024 MB)'; + : pricing.flatFloor + ? 'flat floor: the hourly price for this size and lifetime is below the flat rate, so the flat rate is charged, upfront, no refund on early terminate' + : 'flat (timeout <= 300 s, cpu <= 1, memory <= 1024 MB)'; // ── AskUser cost preview (skipped if env auto-approve or non-UI mode) ── const autoApprove = process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL === '1'; @@ -634,18 +746,26 @@ export const modalCreateCapability: CapabilityHandler = { // Wallet reservation — block over-spend if other in-flight calls hold balance. // Hold the most we will sign (list price + Base fee), not the list price: // the quote guard in postWithPayment refuses anything above that ceiling. + // A balance read that fails resolves to Infinity inside hold(), so a throw + // here is a bad amount, not an RPC blip: refuse rather than create with no + // hold. let reservation: ReservationToken | null = null; try { - reservation = await walletReservation.hold(maxSignableUsd(price)); - if (!reservation) { - return { - output: - `Insufficient ${isKeyMode() ? 'account credit' : 'USDC'} for ModalCreate (${tier}, ~${fmtUsd(price)}). ` + - describeHeadroom(), - isError: true, - }; - } - } catch { /* fall through, x402 will surface real error */ } + reservation = await walletReservation.hold(ceilingUsd); + } catch (err) { + return { + output: `Error: could not reserve funds for ModalCreate (${(err as Error).message}); nothing was sent or charged.`, + isError: true, + }; + } + if (!reservation) { + return { + output: + `Insufficient ${isKeyMode() ? 'account credit' : 'USDC'} for ModalCreate (${tier}, ~${fmtUsd(price)}). ` + + describeHeadroom(), + isError: true, + }; + } try { const body: Record = {}; @@ -701,8 +821,10 @@ export const modalCreateCapability: CapabilityHandler = { }); // Stats — surface Modal usage in `franklin insights` like other paid tools. + // Record what settled, not the client's list price (see modalCharge). + const charge = modalCharge(res, price); try { - recordUsage(`modal/${tier}`, 0, 0, price, latencyMs); + recordUsage(`modal/${tier}`, 0, 0, charge.usd, latencyMs, false, charge.estimated); } catch { /* ignore */ } return { @@ -711,7 +833,7 @@ export const modalCreateCapability: CapabilityHandler = { `- id: \`${sandboxId}\`\n` + `- tier: ${tier === 'cpu' ? 'CPU only' : `GPU ${tier}`}\n` + `- timeout: ${timeoutSec}s (billed lifetime; terminating early refunds nothing)\n` + - `- charged: ${fmtUsd(price)} (${billingLine})\n\n` + + `- charged: ${describeCharge(charge)} (${billingLine})\n\n` + `Next: ModalExec({ sandbox_id: "${sandboxId}", command: ["python","-c","print(1)"] })`, }; } finally { @@ -777,10 +899,12 @@ export const modalExecCapability: CapabilityHandler = { }; } + // Hold the ceiling the quote guard may sign (list + Base fee + 1 unit), + // not the bare list price. For micro-cost calls a null hold (insufficient) + // does not block — the guard still caps what can be signed. let reservation: ReservationToken | null = null; try { - reservation = await walletReservation.hold(EXEC_PRICE_USD); - // For micro-cost calls don't hard-block on insufficient — just proceed. + reservation = await walletReservation.hold(maxSignableUsd(EXEC_PRICE_USD)); } catch { /* ignore */ } try { @@ -850,7 +974,8 @@ export const modalExecCapability: CapabilityHandler = { const hasAnyOutput = stdout.length > 0 || stderr.length > 0; const exitCode = rawExit !== null ? rawExit : (hasAnyOutput ? 0 : -1); - try { recordUsage('modal/exec', 0, 0, EXEC_PRICE_USD, latencyMs); } catch { /* ignore */ } + const charge = modalCharge(res, EXEC_PRICE_USD); + try { recordUsage('modal/exec', 0, 0, charge.usd, latencyMs, false, charge.estimated); } catch { /* ignore */ } const summary = `exit ${exitCode}` + (rawExit === null ? ' (inferred — no exit_code field in response)' : ''); const sections = [ @@ -892,7 +1017,7 @@ export const modalStatusCapability: CapabilityHandler = { if (!sandbox_id) return { output: 'Error: sandbox_id is required', isError: true }; let reservation: ReservationToken | null = null; - try { reservation = await walletReservation.hold(STATUS_PRICE_USD); } catch { /* ignore */ } + try { reservation = await walletReservation.hold(maxSignableUsd(STATUS_PRICE_USD)); } catch { /* ignore */ } try { const callStartedAt = Date.now(); @@ -912,7 +1037,8 @@ export const modalStatusCapability: CapabilityHandler = { return { output: `ModalStatus failed (${res.status}): ${err}`, isError: true }; } - try { recordUsage('modal/status', 0, 0, STATUS_PRICE_USD, latencyMs); } catch { /* ignore */ } + const charge = modalCharge(res, STATUS_PRICE_USD); + try { recordUsage('modal/status', 0, 0, charge.usd, latencyMs, false, charge.estimated); } catch { /* ignore */ } const status = (res.body.status as string) || 'unknown'; const extra = JSON.stringify(res.body, null, 2); @@ -929,11 +1055,12 @@ export const modalTerminateCapability: CapabilityHandler = { spec: { name: 'ModalTerminate', description: - 'Terminate a Modal sandbox and release its resources. Charges $0.001. ' + - 'Strongly recommended after every successful ModalExec sequence — ' + - 'Modal bills wall-clock GPU time until the sandbox terminates or hits ' + - 'its `timeout`. Session-end auto-cleanup also calls this for any sandboxes ' + - 'the agent forgot, but explicit is better.', + 'Terminate a Modal sandbox: stops it and anything running in it, frees its resources, ' + + 'and ModalExec on that id fails afterwards. Charges $0.001. ' + + 'It does NOT refund anything: ModalCreate already charged the full requested `timeout` ' + + 'upfront, so terminating early saves no money. Choose the timeout the work needs at ' + + 'ModalCreate. Call this when you are done with a sandbox so it does not hold resources ' + + 'until its timeout; nothing terminates sandboxes automatically when the session ends.', input_schema: { type: 'object', properties: { @@ -948,7 +1075,7 @@ export const modalTerminateCapability: CapabilityHandler = { if (!sandbox_id) return { output: 'Error: sandbox_id is required', isError: true }; let reservation: ReservationToken | null = null; - try { reservation = await walletReservation.hold(TERMINATE_PRICE_USD); } catch { /* ignore */ } + try { reservation = await walletReservation.hold(maxSignableUsd(TERMINATE_PRICE_USD)); } catch { /* ignore */ } try { const callStartedAt = Date.now(); @@ -963,20 +1090,33 @@ export const modalTerminateCapability: CapabilityHandler = { ); const latencyMs = Date.now() - callStartedAt; - // Always remove from tracker — even on failure, retrying is wasteful. - sessionSandboxTracker.remove(sandbox_id); - if (!res.ok) { const err = res.body.error ? String(res.body.error) : res.raw.slice(0, 300); + // 402 (a quote-guard refusal or failed signing: nothing was paid, so the + // terminate never ran) and 5xx leave the sandbox running as far as we + // know. Keep it tracked and report an error. Other 4xx (e.g. already + // terminated, unknown id) are benign: drop it from the tracker. + if (res.status === 402 || res.status >= 500) { + return { + output: + `ModalTerminate failed (${res.status}): ${err}\n\n` + + `The sandbox \`${sandbox_id}\` is probably still running and is still tracked. ` + + `It stops by itself at its create timeout (already paid for). Retry ModalTerminate if you need it stopped now.`, + isError: true, + }; + } + sessionSandboxTracker.remove(sandbox_id); return { output: `ModalTerminate returned ${res.status}: ${err}\n\n` + - `(Removed from local tracker regardless. Modal-side cleanup will happen at the timeout.)`, - isError: res.status >= 500, // 4xx (e.g. already-terminated) is benign + `(Removed from local tracker: the gateway reports no sandbox to terminate.)`, + isError: false, }; } - try { recordUsage('modal/terminate', 0, 0, TERMINATE_PRICE_USD, latencyMs); } catch { /* ignore */ } + sessionSandboxTracker.remove(sandbox_id); + const charge = modalCharge(res, TERMINATE_PRICE_USD); + try { recordUsage('modal/terminate', 0, 0, charge.usd, latencyMs, false, charge.estimated); } catch { /* ignore */ } return { output: `Sandbox \`${sandbox_id}\` terminated.` }; } finally { @@ -988,11 +1128,11 @@ export const modalTerminateCapability: CapabilityHandler = { // ─── Bulk session cleanup ──────────────────────────────────────────────── /** - * Terminate every sandbox the current session has created. Called from - * vscode-session.ts at session end (and the SessionToolGuard cleanup path) - * so a missed agent ModalTerminate doesn't leave Modal billing the user - * up to the per-sandbox timeout. Best-effort: failures are logged but - * don't block session shutdown. + * Terminate every sandbox the current session has created. Written for a + * session-end hook that no longer exists, so nothing calls it today. + * Terminating refunds nothing (each lifetime was charged upfront at create); + * it only stops sandboxes left running. Best-effort: failures are returned, + * not thrown. */ export async function terminateAllSessionSandboxes(opts: { abortSignal?: AbortSignal } = {}): Promise<{ attempted: number; diff --git a/src/wallet/reservation.ts b/src/wallet/reservation.ts index b221d1f7..e015ce40 100644 --- a/src/wallet/reservation.ts +++ b/src/wallet/reservation.ts @@ -162,8 +162,15 @@ class WalletReservationManager { * Try to reserve `amountUsd`. Returns a token on success, or null if * insufficient (balance - already-reserved < amountUsd). Caller MUST * release the token after the actual payment resolves, success or fail. + * + * Throws on an amount that is not a finite number. A NaN hold used to be + * granted (every comparison with NaN is false) and then poisoned the + * reserved total, so every later hold passed whatever the balance. */ async hold(amountUsd: number): Promise { + if (typeof amountUsd !== 'number' || !Number.isFinite(amountUsd)) { + throw new RangeError(`cannot reserve a non-finite amount (${String(amountUsd)})`); + } if (amountUsd <= 0) { // Free / zero-cost calls don't need accounting. return { id: `free-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, amountUsd: 0 }; diff --git a/test/local.mjs b/test/local.mjs index e1575486..e4f2f316 100644 --- a/test/local.mjs +++ b/test/local.mjs @@ -3511,13 +3511,13 @@ test('paid media and Modal tools pass measured latency to recordUsage', async () 'all four Modal paid calls must capture start time'); assert.equal((modal.match(/latencyMs = Date\.now\(\) - callStartedAt/g) ?? []).length, 4, 'all four Modal paid calls must compute latency'); - assert.match(modal, /recordUsage\(`modal\/\$\{tier\}`, 0, 0, price, latencyMs\)/, + assert.match(modal, /recordUsage\(`modal\/\$\{tier\}`, 0, 0, charge\.usd, latencyMs, false, charge\.estimated\)/, 'ModalCreate recordUsage must receive latencyMs'); - assert.match(modal, /recordUsage\('modal\/exec', 0, 0, EXEC_PRICE_USD, latencyMs\)/, + assert.match(modal, /recordUsage\('modal\/exec', 0, 0, charge\.usd, latencyMs, false, charge\.estimated\)/, 'ModalExec recordUsage must receive latencyMs'); - assert.match(modal, /recordUsage\('modal\/status', 0, 0, STATUS_PRICE_USD, latencyMs\)/, + assert.match(modal, /recordUsage\('modal\/status', 0, 0, charge\.usd, latencyMs, false, charge\.estimated\)/, 'ModalStatus recordUsage must receive latencyMs'); - assert.match(modal, /recordUsage\('modal\/terminate', 0, 0, TERMINATE_PRICE_USD, latencyMs\)/, + assert.match(modal, /recordUsage\('modal\/terminate', 0, 0, charge\.usd, latencyMs, false, charge\.estimated\)/, 'ModalTerminate recordUsage must receive latencyMs'); }); @@ -13109,6 +13109,8 @@ test('modalCreatePriceUsd bills a lifetime above 300 s hourly at any size, CPU i assert.equal(h.model, 'hourly'); assert.equal(h.hourlyRateUsd, 9); assert.ok(close(h.priceUsd, 9 * 301 / 3600)); - // Hourly-eligible (8 cores) but below the flat floor: the floor wins and the model says flat. - assert.deepEqual(modalCreatePricing('T4', 8, undefined, 10), { priceUsd: 0.05, model: 'flat' }); + // Hourly-eligible (8 cores) but below the flat floor: the floor wins, the model + // says flat, and flatFloor marks that the flat-eligibility rule does not apply. + assert.deepEqual(modalCreatePricing('T4', 8, undefined, 10), { priceUsd: 0.05, model: 'flat', flatFloor: true }); + assert.deepEqual(modalCreatePricing('T4', 1, 1024, 300), { priceUsd: 0.05, model: 'flat' }, 'genuinely flat-eligible: no floor flag'); }); diff --git a/test/reservation.local.mjs b/test/reservation.local.mjs index f447624f..088e00d5 100644 --- a/test/reservation.local.mjs +++ b/test/reservation.local.mjs @@ -10,6 +10,8 @@ const { walletReservation, AMBIGUOUS_GRACE_MS } = await import('../dist/wallet/r const { postWithPayment, _setPaymentSignerForTests } = await import('../dist/tools/modal.js'); const fixed = (v) => async () => v; +// Paid-tool success paths call recordUsage; keep them out of the real stats file. +process.env.FRANKLIN_NO_AUDIT = '1'; test('markAmbiguous keeps the amount counted and survives a later release()', async () => { walletReservation._resetForTests(fixed(0.10)); @@ -119,6 +121,12 @@ const realFetch = globalThis.fetch; after(() => { globalThis.fetch = realFetch; _setPaymentSignerForTests(null); }); function res402() { + return new Response(JSON.stringify({ + x402Version: 2, + accepts: [{ scheme: 'exact', network: 'eip155:8453', amount: '10000', payTo: '0xabc', asset: '0xusdc', maxTimeoutSeconds: 300 }], + }), { status: 402, headers: { 'content-type': 'application/json' } }); +} +function res402Unreadable() { return new Response(JSON.stringify({ accepts: [] }), { status: 402, headers: { 'content-type': 'application/json' } }); } /** fetch stub: first call 402, second call runs `paid(signal)`. */ @@ -143,7 +151,7 @@ async function runPaid({ paid, timeoutMs = 60, signer, parent = new AbortControl const token = await walletReservation.hold(0.25); let threw = null; try { - await postWithPayment('https://gateway.invalid/modal/create', {}, 'test', parent.signal, timeoutMs, token); + await postWithPayment('https://gateway.invalid/modal/create', {}, 'test', parent.signal, timeoutMs, token, 0.01); } catch (e) { threw = e; } walletReservation.release(token); // the caller's finally return { threw, snap: walletReservation.snapshot(), token }; @@ -202,7 +210,7 @@ test('probe (unpaid) request failing -> nothing dispatched, nothing ambiguous', walletReservation._resetForTests(fixed(1)); globalThis.fetch = async () => { const e = new Error('aborted'); e.name = 'AbortError'; throw e; }; const token = await walletReservation.hold(0.25); - await assert.rejects(() => postWithPayment('https://gateway.invalid/x', {}, 't', new AbortController().signal, 50, token)); + await assert.rejects(() => postWithPayment('https://gateway.invalid/x', {}, 't', new AbortController().signal, 50, token, 0.01)); walletReservation.release(token); assert.equal(walletReservation.snapshot().totalUsd, 0); }); @@ -341,7 +349,8 @@ test('an unreadable 402 is refused when a ceiling is set', async () => { walletReservation._resetForTests(fixed(1000)); let signed = 0; _setPaymentSignerForTests(async () => { signed++; return { 'PAYMENT-SIGNATURE': 'sig' }; }); - stubFetch(async () => new Response('{}', { status: 200 })); + let n = 0; + globalThis.fetch = async () => (++n === 1 ? res402Unreadable() : new Response('{}', { status: 200 })); const r = await postWithPayment('https://gateway.invalid/x', {}, 't', new AbortController().signal, 1000, null, 0.01); assert.equal(r.ok, false); assert.match(String(r.body.error), /no readable amount/); @@ -404,3 +413,202 @@ test('ModalCreate holds list price + fee allowance, so a balance at exactly the assert.match(out.output, /Insufficient/); assert.equal(q.sent.length, 0); }); + +// ─── GLM 5.3 review of #248: follow-ups ────────────────────────────────── + +const { + modalTerminateCapability, modalExecCapability, modalStatusCapability, modalCapabilities, + modalCreatePricing, modalCharge, sessionSandboxTracker, +} = await import('../dist/tools/modal.js'); +const { getLiveSpendUsd } = await import('../dist/stats/tracker.js'); + +test('no Modal tool text teaches usage billing: terminate refunds nothing', () => { + const term = modalTerminateCapability.spec.description; + assert.match(term, /does NOT refund/); + assert.match(term, /upfront/); + for (const cap of modalCapabilities) { + const text = JSON.stringify(cap.spec); + assert.doesNotMatch(text, /bills? wall-clock|until the sandbox terminates|keep billing/i, cap.spec.name); + assert.doesNotMatch(text, /auto-cleanup also calls/i, `${cap.spec.name}: no session-end cleanup is wired`); + } +}); + +test('gpu "" / blank / null is a CPU create with the quote guard and reservation on', async () => { + for (const gpu of ['', ' ', null]) { + walletReservation._resetForTests(fixed(1000)); + // A CPU 300 s create is $0.01; a $6 quote must be refused, which proves the + // guard ran with a real price (tier "" used to price as undefined = no guard). + const q = stubQuote('6000000'); + const out = await modalCreateCapability.execute({ gpu }, createCtx()); + assert.equal(out.isError, true, `gpu ${JSON.stringify(gpu)}`); + assert.match(out.output, /quote_exceeds_expected/); + assert.equal(q.signedCount(), 0); + assert.equal(q.sent[0].body.gpu, undefined, 'blank gpu is not sent'); + } + walletReservation._resetForTests(fixed(1000)); + const q = stubQuote('10000'); + let held = null; + const origFetch = globalThis.fetch; + globalThis.fetch = async (u, i) => { held ??= walletReservation.snapshot().totalUsd; return origFetch(u, i); }; + const out = await modalCreateCapability.execute({ gpu: '' }, createCtx()); + assert.equal(out.isError, undefined, out.output); + assert.equal(held, 0.011001, 'reservation holds the CPU ceiling'); + assert.match(out.output, /tier: CPU only/); + assert.equal(q.signedCount(), 1); +}); + +test('gpu "" in the confirm dialog renders a CPU price instead of throwing', async () => { + walletReservation._resetForTests(fixed(1000)); + stubQuote('10000'); + let prompt = ''; + const ctx = { ...createCtx(), onAskUser: async (q) => { prompt = q; return 'Cancel'; } }; + const prev = process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL; + delete process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL; + try { + const out = await modalCreateCapability.execute({ gpu: '' }, ctx); + assert.match(out.output, /cancelled/); + } finally { + if (prev !== undefined) process.env.FRANKLIN_MEDIA_AUTO_APPROVE_ALL = prev; + } + assert.match(prompt, /CPU only/); + assert.match(prompt, /Create cost:\s+\$0\.01 /); +}); + +test('a non-string or unknown gpu is rejected before any request', async () => { + for (const gpu of [0, false, 4, 'cpu', 'B200']) { + walletReservation._resetForTests(fixed(1000)); + const q = stubQuote('10000'); + const out = await modalCreateCapability.execute({ gpu }, createCtx()); + assert.equal(out.isError, true, `gpu ${JSON.stringify(gpu)}`); + assert.match(out.output, /invalid gpu/); + assert.equal(q.sent.length, 0); + } + // Case and whitespace still fold onto a real tier. + walletReservation._resetForTests(fixed(1000)); + const q = stubQuote('50000'); + const out = await modalCreateCapability.execute({ gpu: ' t4 ' }, createCtx()); + assert.equal(out.isError, undefined, out.output); + assert.equal(q.sent[0].body.gpu, 'T4'); +}); + +test('fail closed: no price means no signature and no NaN hold', async () => { + assert.throws(() => modalCreatePricing(''), /no Modal price/); + assert.throws(() => modalCreatePricing('B200'), /no Modal price/); + assert.throws(() => maxSignableAtomic(undefined), /no quote ceiling/); + assert.throws(() => maxSignableAtomic(NaN), /no quote ceiling/); + assert.throws(() => maxSignableAtomic(-1), /no quote ceiling/); + walletReservation._resetForTests(fixed(1000)); + await assert.rejects(() => walletReservation.hold(NaN), /non-finite/); + await assert.rejects(() => walletReservation.hold(undefined), /non-finite/); + assert.equal(walletReservation.snapshot().totalUsd, 0, 'a refused hold leaves nothing behind'); + for (const maxPrice of [undefined, NaN, Infinity, -1]) { + const q = stubQuote('1'); + const r = await postWithPayment('https://gateway.invalid/x', {}, 't', new AbortController().signal, 1000, null, maxPrice); + assert.equal(r.ok, false, `maxPriceUsd ${maxPrice}`); + assert.equal(r.status, 402); + assert.match(String(r.body.error), /quote_exceeds_expected: this client has no expected price/); + assert.equal(q.signedCount(), 0); + assert.equal(q.sent.length, 1, 'no paid request dispatched'); + } +}); + +test('ModalCreate reports the signed amount, not the sol list price (Base hourly)', async () => { + walletReservation._resetForTests(fixed(1000)); + stubQuote('667667'); // Base A100 600 s, probed 2026-11-13 + const before = getLiveSpendUsd(); + const out = await modalCreateCapability.execute({ gpu: 'A100', timeout: 600 }, createCtx()); + assert.equal(out.isError, undefined, out.output); + assert.match(out.output, /charged: \$0\.667667 \(hourly/); + assert.doesNotMatch(out.output, /\$1\.17/); + assert.ok(Math.abs(getLiveSpendUsd() - before - 0.667667) < 1e-9, 'recordUsage gets the settled amount'); +}); + +test('ModalCreate prefers the gateway cost header, and labels a list price as an estimate', async () => { + // x-blockrun-cost-usd wins over the signed quote. + walletReservation._resetForTests(fixed(1000)); + let n = 0; + globalThis.fetch = async () => (++n === 1 + ? res402Quote('11000') + : new Response(JSON.stringify({ sandbox_id: 'sb_h' }), { status: 200, headers: { 'x-blockrun-cost-usd': '0.011000' } })); + _setPaymentSignerForTests(async () => ({ 'PAYMENT-SIGNATURE': 'sig' })); + let out = await modalCreateCapability.execute({}, createCtx()); + assert.match(out.output, /charged: \$0\.011 \(flat/); + + // No 402 and no header (e.g. a key-mode 200): the list price, marked estimated. + walletReservation._resetForTests(fixed(1000)); + globalThis.fetch = async () => new Response(JSON.stringify({ sandbox_id: 'sb_k' }), { status: 200 }); + const before = getLiveSpendUsd(); + out = await modalCreateCapability.execute({ gpu: 'A100', timeout: 600 }, createCtx()); + assert.match(out.output, /charged: ~\$1\.17 estimated \(list price; the gateway did not report the settled amount\)/); + assert.ok(Math.abs(getLiveSpendUsd() - before - 7 / 6) < 1e-9); + + assert.deepEqual(modalCharge({ chargedUsd: 0, signedUsd: 0.5 }, 1), { usd: 0, estimated: false }, '0 from the header is a value'); + assert.deepEqual(modalCharge({ chargedUsd: null, signedUsd: 0.5 }, 1), { usd: 0.5, estimated: false }); + assert.deepEqual(modalCharge({ chargedUsd: null, signedUsd: null }, 1), { usd: 1, estimated: true }); +}); + +test('exec / status / terminate hold the ceiling the guard may sign, not the bare list price', async () => { + const cases = [ + [modalExecCapability, { sandbox_id: 'sb_x', command: 'true' }, { stdout: 'ok', exit_code: 0 }], + [modalStatusCapability, { sandbox_id: 'sb_x' }, { status: 'running' }], + [modalTerminateCapability, { sandbox_id: 'sb_x' }, { ok: true }], + ]; + for (const [cap, input, paidBody] of cases) { + walletReservation._resetForTests(fixed(1000)); + stubQuote('2000', paidBody); // Base: $0.001 + $0.001 fee + const heldAt = []; + const inner = globalThis.fetch; + globalThis.fetch = async (u, i) => { heldAt.push(walletReservation.snapshot().totalUsd); return inner(u, i); }; + const out = await cap.execute(input, createCtx()); + assert.ok(!out.isError, `${cap.spec.name}: ${out.output}`); + assert.equal(heldAt[0], 0.002001, `${cap.spec.name} holds list + fee + 1 unit`); + assert.equal(walletReservation.snapshot().totalUsd, 0, 'released after'); + } +}); + +test('billingLine says "flat floor" for a large create priced at the floor', async () => { + walletReservation._resetForTests(fixed(1000)); + stubQuote('50000'); + const out = await modalCreateCapability.execute({ gpu: 'T4', cpu: 8, memory: 32768, timeout: 10 }, createCtx()); + assert.equal(out.isError, undefined, out.output); + assert.match(out.output, /\(flat floor: the hourly price for this size and lifetime is below the flat rate/); + assert.doesNotMatch(out.output, /timeout <= 300 s, cpu <= 1/); + // A genuinely flat-eligible create keeps the eligibility wording. + walletReservation._resetForTests(fixed(1000)); + stubQuote('50000'); + const flat = await modalCreateCapability.execute({ gpu: 'T4' }, createCtx()); + assert.match(flat.output, /\(flat \(timeout <= 300 s, cpu <= 1, memory <= 1024 MB\)\)/); +}); + +test('a quote-guard refusal on ModalTerminate is an error and keeps the sandbox tracked', async () => { + sessionSandboxTracker.drainIds(); + sessionSandboxTracker.add({ id: 'sb_t', gpu: 'H100', createdAt: Date.now() }); + walletReservation._resetForTests(fixed(1000)); + const q = stubQuote('5000'); // above the $0.002001 terminate ceiling + const out = await modalTerminateCapability.execute({ sandbox_id: 'sb_t' }, createCtx()); + assert.equal(out.isError, true); + assert.match(out.output, /ModalTerminate failed \(402\): quote_exceeds_expected/); + assert.match(out.output, /still tracked/); + assert.equal(q.signedCount(), 0); + assert.deepEqual(sessionSandboxTracker.list().map((r) => r.id), ['sb_t'], 'not dropped'); + + // A 5xx is an error and keeps it tracked too. + globalThis.fetch = async () => new Response('{"error":"upstream"}', { status: 502 }); + const five = await modalTerminateCapability.execute({ sandbox_id: 'sb_t' }, createCtx()); + assert.equal(five.isError, true); + assert.deepEqual(sessionSandboxTracker.list().map((r) => r.id), ['sb_t']); + + // A benign 4xx (already gone) drops it without an error. + globalThis.fetch = async () => new Response('{"error":"not found"}', { status: 404 }); + const gone = await modalTerminateCapability.execute({ sandbox_id: 'sb_t' }, createCtx()); + assert.equal(gone.isError, false); + assert.equal(sessionSandboxTracker.list().length, 0); + + // Success drops it. + sessionSandboxTracker.add({ id: 'sb_u', gpu: 'cpu', createdAt: Date.now() }); + walletReservation._resetForTests(fixed(1000)); + stubQuote('1000', { ok: true }); + const ok = await modalTerminateCapability.execute({ sandbox_id: 'sb_u' }, createCtx()); + assert.ok(!ok.isError, ok.output); + assert.equal(sessionSandboxTracker.list().length, 0); +});