@tangle-network/agent-app 0.45.26 → 0.45.28
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/dist/assistant/index.d.ts +1 -0
- package/dist/assistant/index.js +5 -5
- package/dist/chat-routes/index.js +21 -21
- package/dist/chat-store/index.js +2 -2
- package/dist/{chunk-B2UEW62O.js → chunk-5ZTFZBS6.js} +4 -4
- package/dist/{chunk-AGCRCOQH.js → chunk-AWPK7ZDS.js} +1 -1
- package/dist/chunk-C3CAYGGQ.js +18 -0
- package/dist/chunk-C3CAYGGQ.js.map +1 -0
- package/dist/chunk-EMLGWEHV.js +33 -0
- package/dist/chunk-EMLGWEHV.js.map +1 -0
- package/dist/{chunk-XEA5EG6P.js → chunk-EPZYYWCT.js} +8 -30
- package/dist/chunk-EPZYYWCT.js.map +1 -0
- package/dist/{chunk-WD2B6HGY.js → chunk-K4RA5T3A.js} +11 -32
- package/dist/chunk-K4RA5T3A.js.map +1 -0
- package/dist/chunk-NEJ7OMQS.js +351 -0
- package/dist/chunk-NEJ7OMQS.js.map +1 -0
- package/dist/{chunk-7V2I3JGZ.js → chunk-OTLEYHOG.js} +50 -12
- package/dist/chunk-OTLEYHOG.js.map +1 -0
- package/dist/{chunk-RT5RKAFX.js → chunk-QGSVF6DZ.js} +8 -18
- package/dist/chunk-QGSVF6DZ.js.map +1 -0
- package/dist/{chunk-KOMP6NDW.js → chunk-WC43OQMR.js} +45 -34
- package/dist/chunk-WC43OQMR.js.map +1 -0
- package/dist/{chunk-N3G3FSM4.js → chunk-YXA3U4JZ.js} +9 -47
- package/dist/chunk-YXA3U4JZ.js.map +1 -0
- package/dist/design-canvas-react/index.js +4 -4
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/legibility/cli.js +14 -8
- package/dist/legibility/cli.js.map +1 -1
- package/dist/legibility/index.js +2 -1
- package/dist/peer-floors/cli.js +14 -8
- package/dist/peer-floors/cli.js.map +1 -1
- package/dist/preflight/cli.js +4 -2
- package/dist/preflight/cli.js.map +1 -1
- package/dist/{run-tEsZUhAf.d.ts → run-D80hoLKh.d.ts} +1 -1
- package/dist/sandbox/index.d.ts +53 -1
- package/dist/sandbox/index.js +1 -1
- package/dist/signoff/cli.d.ts +2 -2
- package/dist/signoff/cli.js +6 -18
- package/dist/signoff/cli.js.map +1 -1
- package/dist/signoff/index.d.ts +4 -420
- package/dist/signoff/index.js +3 -55
- package/dist/signoff/proof-cli.js +11 -6
- package/dist/signoff/proof-cli.js.map +1 -1
- package/dist/signoff/proof.d.ts +70 -271
- package/dist/signoff/proof.js +3 -73
- package/dist/signoff/proof.js.map +1 -1
- package/dist/spend/cli.d.ts +1 -0
- package/dist/spend/cli.js +119 -0
- package/dist/spend/cli.js.map +1 -0
- package/dist/spend/index.d.ts +640 -0
- package/dist/spend/index.js +196 -0
- package/dist/spend/index.js.map +1 -0
- package/dist/stream/index.js +14 -14
- package/dist/teams/index.js +9 -9
- package/dist/teams/invitations-api.js +7 -7
- package/dist/theme-contract/cli.js +6 -2
- package/dist/theme-contract/cli.js.map +1 -1
- package/dist/theme-contract/index.js +2 -1
- package/dist/{types-U7Nz-txa.d.ts → types-Bd6uW9vQ.d.ts} +1 -1
- package/dist/web-react/index.d.ts +28 -40
- package/dist/web-react/index.js +11 -11
- package/package.json +7 -1
- package/dist/chunk-7V2I3JGZ.js.map +0 -1
- package/dist/chunk-KOMP6NDW.js.map +0 -1
- package/dist/chunk-N3G3FSM4.js.map +0 -1
- package/dist/chunk-RT5RKAFX.js.map +0 -1
- package/dist/chunk-WD2B6HGY.js.map +0 -1
- package/dist/chunk-XEA5EG6P.js.map +0 -1
- /package/dist/{chunk-B2UEW62O.js.map → chunk-5ZTFZBS6.js.map} +0 -0
- /package/dist/{chunk-AGCRCOQH.js.map → chunk-AWPK7ZDS.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/spend/types.ts","../src/spend/ceiling.ts","../src/spend/reference.ts","../src/spend/reconcile.ts","../src/spend/report.ts"],"sourcesContent":["/**\n * The vocabulary of consumer-side spend verification.\n *\n * Kept in its own module with ZERO imports so a product can type its storage\n * rows and its reconciliation config without pulling in `node:fs` through the\n * CLI half.\n *\n * The model in one paragraph: the platform's ledger is authoritative about what\n * was CHARGED. A product knows something the ledger does not — what it ASKED\n * for. Recording that second view, and diffing it against the first, is what\n * turns a platform billing defect from silent money into an alert. Nothing here\n * lets a product self-certify a charge away; the output is a discrepancy a human\n * disputes.\n */\n\n// ── the product's own view of a box's life ────────────────────────────────────\n\n/**\n * One box, as the PRODUCT understands it. Folded, not an append-only log: a\n * product runs one row per sandbox, and every field below is derived by a\n * monotonic fold (see `foldSpendBoxRecord`) so two concurrent writers cannot\n * produce a wrong answer, only a stale one.\n *\n * Timestamps are epoch ms throughout, matching the platform's own\n * `sandbox_meta.last_started_at`.\n */\nexport interface SpendBoxRecord {\n /** The platform's sandbox id — the join key to every settlement row. */\n readonly sandboxId: string\n /** The product's own tenancy unit, which the platform does not model. */\n readonly workspaceId: string\n /** First moment the product knew this box existed. */\n readonly createdAt: number\n /**\n * The idle timeout the product ASKED the platform for, seconds. This is the\n * width of the grace window between the last thing the product saw and the\n * moment the platform should have stopped billing.\n */\n readonly idleTimeoutSeconds: number\n /**\n * The maximum lifetime the product asked for, seconds, when it asked for one.\n * This is the strongest bound a product holds: the platform destroys the box\n * at `createdAt + maxLifetimeSeconds` regardless of what the product observed,\n * so it caps the ceiling even when nothing else can (see `computeExpectedCeiling`).\n */\n readonly maxLifetimeSeconds: number | null\n /** Latest moment the product OBSERVED the box doing work. */\n readonly lastActivityAt: number\n /**\n * Detached runs dispatched but never observed to finish, by run id.\n *\n * Non-empty means the product genuinely cannot bound this box from its own\n * observations: it handed the platform work and disconnected. The ceiling\n * degrades accordingly rather than pretending to a tightness it did not earn.\n */\n readonly openDetachedRunIds: readonly string[]\n /** When the product knows the box stopped. Cleared by later activity. */\n readonly stoppedAt: number | null\n /** When the product knows the box was deleted. Set once — a deleted id never returns. */\n readonly deletedAt: number | null\n /** Opaque product-column values, written verbatim and never read here. */\n readonly extras?: Record<string, unknown>\n}\n\n/**\n * A fold step. Every field states its own merge rule, so a SQL implementation\n * can apply it in one statement and reach the same record an in-memory\n * read-modify-write reaches.\n */\nexport interface SpendBoxPatch {\n /** Advance `lastActivityAt` to the max of stored and this. Never moves backward. */\n readonly observedActivityAt?: number\n /** Add a run id to `openDetachedRunIds` (set semantics — re-adding is a no-op). */\n readonly openDetachedRunAdd?: string\n /** Remove a run id from `openDetachedRunIds`. Removing an absent id is a no-op. */\n readonly openDetachedRunRemove?: string\n /**\n * Latest-wins. Activity observed AFTER a recorded stop clears it: a box that\n * worked after we thought it stopped is running again, and a stale stop would\n * make the ceiling too tight.\n */\n readonly stoppedAt?: number\n /** Set-once. A later delete observation does not move the first one. */\n readonly deletedAt?: number\n}\n\n// ── what bounds a box's billable time ─────────────────────────────────────────\n\n/** Which fact bounds a box's billable time, weakest last. */\nexport type CeilingBasis =\n /** The product observed deletion. Billing cannot run past a box that is gone. */\n | 'deleted'\n /** The product observed a stop. Billing should have closed there. */\n | 'stopped'\n /** No stop seen, but the platform destroys the box at its max lifetime. */\n | 'max-lifetime'\n /** No stop seen; the platform's idle timer is what should have closed billing. */\n | 'idle-timeout'\n /**\n * An unfinished detached run and no max lifetime — the product cannot bound\n * this box at all, so the ceiling degrades to the reconciliation instant.\n * A finding on this basis is weak evidence and says so.\n */\n | 'open-detached-run'\n\n/** The upper bound on one box's billable duration, and what earned it. */\nexport interface ExpectedCeiling {\n readonly sandboxId: string\n readonly basis: CeilingBasis\n /** The latest instant this box could still have been billable, epoch ms. */\n readonly horizonAt: number\n /** `horizonAt - createdAt + toleranceMs`. The upper bound on billable ms. */\n readonly ceilingMs: number\n readonly toleranceMs: number\n /**\n * False when the basis is `open-detached-run` — the ceiling then rests on the\n * reconciliation instant rather than on anything the product observed, so an\n * overage means the platform billed outside the box's own lifetime, not merely\n * longer than expected.\n */\n readonly bounded: boolean\n}\n\n// ── what the platform actually emitted ────────────────────────────────────────\n\n/**\n * One settled ledger row, in the shape the platform's `credit_transactions`\n * table stores it. The product supplies these through its own fetch (the\n * platform's credit-history API, an export, a mirror) — this package never\n * reaches for them, because the ledger is the counterparty's record and reading\n * it is the product's authenticated business.\n *\n * The product's fetch MUST scope rows to boxes it owns. Products bill to a\n * shared company key, so an unscoped fetch returns every sibling product's\n * settlements and every one of them is a correct `unknown-box` finding.\n */\nexport interface SettlementRow {\n /** The ledger row id, for the dispute. */\n readonly id: string\n /**\n * `sandbox:<kind>:<sandboxId>:<intervalStartMs>` — the platform's idempotency\n * key, and the only place the billed interval's START is recorded.\n */\n readonly referenceId: string | null\n /**\n * Signed nanodollars, exactly as the ledger stores it: negative is a charge,\n * positive is a credit or refund.\n */\n readonly amountNanoUsd: number\n /** `compute` | `refund` | `inference` | … */\n readonly type: string\n /** `sandbox` | `router` | … */\n readonly product: string | null\n /** `sandbox:<sandboxId>` — the platform's aggregation unit. */\n readonly groupKey: string | null\n /** Settlement instant, epoch ms. The product normalizes the stored text. */\n readonly createdAt: number\n readonly description: string | null\n /** Provider at-cost basis, unsigned nanodollars. Null when unattributed. */\n readonly costBasisNanoUsd: number | null\n /**\n * The billed duration, when the product's ledger view exposes it directly.\n * Null is the common case: the platform does not store duration on the row.\n */\n readonly billedMs: number | null\n}\n\n/** The parts of a settlement reference id, once parsed. */\nexport interface SettlementReference {\n /** `stop` | `compute` | `egress` | `gpu-lease` | anything the platform adds. */\n readonly kind: string\n /** For compute kinds, the sandbox id. For `gpu-lease`, the lease id. */\n readonly resourceId: string\n /** The interval's start, epoch ms. Null for kinds that carry no interval. */\n readonly intervalStartMs: number | null\n}\n\n/** How a settled duration was arrived at — every duration finding carries one. */\nexport type BilledDurationBasis =\n /** The ledger row carried the duration. Exact. */\n | 'reported'\n /** `amount ÷ the product's stated hourly rate`. Exact when the rate is right. */\n | 'rate'\n /**\n * `settledAt - intervalStart`. An UPPER bound, not the billed duration: a\n * correct settlement posted late by the platform's durable settlement queue\n * reads longer here than it billed. Findings on this basis say so.\n */\n | 'reference-span'\n /** No basis available — duration rules are skipped for this row. */\n | 'unknown'\n\n// ── findings ──────────────────────────────────────────────────────────────────\n\n/** The checks this reconciler runs. Each is individually skippable, by name. */\nexport type SpendCheckId =\n /** A settlement against a box the product has no record of ever asking for. */\n | 'unknown-box'\n /** A settled duration longer than the product's own upper bound allows. */\n | 'over-ceiling'\n /** A spend window far above the trailing median — the burst shape of a defect. */\n | 'velocity'\n /** The balance the product observes has gone below its floor. */\n | 'negative-balance'\n\nexport const SPEND_CHECKS: readonly SpendCheckId[] = [\n 'unknown-box',\n 'over-ceiling',\n 'velocity',\n 'negative-balance',\n]\n\n/**\n * One discrepancy, with every number the rule compared.\n *\n * Nullable fields are per-check and deliberately present-but-null rather than\n * absent: a reader scanning a JSON dump can tell \"this rule does not measure\n * that\" from \"that measurement is missing\".\n */\nexport interface SpendFinding {\n readonly check: SpendCheckId\n /** What is wrong, in one sentence, with the numbers in it. */\n readonly message: string\n /** What to do about it. A finding without a remedy is a complaint. */\n readonly remedy: string\n readonly sandboxId: string | null\n readonly workspaceId: string | null\n /** The ledger rows that evidence this finding — the dispute's exhibit list. */\n readonly referenceIds: readonly string[]\n /** Nanodollars this finding puts in question, unsigned. */\n readonly settledNanoUsd: number\n /** `over-ceiling` — the duration actually settled, and how that was derived. */\n readonly settledMs: number | null\n readonly durationBasis: BilledDurationBasis | null\n /** `over-ceiling` — the bound it broke, and what earned that bound. */\n readonly ceilingMs: number | null\n readonly overageMs: number | null\n readonly ceilingBasis: CeilingBasis | null\n /** `velocity` — the window, its trailing median, and the ratio between them. */\n readonly windowNanoUsd: number | null\n readonly trailingMedianNanoUsd: number | null\n readonly velocityRatio: number | null\n readonly windowStartAt: number | null\n /** `negative-balance` — the observed balance and the floor it broke. */\n readonly balanceNanoUsd: number | null\n readonly balanceFloorNanoUsd: number | null\n}\n\n/** What one reconciliation pass concluded. */\nexport interface SpendReport {\n /** True when nothing fired. `ok === findings.length === 0`. */\n readonly ok: boolean\n readonly findings: readonly SpendFinding[]\n readonly checksRun: readonly SpendCheckId[]\n /** Rows the pass read, including the ones no rule looked at. */\n readonly rowsExamined: number\n /** Distinct boxes those rows settled against. */\n readonly boxesExamined: number\n /** Total charged across every examined row, unsigned nanodollars. */\n readonly settledNanoUsd: number\n /** Total credited back across every examined row, unsigned nanodollars. */\n readonly creditedNanoUsd: number\n /** The instant the pass treated as \"now\". */\n readonly asOf: number\n}\n","import type { CeilingBasis, ExpectedCeiling, SpendBoxRecord } from './types'\n\n/**\n * Slack allowed between the product's bound and what the platform settled,\n * before an overage is called a discrepancy. 15 minutes.\n *\n * Not a guess: it is the platform's OWN staleness threshold for compute\n * settlement. Its runbook clears an incident when\n * `/health computeSettlement.oldestAgeSeconds` is \"back under 900\" — so 900 s is\n * the age the platform itself treats as normal settlement lag, and anything\n * inside it is drift the platform has already declared acceptable. Below that a\n * product would alert on the platform's ordinary queue behaviour; far above it\n * the tolerance starts eating the signal, because the idle window it must stay\n * well under is 3600 s in every shipped product.\n *\n * It is a caller parameter because a product that asks for a shorter idle\n * timeout must shrink this with it.\n */\nexport const DEFAULT_CEILING_TOLERANCE_MS = 900_000\n\nexport interface ComputeExpectedCeilingOptions {\n /** The instant the reconciliation treats as \"now\", epoch ms. */\n readonly asOf: number\n /** Slack before an overage counts. Default {@link DEFAULT_CEILING_TOLERANCE_MS}. */\n readonly toleranceMs?: number\n}\n\n/**\n * The upper bound on how long one box could honestly have been billable.\n *\n * The whole design constraint is that this must stay an UPPER bound under\n * everything the product cannot see. Three such blind spots exist, and they\n * pull in different directions:\n *\n * - **Platform-side suspends.** The platform can park a box the product never\n * hears about. That only ever REDUCES real billable time, so an upper bound\n * is unaffected and nothing here widens for it.\n * - **Detached runs.** The product dispatches work and disconnects. The box\n * keeps working — and billing — after the last activity the product saw, so\n * `lastActivityAt` understates the truth. An unfinished detached run\n * therefore abandons the activity-based bound entirely rather than reporting\n * a bound it cannot support.\n * - **Reconnects.** A browser or worker re-attaches and work resumes. This\n * needs no special case: a reconnect is recorded as activity, the fold takes\n * the max, and the horizon moves out on its own.\n *\n * The bound that rescues the detached case is `maxLifetimeSeconds`. The platform\n * destroys the box at `createdAt + maxLifetimeSeconds` no matter what anyone\n * observed, so a product that asks for one holds a hard bound that survives\n * every blind spot above. Both shipped products ask for 86 400 s, which is why\n * the incident — 124 to 268 hours settled against boxes with a 24-hour\n * lifetime — is detectable with no lifecycle bookkeeping at all.\n */\nexport function computeExpectedCeiling(\n record: SpendBoxRecord,\n options: ComputeExpectedCeilingOptions,\n): ExpectedCeiling {\n const toleranceMs = options.toleranceMs ?? DEFAULT_CEILING_TOLERANCE_MS\n const { asOf } = options\n\n let basis: CeilingBasis\n let horizonAt: number\n\n if (record.deletedAt !== null) {\n basis = 'deleted'\n horizonAt = record.deletedAt\n } else if (record.stoppedAt !== null) {\n basis = 'stopped'\n horizonAt = record.stoppedAt\n } else if (record.openDetachedRunIds.length > 0) {\n // Nothing the product observed bounds this box. Fall back to the\n // reconciliation instant, and say so through `bounded: false`.\n basis = 'open-detached-run'\n horizonAt = asOf\n } else {\n basis = 'idle-timeout'\n horizonAt = record.lastActivityAt + record.idleTimeoutSeconds * 1000\n }\n\n // The hard platform bound wins whenever it is tighter — including over an\n // unfinished detached run, which is what turns an unbounded box back into a\n // bounded one.\n if (record.maxLifetimeSeconds !== null) {\n const lifetimeHorizon = record.createdAt + record.maxLifetimeSeconds * 1000\n if (lifetimeHorizon < horizonAt) {\n basis = 'max-lifetime'\n horizonAt = lifetimeHorizon\n }\n }\n\n // Time that has not elapsed cannot have been billed, so an idle window\n // reaching into the future does not widen the bound. This only ever tightens\n // the ceiling, so it cannot mask a charge.\n if (horizonAt > asOf) horizonAt = asOf\n // A horizon before creation would produce a negative ceiling; a box is at\n // minimum billable for the instant it existed.\n if (horizonAt < record.createdAt) horizonAt = record.createdAt\n\n return {\n sandboxId: record.sandboxId,\n basis,\n horizonAt,\n ceilingMs: horizonAt - record.createdAt + toleranceMs,\n toleranceMs,\n bounded: basis !== 'open-detached-run',\n }\n}\n","import type { SettlementReference, SettlementRow } from './types'\n\n/**\n * Parse the platform's settlement idempotency key.\n *\n * The platform mints it as `sandbox:<kind>:<resourceId>:<intervalStart>`\n * (`d1-usage-service.ts`), where `intervalStart` is the interval cursor in epoch\n * ms — the SAME `last_started_at` the settlement subtracts from to get its\n * billed duration. That makes this string the only place a consumer can read the\n * billed interval's start, because the ledger row itself stores no duration.\n *\n * Kinds seen in production: `stop` (an interval closing), `compute` (a heartbeat\n * claim), `egress`, `gpu-lease`. `stop` deliberately covers both a settle and a\n * late stop racing over the same claim, so the two derive one reference id and\n * the ledger's uniqueness constraint makes the overlap safe.\n *\n * Returns null for anything that is not a sandbox reference — a router\n * inference row, a grant, a refund — rather than guessing.\n */\nexport function parseSettlementReference(referenceId: string | null | undefined): SettlementReference | null {\n if (!referenceId) return null\n const parts = referenceId.split(':')\n if (parts.length < 3 || parts[0] !== 'sandbox') return null\n const kind = parts[1]\n if (!kind) return null\n\n // The trailing segment is the interval cursor ONLY when it reads as an epoch\n // instant. `sandbox:gpu-lease:<leaseId>` has no cursor, and a resource id that\n // happened to contain a colon must not have its tail eaten as one.\n const tail = parts[parts.length - 1] as string\n const tailMs = /^\\d+$/.test(tail) ? Number(tail) : Number.NaN\n const hasCursor = parts.length >= 4 && Number.isSafeInteger(tailMs) && tailMs > 0\n\n const resourceId = hasCursor ? parts.slice(2, -1).join(':') : parts.slice(2).join(':')\n if (!resourceId) return null\n\n return { kind, resourceId, intervalStartMs: hasCursor ? tailMs : null }\n}\n\n/**\n * Read the sandbox id out of the platform's aggregation key, `sandbox:<id>`.\n *\n * Distinct from the reference id: `groupKey` is the unit a billing statement\n * groups by and is deliberately NOT unique per row, while `referenceId` is\n * unique per interval. A null group key means \"do not aggregate\" (grants,\n * top-ups, refunds, transfers) and is not an error.\n */\nexport function parseSandboxGroupKey(groupKey: string | null | undefined): string | null {\n if (!groupKey) return null\n const parts = groupKey.split(':')\n if (parts.length < 2 || parts[0] !== 'sandbox') return null\n const id = parts.slice(1).join(':')\n return id || null\n}\n\n/**\n * The sandbox a settlement row is attributable to.\n *\n * The reference id wins over the group key because it is the field the platform\n * dedups on, so it is the one guaranteed present and correct on a compute\n * settlement; the group key is the fallback for rows written before a producer\n * stamped a reference, and for kinds whose reference names something else (a GPU\n * lease id, not a box).\n */\nexport function settlementSandboxId(row: SettlementRow): string | null {\n const reference = parseSettlementReference(row.referenceId)\n if (reference && reference.intervalStartMs !== null) return reference.resourceId\n return parseSandboxGroupKey(row.groupKey) ?? (reference ? reference.resourceId : null)\n}\n\n/** True when a row is a charge (the ledger stores charges as negative amounts). */\nexport function isCharge(row: SettlementRow): boolean {\n return row.amountNanoUsd < 0\n}\n\n/** A charge's magnitude in unsigned nanodollars; 0 for credits. */\nexport function chargeNanoUsd(row: SettlementRow): number {\n return row.amountNanoUsd < 0 ? -row.amountNanoUsd : 0\n}\n","import { DEFAULT_CEILING_TOLERANCE_MS, computeExpectedCeiling } from './ceiling'\nimport { chargeNanoUsd, parseSettlementReference, settlementSandboxId } from './reference'\nimport type { SpendLedgerStorePort } from './store'\nimport {\n SPEND_CHECKS,\n type BilledDurationBasis,\n type CeilingBasis,\n type SettlementRow,\n type SpendBoxRecord,\n type SpendCheckId,\n type SpendFinding,\n type SpendReport,\n} from './types'\n\n/** How many nanodollars in one US dollar. The ledger's unit. */\nconst NANO_PER_USD = 1_000_000_000\nconst MS_PER_HOUR = 3_600_000\n\nexport interface VelocityOptions {\n /** Bucket width for a spend window, ms. Default 24 h. */\n readonly windowMs?: number\n /** Fire when a window exceeds this multiple of the trailing median. Default 5. */\n readonly multiple?: number\n /**\n * Windows of history required before a median means anything. Default 3.\n * Below this the rule stays silent, so a product's genuine first days of\n * usage are not reported as an anomaly.\n */\n readonly minTrailingWindows?: number\n /**\n * A window under this never fires, whatever the ratio. Default $1.00.\n *\n * Without a floor the rule is useless: a trailing median of a tenth of a cent\n * makes every ordinary day a 5x outlier. $1.00 is set from the incident's own\n * distribution — the smallest of the eight affected wallets took $1.98, and\n * the two rows in the same window that were GENUINE were sub-cent. So the\n * floor sits above the noise and below every real finding.\n */\n readonly minAbsoluteNanoUsd?: number\n}\n\nconst DEFAULT_VELOCITY: Required<VelocityOptions> = {\n windowMs: 86_400_000,\n multiple: 5,\n minTrailingWindows: 3,\n minAbsoluteNanoUsd: NANO_PER_USD,\n}\n\n/** The balance the product observes, and the floor it must not cross. */\nexport interface ObservedBalance {\n /** Signed nanodollars, as the platform reports it. */\n readonly nanoUsd: number\n /** Below this is a finding. Default 0. */\n readonly floorNanoUsd?: number\n}\n\n/**\n * A box's price, nanodollars per hour, used to derive an EXACT billed duration\n * from a charge. Return null when the product does not know the box's rate; the\n * reconciler then falls back to the reference span.\n */\nexport type BoxRateResolver = (record: SpendBoxRecord | null, sandboxId: string) => number | null | undefined\n\nexport interface ReconcileSpendOptions {\n /**\n * Settled ledger rows, supplied by the product's own authenticated fetch.\n *\n * MUST be scoped to boxes this product owns. Products bill to a shared company\n * key, so an unscoped fetch returns every sibling product's settlements and\n * every one is a correct — and useless — `unknown-box` finding.\n */\n readonly rows: readonly SettlementRow[]\n /** The product's expectation ledger. */\n readonly store: SpendLedgerStorePort\n /** Treated as \"now\". Default `Date.now()`. */\n readonly asOf?: number\n /** Ceiling slack. Default {@link DEFAULT_CEILING_TOLERANCE_MS}. */\n readonly toleranceMs?: number\n /** Box price, for the exact duration basis. A number applies to every box. */\n readonly nanoUsdPerHour?: number | BoxRateResolver\n /** Velocity tuning, or `false` to skip the rule. */\n readonly velocity?: VelocityOptions | false\n /** The workspace balance, when the product can see one. Omitted skips the rule. */\n readonly balance?: ObservedBalance\n /** Stamped onto findings so an alert names the tenant. */\n readonly workspaceId?: string\n /** Checks to leave out of this pass. */\n readonly skip?: readonly SpendCheckId[]\n}\n\nfunction usd(nano: number): string {\n return `$${(nano / NANO_PER_USD).toFixed(2)}`\n}\n\nfunction hours(ms: number): string {\n return `${(ms / MS_PER_HOUR).toFixed(1)}h`\n}\n\n/** Trust order, least trustworthy first — a mixed aggregate reports the weakest. */\nconst BASIS_TRUST: readonly BilledDurationBasis[] = ['unknown', 'reference-span', 'rate', 'reported']\n\nfunction weakestBasis(a: BilledDurationBasis, b: BilledDurationBasis): BilledDurationBasis {\n return BASIS_TRUST.indexOf(a) <= BASIS_TRUST.indexOf(b) ? a : b\n}\n\n/**\n * How long one settlement billed for, and how confidently we know it.\n *\n * The ledger row does not store a duration — this is the whole reason the check\n * is subtle. Three ways to recover it, best first:\n *\n * 1. `reported` — the product's ledger view exposed it. Exact.\n * 2. `rate` — `charge / pricePerHour`. Exact, because the platform computes the\n * charge as `(durationMs / 3_600_000) * costPerHour` and nothing else enters\n * it. Requires the product to know its box's price.\n * 3. `reference-span` — `settledAt - intervalStart`, both read off the row. An\n * UPPER bound, not the duration: a correct settlement delayed by the\n * platform's durable settlement queue reads longer here than it billed. It is\n * exact for the failure this module exists to catch, because billing \"up to\n * now\" makes the settlement instant and the interval end the same moment.\n */\nfunction resolveBilledMs(\n row: SettlementRow,\n ratePerHourNano: number | null,\n): { ms: number; basis: BilledDurationBasis } {\n if (row.billedMs !== null) return { ms: row.billedMs, basis: 'reported' }\n\n const charge = chargeNanoUsd(row)\n if (ratePerHourNano !== null && ratePerHourNano > 0 && charge > 0) {\n return { ms: (charge / ratePerHourNano) * MS_PER_HOUR, basis: 'rate' }\n }\n\n const reference = parseSettlementReference(row.referenceId)\n if (reference?.intervalStartMs != null && row.createdAt > reference.intervalStartMs) {\n return { ms: row.createdAt - reference.intervalStartMs, basis: 'reference-span' }\n }\n\n return { ms: 0, basis: 'unknown' }\n}\n\nfunction median(values: readonly number[]): number {\n if (values.length === 0) return 0\n const sorted = [...values].sort((a, b) => a - b)\n const mid = Math.floor(sorted.length / 2)\n if (sorted.length % 2 === 1) return sorted[mid] as number\n return (((sorted[mid - 1] as number) + (sorted[mid] as number)) / 2)\n}\n\nfunction emptyFinding(check: SpendCheckId): Omit<SpendFinding, 'message' | 'remedy'> {\n return {\n check,\n sandboxId: null,\n workspaceId: null,\n referenceIds: [],\n settledNanoUsd: 0,\n settledMs: null,\n durationBasis: null,\n ceilingMs: null,\n overageMs: null,\n ceilingBasis: null,\n windowNanoUsd: null,\n trailingMedianNanoUsd: null,\n velocityRatio: null,\n windowStartAt: null,\n balanceNanoUsd: null,\n balanceFloorNanoUsd: null,\n }\n}\n\n/**\n * Diff what the platform charged against what the product believes it asked for.\n *\n * Never disputes anything and never writes: the output is a report a human acts\n * on. The platform's ledger stays authoritative — this only ever produces the\n * evidence for a conversation with it.\n */\nexport async function reconcileSpend(options: ReconcileSpendOptions): Promise<SpendReport> {\n const asOf = options.asOf ?? Date.now()\n const toleranceMs = options.toleranceMs ?? DEFAULT_CEILING_TOLERANCE_MS\n const workspaceId = options.workspaceId ?? null\n const skip = new Set(options.skip ?? [])\n const checksRun = SPEND_CHECKS.filter((check) => !skip.has(check))\n const runs = (check: SpendCheckId): boolean => !skip.has(check)\n\n const findings: SpendFinding[] = []\n let settledNanoUsd = 0\n let creditedNanoUsd = 0\n\n // ── group charges by the box they are attributable to ──────────────────────\n const byBox = new Map<string, SettlementRow[]>()\n for (const row of options.rows) {\n if (row.amountNanoUsd < 0) settledNanoUsd += -row.amountNanoUsd\n else creditedNanoUsd += row.amountNanoUsd\n if (row.amountNanoUsd >= 0) continue\n const sandboxId = settlementSandboxId(row)\n if (!sandboxId) continue\n const bucket = byBox.get(sandboxId)\n if (bucket) bucket.push(row)\n else byBox.set(sandboxId, [row])\n }\n\n const rateOf = (record: SpendBoxRecord | null, sandboxId: string): number | null => {\n const rate = options.nanoUsdPerHour\n if (rate === undefined) return null\n if (typeof rate === 'number') return rate\n return rate(record, sandboxId) ?? null\n }\n\n for (const [sandboxId, rows] of byBox) {\n const record = await options.store.load(sandboxId)\n const referenceIds = rows.map((row) => row.referenceId ?? row.id)\n const charged = rows.reduce((sum, row) => sum + chargeNanoUsd(row), 0)\n\n // ── unknown-box ──────────────────────────────────────────────────────────\n if (!record) {\n if (runs('unknown-box')) {\n findings.push({\n ...emptyFinding('unknown-box'),\n sandboxId,\n workspaceId,\n referenceIds,\n settledNanoUsd: charged,\n message:\n `${usd(charged)} settled across ${rows.length} row(s) against sandbox ${sandboxId}, ` +\n 'which this product has no record of ever asking for.',\n remedy:\n 'Either the fetch is not scoped to this product\\'s own boxes (fix the scope — a shared ' +\n 'billing key returns every sibling product\\'s settlements), or a box was provisioned ' +\n 'outside the recorded seam, or the platform billed a box that is not ours. Identify ' +\n `which by looking up ${sandboxId} on the platform before disputing.`,\n })\n }\n continue\n }\n\n // ── over-ceiling ─────────────────────────────────────────────────────────\n if (!runs('over-ceiling')) continue\n\n const ceiling = computeExpectedCeiling(record, { asOf, toleranceMs })\n const ratePerHourNano = rateOf(record, sandboxId)\n\n let settledMs = 0\n let basis: BilledDurationBasis = 'reported'\n let anyMeasured = false\n for (const row of rows) {\n const resolved = resolveBilledMs(row, ratePerHourNano)\n if (resolved.basis === 'unknown') {\n basis = weakestBasis(basis, 'unknown')\n continue\n }\n anyMeasured = true\n settledMs += resolved.ms\n basis = weakestBasis(basis, resolved.basis)\n }\n if (!anyMeasured) continue\n if (settledMs <= ceiling.ceilingMs) continue\n\n const overageMs = settledMs - ceiling.ceilingMs\n const confidence = ceiling.bounded\n ? ''\n : ' The product could not bound this box from its own observations (an unfinished detached ' +\n 'run, and no max lifetime), so the ceiling rests on the reconciliation instant: this ' +\n 'settlement bills time outside the box\\'s own life, not merely more than expected.'\n const spanCaveat =\n basis === 'reference-span'\n ? ' Duration is derived from the settlement instant minus the interval start, which ' +\n 'overstates a settlement the platform merely posted late — confirm before disputing.'\n : ''\n\n findings.push({\n ...emptyFinding('over-ceiling'),\n sandboxId,\n workspaceId: record.workspaceId || workspaceId,\n referenceIds,\n settledNanoUsd: charged,\n settledMs,\n durationBasis: basis,\n ceilingMs: ceiling.ceilingMs,\n overageMs,\n ceilingBasis: ceiling.basis,\n message:\n `Sandbox ${sandboxId} settled ${hours(settledMs)} (${usd(charged)}) across ${rows.length} ` +\n `row(s), against an expected ceiling of ${hours(ceiling.ceilingMs)} — over by ` +\n `${hours(overageMs)}. Ceiling basis: ${ceiling.basis}; duration basis: ${basis}.` +\n confidence +\n spanCaveat,\n remedy:\n `Dispute ${referenceIds.join(', ')} against the platform ledger with both numbers. ` +\n (ceiling.basis === 'stopped' || ceiling.basis === 'deleted'\n ? 'The product recorded this box as no longer running before the billed time ended, so ' +\n 'either the stop did not take or the interval was settled at the wrong boundary.'\n : 'Freeze the open interval before anything deletes this box — deleting a box with an ' +\n 'open compute interval settles the whole gap at once.'),\n })\n }\n\n // ── velocity ───────────────────────────────────────────────────────────────\n if (runs('velocity') && options.velocity !== false) {\n const cfg = { ...DEFAULT_VELOCITY, ...(options.velocity ?? {}) }\n const buckets = new Map<number, { nano: number; references: string[] }>()\n for (const row of options.rows) {\n const charge = chargeNanoUsd(row)\n if (charge === 0) continue\n const bucketStart = Math.floor(row.createdAt / cfg.windowMs) * cfg.windowMs\n const bucket = buckets.get(bucketStart)\n if (bucket) {\n bucket.nano += charge\n bucket.references.push(row.referenceId ?? row.id)\n } else {\n buckets.set(bucketStart, { nano: charge, references: [row.referenceId ?? row.id] })\n }\n }\n\n const ordered = [...buckets.entries()].sort((a, b) => a[0] - b[0])\n for (let i = 0; i < ordered.length; i++) {\n const entry = ordered[i]\n if (!entry) continue\n const [windowStartAt, bucket] = entry\n if (i < cfg.minTrailingWindows) continue\n const trailing = ordered.slice(0, i).map(([, prior]) => prior.nano)\n const trailingMedian = median(trailing)\n const threshold = Math.max(trailingMedian * cfg.multiple, cfg.minAbsoluteNanoUsd)\n if (bucket.nano <= threshold) continue\n const ratio = trailingMedian > 0 ? bucket.nano / trailingMedian : Number.POSITIVE_INFINITY\n\n findings.push({\n ...emptyFinding('velocity'),\n workspaceId,\n referenceIds: bucket.references,\n settledNanoUsd: bucket.nano,\n windowNanoUsd: bucket.nano,\n trailingMedianNanoUsd: trailingMedian,\n velocityRatio: ratio,\n windowStartAt,\n message:\n `${usd(bucket.nano)} settled in the window starting ${new Date(windowStartAt).toISOString()} ` +\n `across ${bucket.references.length} row(s), against a trailing median of ` +\n `${usd(trailingMedian)} over ${trailing.length} prior window(s) — ` +\n `${Number.isFinite(ratio) ? `${ratio.toFixed(1)}x` : 'no prior spend to compare against'}, ` +\n `over the ${cfg.multiple}x threshold.`,\n remedy:\n 'A burst of this shape is what a settlement defect looks like from the consumer side: ' +\n 'long-dormant intervals cashed out at once. Check whether these rows carry interval ' +\n 'starts far older than the settlement instant before treating it as real usage.',\n })\n }\n }\n\n // ── negative-balance ───────────────────────────────────────────────────────\n if (runs('negative-balance') && options.balance) {\n const floor = options.balance.floorNanoUsd ?? 0\n if (options.balance.nanoUsd < floor) {\n findings.push({\n ...emptyFinding('negative-balance'),\n workspaceId,\n settledNanoUsd: Math.max(0, floor - options.balance.nanoUsd),\n balanceNanoUsd: options.balance.nanoUsd,\n balanceFloorNanoUsd: floor,\n message:\n `Observed balance ${usd(options.balance.nanoUsd)} is below the floor ${usd(floor)}.`,\n remedy:\n 'Stop provisioning new compute for this owner until the balance is explained. A negative ' +\n 'balance that nobody is watching is how a billing defect becomes settled money.',\n })\n }\n }\n\n return {\n ok: findings.length === 0,\n findings,\n checksRun,\n rowsExamined: options.rows.length,\n boxesExamined: byBox.size,\n settledNanoUsd,\n creditedNanoUsd,\n asOf,\n }\n}\n","import type { SpendFinding, SpendReport } from './types'\n\nconst NANO_PER_USD = 1_000_000_000\n\nfunction usd(nano: number | null): string {\n return nano === null ? '—' : `$${(nano / NANO_PER_USD).toFixed(2)}`\n}\n\n/**\n * Render a reconciliation for a human deciding whether to open a dispute.\n *\n * Every finding prints its numbers, not a summary of them: the reader's next\n * action is a conversation with the platform about specific reference ids, and a\n * report that made them re-derive the durations would just be re-read alongside\n * the raw rows anyway.\n */\nexport function formatSpendReport(report: SpendReport): string {\n const lines: string[] = []\n lines.push(\n `spend reconciliation — ${report.rowsExamined} row(s), ${report.boxesExamined} box(es), ` +\n `${usd(report.settledNanoUsd)} charged, ${usd(report.creditedNanoUsd)} credited, ` +\n `as of ${new Date(report.asOf).toISOString()}`,\n )\n lines.push(`checks: ${report.checksRun.join(', ') || '(none)'}`)\n\n if (report.ok) {\n lines.push('')\n lines.push('OK — no discrepancy between the product\\'s expectations and the settled ledger.')\n return lines.join('\\n')\n }\n\n lines.push('')\n lines.push(`${report.findings.length} finding(s):`)\n for (const finding of report.findings) {\n lines.push('')\n lines.push(` [${finding.check}] ${finding.message}`)\n for (const [label, value] of measuredFields(finding)) lines.push(` ${label}: ${value}`)\n if (finding.referenceIds.length > 0) {\n lines.push(` rows: ${finding.referenceIds.join(', ')}`)\n }\n lines.push(` → ${finding.remedy}`)\n }\n return lines.join('\\n')\n}\n\n/** Every measured field a finding carries, including the ones it left null. */\nfunction measuredFields(finding: SpendFinding): Array<[string, string]> {\n const ms = (value: number | null): string =>\n value === null ? '—' : `${(value / 3_600_000).toFixed(2)}h`\n return [\n ['sandbox', finding.sandboxId ?? '—'],\n ['workspace', finding.workspaceId ?? '—'],\n ['amount', usd(finding.settledNanoUsd)],\n ['settled', ms(finding.settledMs)],\n ['ceiling', ms(finding.ceilingMs)],\n ['overage', ms(finding.overageMs)],\n ['ceiling basis', finding.ceilingBasis ?? '—'],\n ['duration basis', finding.durationBasis ?? '—'],\n ['window', finding.windowStartAt === null ? '—' : new Date(finding.windowStartAt).toISOString()],\n ['window spend', usd(finding.windowNanoUsd)],\n ['trailing median', usd(finding.trailingMedianNanoUsd)],\n ['ratio', finding.velocityRatio === null ? '—' : `${finding.velocityRatio.toFixed(1)}x`],\n ['balance', usd(finding.balanceNanoUsd)],\n ['balance floor', usd(finding.balanceFloorNanoUsd)],\n ]\n}\n\n/** The report as a plain JSON value, for an alerting pipeline. */\nexport function spendReportToJson(report: SpendReport): string {\n return JSON.stringify(report, null, 2)\n}\n"],"mappings":";AA6MO,IAAM,eAAwC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SAAS,CAAC;AAAA,IACjC,CAAC,WAAW,GAAG,QAAQ,SAAS,CAAC;AAAA,IACjC,CAAC,iBAAiB,QAAQ,gBAAgB,QAAG;AAAA,IAC7C,CAAC,kBAAkB,QAAQ,iBAAiB,QAAG;AAAA,IAC/C,CAAC,UAAU,QAAQ,kBAAkB,OAAO,WAAM,IAAI,KAAK,QAAQ,aAAa,EAAE,YAAY,CAAC;AAAA,IAC/F,CAAC,gBAAgBA,KAAI,QAAQ,aAAa,CAAC;AAAA,IAC3C,CAAC,mBAAmBA,KAAI,QAAQ,qBAAqB,CAAC;AAAA,IACtD,CAAC,SAAS,QAAQ,kBAAkB,OAAO,WAAM,GAAG,QAAQ,cAAc,QAAQ,CAAC,CAAC,GAAG;AAAA,IACvF,CAAC,WAAWA,KAAI,QAAQ,cAAc,CAAC;AAAA,IACvC,CAAC,iBAAiBA,KAAI,QAAQ,mBAAmB,CAAC;AAAA,EACpD;AACF;AAGO,SAAS,kBAAkB,QAA6B;AAC7D,SAAO,KAAK,UAAU,QAAQ,MAAM,CAAC;AACvC;","names":["NANO_PER_USD","usd"]}
|
|
@@ -971,6 +971,13 @@ function buildAppToolMcpServers(options) {
|
|
|
971
971
|
}
|
|
972
972
|
return entries;
|
|
973
973
|
}
|
|
974
|
+
function emitSandboxActivity(spend, box) {
|
|
975
|
+
if (!spend?.onActivity) return;
|
|
976
|
+
try {
|
|
977
|
+
spend.onActivity({ sandboxId: box.id, at: Date.now() });
|
|
978
|
+
} catch {
|
|
979
|
+
}
|
|
980
|
+
}
|
|
974
981
|
function shellSingleQuote(value) {
|
|
975
982
|
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
976
983
|
}
|
|
@@ -1704,6 +1711,31 @@ async function assertExistingBoxEgress(box, desired, migrate, stage, name) {
|
|
|
1704
1711
|
);
|
|
1705
1712
|
}
|
|
1706
1713
|
async function ensureWorkspaceSandbox(shell, options) {
|
|
1714
|
+
await options.spend?.beforeProvision?.({
|
|
1715
|
+
workspaceId: options.workspaceId,
|
|
1716
|
+
...options.userId ? { userId: options.userId } : {}
|
|
1717
|
+
});
|
|
1718
|
+
const box = await bringUpWorkspaceSandbox(shell, options);
|
|
1719
|
+
await observeProvisionedBox(shell, options, box);
|
|
1720
|
+
return box;
|
|
1721
|
+
}
|
|
1722
|
+
async function observeProvisionedBox(shell, options, box) {
|
|
1723
|
+
if (!options.spend?.onProvisioned) return;
|
|
1724
|
+
const resources = shell.resources ?? DEFAULT_SANDBOX_RESOURCES;
|
|
1725
|
+
try {
|
|
1726
|
+
await options.spend.onProvisioned({
|
|
1727
|
+
workspaceId: options.workspaceId,
|
|
1728
|
+
...options.userId ? { userId: options.userId } : {},
|
|
1729
|
+
sandboxId: box.id,
|
|
1730
|
+
boxKey: box.name,
|
|
1731
|
+
idleTimeoutSeconds: resources.idleTimeoutSeconds,
|
|
1732
|
+
maxLifetimeSeconds: resources.maxLifetimeSeconds,
|
|
1733
|
+
at: Date.now()
|
|
1734
|
+
});
|
|
1735
|
+
} catch {
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
async function bringUpWorkspaceSandbox(shell, options) {
|
|
1707
1739
|
try {
|
|
1708
1740
|
return await provisionWorkspaceSandbox(shell, options);
|
|
1709
1741
|
} catch (err) {
|
|
@@ -2003,20 +2035,25 @@ async function* streamSandboxPrompt(shell, box, message, options) {
|
|
|
2003
2035
|
...options?.interactions ? { interactions: options.interactions } : {}
|
|
2004
2036
|
}
|
|
2005
2037
|
});
|
|
2038
|
+
emitSandboxActivity(options?.spend, box);
|
|
2006
2039
|
let severedFinishReason = null;
|
|
2007
|
-
|
|
2008
|
-
const
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2040
|
+
try {
|
|
2041
|
+
for await (const event of stream) {
|
|
2042
|
+
const step = classifySeveredStream(event);
|
|
2043
|
+
if (step) severedFinishReason = step.kind === "step-finish" && step.severed ? step.reason : null;
|
|
2044
|
+
if (severedFinishReason && isTerminalPromptEvent(event)) {
|
|
2045
|
+
throw new Error(`sandbox model stream severed mid-turn (reason="${severedFinishReason}")`);
|
|
2046
|
+
}
|
|
2047
|
+
if (options?.disallowQuestions) {
|
|
2048
|
+
const q = detectInteractiveQuestion(event);
|
|
2049
|
+
if (q) {
|
|
2050
|
+
throw new Error(`sandbox agent asked an interactive question during an autonomous run: ${q}`);
|
|
2051
|
+
}
|
|
2017
2052
|
}
|
|
2053
|
+
yield event;
|
|
2018
2054
|
}
|
|
2019
|
-
|
|
2055
|
+
} finally {
|
|
2056
|
+
emitSandboxActivity(options?.spend, box);
|
|
2020
2057
|
}
|
|
2021
2058
|
if (severedFinishReason) {
|
|
2022
2059
|
throw new Error(`sandbox model stream severed mid-turn (reason="${severedFinishReason}")`);
|
|
@@ -2177,6 +2214,7 @@ async function driveSandboxTurn(shell, box, message, options) {
|
|
|
2177
2214
|
// no consumer to answer a question. Interactive Q&A is streaming-path only.
|
|
2178
2215
|
backend: { type: harness, profile, ...model ? { model } : {} }
|
|
2179
2216
|
});
|
|
2217
|
+
emitSandboxActivity(options.spend, box);
|
|
2180
2218
|
return ok(drive);
|
|
2181
2219
|
} catch (err) {
|
|
2182
2220
|
return fail(err);
|
|
@@ -2316,4 +2354,4 @@ export {
|
|
|
2316
2354
|
isTerminalPromptEvent,
|
|
2317
2355
|
detectInteractiveQuestion
|
|
2318
2356
|
};
|
|
2319
|
-
//# sourceMappingURL=chunk-
|
|
2357
|
+
//# sourceMappingURL=chunk-OTLEYHOG.js.map
|