@tangle-network/agent-app 0.60.250 → 0.60.252
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/DesignCanvas-L6J72JQ2.js +15 -0
- package/dist/DesignCanvasEditor-QFQD63MR.js +18 -0
- package/dist/agent-enrollment/drizzle.js +3 -3
- package/dist/agent-enrollment/index.js +3 -3
- package/dist/app-auth/drizzle.d.ts +475 -0
- package/dist/app-auth/drizzle.js +86 -0
- package/dist/app-auth/drizzle.js.map +1 -0
- package/dist/app-auth/index.js +5 -3
- package/dist/app-auth/index.js.map +1 -1
- package/dist/app-oauth/drizzle.d.ts +2080 -0
- package/dist/app-oauth/drizzle.js +161 -0
- package/dist/app-oauth/drizzle.js.map +1 -0
- package/dist/app-oauth/index.d.ts +4 -0
- package/dist/app-oauth/index.js +8 -222
- package/dist/app-oauth/index.js.map +1 -1
- package/dist/app-oauth/issuer.d.ts +133 -0
- package/dist/app-oauth/issuer.js +247 -0
- package/dist/app-oauth/issuer.js.map +1 -0
- package/dist/assistant/index.js +13 -13
- package/dist/chat-react/index.js +4 -4
- package/dist/chat-routes/index.js +37 -67
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/promote-file-part.d.ts +2 -3
- package/dist/chat-store/index.js +4 -4
- package/dist/{chunk-MY3EJJ6Y.js → chunk-4FEH6266.js} +2 -2
- package/dist/{chunk-5Y7Z5G3Y.js → chunk-4GCPADYG.js} +20 -336
- package/dist/chunk-4GCPADYG.js.map +1 -0
- package/dist/{chunk-X556WVBG.js → chunk-4ZSLX3LY.js} +2 -2
- package/dist/chunk-57XPEL7X.js +26 -0
- package/dist/chunk-57XPEL7X.js.map +1 -0
- package/dist/chunk-6Z7TZVKZ.js +26 -0
- package/dist/chunk-6Z7TZVKZ.js.map +1 -0
- package/dist/{chunk-7KKOFMLD.js → chunk-AWIQQEFP.js} +1 -1
- package/dist/chunk-AWIQQEFP.js.map +1 -0
- package/dist/{chunk-VBKP2NLI.js → chunk-BTKI4XMM.js} +2 -2
- package/dist/{chunk-63QAQP7I.js → chunk-CNBVWPQC.js} +7 -7
- package/dist/{chunk-FENBDSIW.js → chunk-CQGEGPY7.js} +75 -3
- package/dist/chunk-CQGEGPY7.js.map +1 -0
- package/dist/chunk-CTREXL3O.js +335 -0
- package/dist/chunk-CTREXL3O.js.map +1 -0
- package/dist/chunk-DLWO3J7D.js +238 -0
- package/dist/chunk-DLWO3J7D.js.map +1 -0
- package/dist/{chunk-LWSJK546.js → chunk-DSMGS4IV.js} +5 -5
- package/dist/{chunk-LWSJK546.js.map → chunk-DSMGS4IV.js.map} +1 -1
- package/dist/{chunk-A3KPDLSF.js → chunk-EFPIHR6F.js} +18 -18
- package/dist/chunk-FRAICFTZ.js +191 -0
- package/dist/chunk-FRAICFTZ.js.map +1 -0
- package/dist/chunk-GS7VWV26.js +61 -0
- package/dist/chunk-GS7VWV26.js.map +1 -0
- package/dist/{chunk-NMSAZFRL.js → chunk-H5GQMLHA.js} +2 -2
- package/dist/{chunk-OQE6WMDP.js → chunk-HN6MZ2XL.js} +5 -5
- package/dist/chunk-HY57QRRW.js +11 -0
- package/dist/chunk-HY57QRRW.js.map +1 -0
- package/dist/{chunk-TCGZFSN5.js → chunk-KH4QSBNI.js} +2 -2
- package/dist/{chunk-JH3CKHF4.js → chunk-KJODHPWM.js} +8 -8
- package/dist/chunk-LSBI5MWS.js +66 -0
- package/dist/chunk-LSBI5MWS.js.map +1 -0
- package/dist/chunk-MDRH3SDA.js +106 -0
- package/dist/chunk-MDRH3SDA.js.map +1 -0
- package/dist/{chunk-VBWYH7UZ.js → chunk-NHYRIM4I.js} +3 -3
- package/dist/{chunk-BYP54FMI.js → chunk-O2RCDK5D.js} +30 -15
- package/dist/{chunk-BYP54FMI.js.map → chunk-O2RCDK5D.js.map} +1 -1
- package/dist/{chunk-EWOJATDS.js → chunk-PDD5A43Y.js} +3 -3
- package/dist/{chunk-23JUSUUB.js → chunk-RZLCBWGG.js} +2 -2
- package/dist/chunk-SFZELD6V.js +52 -0
- package/dist/chunk-SFZELD6V.js.map +1 -0
- package/dist/{chunk-Y4W6GK5X.js → chunk-UGFCLD32.js} +2 -2
- package/dist/{chunk-ZGUXI5SI.js → chunk-VUBJZEZB.js} +2 -2
- package/dist/{chunk-LQYIBL3G.js → chunk-WL7PZK7Q.js} +71 -1
- package/dist/chunk-WL7PZK7Q.js.map +1 -0
- package/dist/{chunk-7HZCFG2A.js → chunk-WP2GYFZ4.js} +38 -1
- package/dist/chunk-WP2GYFZ4.js.map +1 -0
- package/dist/{chunk-JK7R7BZQ.js → chunk-ZWJ3SZ2G.js} +2 -2
- package/dist/crypto/digest.d.ts +2 -0
- package/dist/crypto/index.d.ts +1 -0
- package/dist/crypto/index.js +6 -2
- package/dist/design-canvas/index.js +5 -3
- package/dist/design-canvas/index.js.map +1 -1
- package/dist/design-canvas-react/engine.js +7 -5
- package/dist/design-canvas-react/index.js +14 -12
- package/dist/design-canvas-react/index.js.map +1 -1
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/eval/index.d.ts +4 -0
- package/dist/eval/index.js +125 -0
- package/dist/eval/index.js.map +1 -1
- package/dist/eval/persona-driver.d.ts +37 -0
- package/dist/eval/research-plan.d.ts +25 -0
- package/dist/eval/research-plan.js +55 -0
- package/dist/eval/research-plan.js.map +1 -0
- package/dist/eval/scorecard.d.ts +38 -0
- package/dist/forms/blank.d.ts +2 -2
- package/dist/forms/index.js +4 -5
- package/dist/forms/index.js.map +1 -1
- package/dist/hosted-agent/application.js +2 -2
- package/dist/interactions/index.js +3 -3
- package/dist/knowledge/prelaunch-audit.d.ts +17 -0
- package/dist/knowledge/prelaunch-audit.js +67 -0
- package/dist/knowledge/prelaunch-audit.js.map +1 -0
- package/dist/media/drizzle.d.ts +207 -0
- package/dist/media/drizzle.js +26 -0
- package/dist/media/drizzle.js.map +1 -0
- package/dist/media/generate-request.d.ts +53 -0
- package/dist/media/generation-record.d.ts +68 -0
- package/dist/media/index.d.ts +13 -0
- package/dist/media/index.js +653 -0
- package/dist/media/index.js.map +1 -0
- package/dist/media/model-catalog.d.ts +109 -0
- package/dist/media/router-client.d.ts +40 -0
- package/dist/media/router-generation.d.ts +44 -0
- package/dist/media/speech-script.d.ts +20 -0
- package/dist/openui/index.js +1 -1
- package/dist/operator/index.js +4 -5
- package/dist/operator/index.js.map +1 -1
- package/dist/plans/decision.d.ts +48 -0
- package/dist/plans/drizzle.d.ts +25 -0
- package/dist/plans/drizzle.js +97 -0
- package/dist/plans/drizzle.js.map +1 -0
- package/dist/plans/index.d.ts +1 -1
- package/dist/plans/index.js +11 -3
- package/dist/platform/billing-config.d.ts +22 -0
- package/dist/platform/billing-config.js +36 -0
- package/dist/platform/billing-config.js.map +1 -0
- package/dist/platform/index.js +13 -11
- package/dist/platform/index.js.map +1 -1
- package/dist/preset-cloudflare/index.js +2 -1
- package/dist/preset-cloudflare/index.js.map +1 -1
- package/dist/profile/index.js +4 -5
- package/dist/profile/index.js.map +1 -1
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +13 -11
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/runtime/telemetry-cap.d.ts +24 -0
- package/dist/runtime/telemetry-cap.js +36 -0
- package/dist/runtime/telemetry-cap.js.map +1 -0
- package/dist/sandbox/index.js +12 -9
- package/dist/sequences/index.js +4 -2
- package/dist/sequences/index.js.map +1 -1
- package/dist/skills-placement/box.d.ts +50 -0
- package/dist/skills-placement/box.js +204 -0
- package/dist/skills-placement/box.js.map +1 -0
- package/dist/skills-placement/index.js +8 -96
- package/dist/skills-placement/index.js.map +1 -1
- package/dist/spend/budget.d.ts +13 -0
- package/dist/spend/drizzle.d.ts +55 -0
- package/dist/spend/drizzle.js +131 -0
- package/dist/spend/drizzle.js.map +1 -0
- package/dist/spend/index.d.ts +2 -1
- package/dist/spend/index.js +77 -58
- package/dist/spend/index.js.map +1 -1
- package/dist/spend/platform-settlements.d.ts +46 -0
- package/dist/stream/index.js +19 -19
- package/dist/studio/generated-media/index.d.ts +6 -0
- package/dist/studio/generated-media/index.js +590 -0
- package/dist/studio/generated-media/index.js.map +1 -0
- package/dist/studio/generated-media/output.d.ts +27 -0
- package/dist/studio/generated-media/store.d.ts +175 -0
- package/dist/studio-react/download-generations.d.ts +7 -0
- package/dist/studio-react/index.d.ts +1 -0
- package/dist/studio-react/index.js +85 -0
- package/dist/studio-react/index.js.map +1 -1
- package/dist/studio-react/use-studio-route.d.ts +44 -0
- package/dist/teams/invitations-api.d.ts +4 -0
- package/dist/teams/invitations-api.js +44 -32
- package/dist/teams/invitations-api.js.map +1 -1
- package/dist/theme/dom.d.ts +22 -0
- package/dist/theme/dom.js +18 -0
- package/dist/theme/dom.js.map +1 -0
- package/dist/vault/collaboration.d.ts +83 -0
- package/dist/vault/collaboration.js +215 -0
- package/dist/vault/collaboration.js.map +1 -0
- package/dist/vault/server.js +6 -53
- package/dist/vault/server.js.map +1 -1
- package/dist/vault/store/coordinator.d.ts +64 -0
- package/dist/vault/store/index.d.ts +12 -0
- package/dist/vault/store/index.js +1202 -0
- package/dist/vault/store/index.js.map +1 -0
- package/dist/vault/store/paths.d.ts +65 -0
- package/dist/vault/store/revisions.d.ts +211 -0
- package/dist/vault/store/sandbox-sync.d.ts +74 -0
- package/dist/vault/store/store.d.ts +161 -0
- package/dist/vault/store/tree.d.ts +11 -0
- package/dist/web/entry-server.d.ts +7 -0
- package/dist/web/entry-server.js +29 -0
- package/dist/web/entry-server.js.map +1 -0
- package/dist/web/fetch-guard.d.ts +6 -0
- package/dist/web/index.d.ts +3 -0
- package/dist/web/index.js +20 -4
- package/dist/web/mime.d.ts +16 -0
- package/dist/web/rate-limit.d.ts +25 -0
- package/dist/web/timeout.d.ts +9 -0
- package/dist/web-react/agent-profile-editor.js +3 -3
- package/dist/web-react/api-access-panel.d.ts +4 -2
- package/dist/web-react/document.d.ts +41 -0
- package/dist/web-react/document.js +103 -0
- package/dist/web-react/document.js.map +1 -0
- package/dist/web-react/index.js +31 -31
- package/dist/workspace-react/index.js +5 -5
- package/package.json +95 -4
- package/dist/DesignCanvas-OW3W2QXW.js +0 -13
- package/dist/DesignCanvasEditor-TCHZF25W.js +0 -16
- package/dist/chunk-5Y7Z5G3Y.js.map +0 -1
- package/dist/chunk-7HZCFG2A.js.map +0 -1
- package/dist/chunk-7KKOFMLD.js.map +0 -1
- package/dist/chunk-FENBDSIW.js.map +0 -1
- package/dist/chunk-LQYIBL3G.js.map +0 -1
- /package/dist/{DesignCanvas-OW3W2QXW.js.map → DesignCanvas-L6J72JQ2.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-TCHZF25W.js.map → DesignCanvasEditor-QFQD63MR.js.map} +0 -0
- /package/dist/{chunk-MY3EJJ6Y.js.map → chunk-4FEH6266.js.map} +0 -0
- /package/dist/{chunk-X556WVBG.js.map → chunk-4ZSLX3LY.js.map} +0 -0
- /package/dist/{chunk-VBKP2NLI.js.map → chunk-BTKI4XMM.js.map} +0 -0
- /package/dist/{chunk-63QAQP7I.js.map → chunk-CNBVWPQC.js.map} +0 -0
- /package/dist/{chunk-A3KPDLSF.js.map → chunk-EFPIHR6F.js.map} +0 -0
- /package/dist/{chunk-NMSAZFRL.js.map → chunk-H5GQMLHA.js.map} +0 -0
- /package/dist/{chunk-OQE6WMDP.js.map → chunk-HN6MZ2XL.js.map} +0 -0
- /package/dist/{chunk-TCGZFSN5.js.map → chunk-KH4QSBNI.js.map} +0 -0
- /package/dist/{chunk-JH3CKHF4.js.map → chunk-KJODHPWM.js.map} +0 -0
- /package/dist/{chunk-VBWYH7UZ.js.map → chunk-NHYRIM4I.js.map} +0 -0
- /package/dist/{chunk-EWOJATDS.js.map → chunk-PDD5A43Y.js.map} +0 -0
- /package/dist/{chunk-23JUSUUB.js.map → chunk-RZLCBWGG.js.map} +0 -0
- /package/dist/{chunk-Y4W6GK5X.js.map → chunk-UGFCLD32.js.map} +0 -0
- /package/dist/{chunk-ZGUXI5SI.js.map → chunk-VUBJZEZB.js.map} +0 -0
- /package/dist/{chunk-JK7R7BZQ.js.map → chunk-ZWJ3SZ2G.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/spend/drizzle.ts"],"sourcesContent":["/**\n * Drizzle (SQLite / D1) implementations of the spend module's persistence:\n * the expectation-ledger `SpendLedgerStorePort`, the ledger reads a settlement\n * sweep needs, and the per-workspace budget opt-in. This optional subpath keeps\n * the core `./spend` entry free of Drizzle.\n *\n * The product owns the tables and their migration. The ledger table needs the\n * columns of {@link SpendBoxLedgerTable}; every timestamp is epoch\n * MILLISECONDS, matching `SpendBoxRecord`, so declare them as plain `integer`\n * (a drizzle `{ mode: 'timestamp' }` column would silently divide by 1000).\n * `openDetachedRunIds` is a JSON-mode text column defaulting to `[]`; `extras`\n * is a nullable JSON-mode text column carrying `{ billingOwnerId }`.\n *\n * `update()` is deliberately NOT a read-modify-write. It runs on the live turn\n * path from a Worker, where two isolates recording activity for the same box\n * are ordinary, so every column is computed in ONE atomic SQL statement using\n * the exact merge rule `foldSpendBoxRecord` states for that field (moves\n * forward only / latest-wins-but-never-behind-activity / set-once). A lost race\n * under a read-modify-write could rewind the ceiling; under this fold a lost\n * race can only tighten it, which surfaces as a false alarm rather than a\n * missed charge.\n */\nimport { and, eq, gte, isNull, lte, or, sql, type SQL } from 'drizzle-orm'\nimport type { AnySQLiteColumn, AnySQLiteTable, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport { DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD } from './budget'\nimport type { SpendLedgerStorePort } from './store'\nimport type { SpendBoxPatch, SpendBoxRecord, SpendWindow } from './types'\n\n/** Any SQLite drizzle database — `any` erases the driver-specific run-result\n * and schema generics so better-sqlite3, D1, and libsql handles all fit. */\nexport type SpendDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any>\n\n/** Required Drizzle column properties of the expectation ledger; SQL column\n * names, foreign keys and indexes remain product-owned. */\nexport type SpendBoxLedgerTable = AnySQLiteTable & {\n sandboxId: AnySQLiteColumn\n workspaceId: AnySQLiteColumn\n createdAt: AnySQLiteColumn\n idleTimeoutSeconds: AnySQLiteColumn\n maxLifetimeSeconds: AnySQLiteColumn\n lastActivityAt: AnySQLiteColumn\n openDetachedRunIds: AnySQLiteColumn\n stoppedAt: AnySQLiteColumn\n deletedAt: AnySQLiteColumn\n extras: AnySQLiteColumn\n}\n\n/** The ledger a store or query reads: a database and the product's table. */\nexport interface SpendLedgerTableOptions {\n readonly db: SpendDatabase\n readonly table: SpendBoxLedgerTable\n}\n\ninterface SpendBoxLedgerRow {\n sandboxId: string\n workspaceId: string\n createdAt: number\n idleTimeoutSeconds: number\n maxLifetimeSeconds: number | null\n lastActivityAt: number\n openDetachedRunIds: string[] | null\n stoppedAt: number | null\n deletedAt: number | null\n extras: Record<string, unknown> | null\n}\n\nfunction rowToRecord(row: SpendBoxLedgerRow): SpendBoxRecord {\n return {\n sandboxId: row.sandboxId,\n workspaceId: row.workspaceId,\n createdAt: row.createdAt,\n idleTimeoutSeconds: row.idleTimeoutSeconds,\n maxLifetimeSeconds: row.maxLifetimeSeconds,\n lastActivityAt: row.lastActivityAt,\n openDetachedRunIds: row.openDetachedRunIds ?? [],\n stoppedAt: row.stoppedAt,\n deletedAt: row.deletedAt,\n ...(row.extras ? { extras: row.extras } : {}),\n }\n}\n\n/** Build the expectation-ledger store over the product's drizzle table. */\nexport function createDrizzleSpendStore(options: SpendLedgerTableOptions): SpendLedgerStorePort {\n const { db, table } = options\n\n async function load(sandboxId: string): Promise<SpendBoxRecord | null> {\n const [row] = await db.select().from(table).where(eq(table.sandboxId, sandboxId)).limit(1)\n return row ? rowToRecord(row as SpendBoxLedgerRow) : null\n }\n\n return {\n load,\n\n /**\n * Every box that could have been live at some point inside `window`.\n *\n * Deliberately COARSE: the box existed by the window's end and was not\n * recorded deleted before it began. The reconciler re-derives liveness from\n * the same fold `computeExpectedCeiling` uses (delete, stop, open detached\n * run, last activity plus idle timeout, capped by max lifetime), so this\n * only has to be a superset it can filter down. Encoding the real rule here\n * would put a second definition of \"live\" in SQL, free to drift from the one\n * the ceiling check uses. `stopped_at` is therefore not a filter: later\n * activity can clear a stop, and the fold decides which stop closed the box.\n *\n * Over-returning is correct; under-returning is the only real failure — a\n * box this query omits is a box the pass never notices went unbilled.\n */\n async listLiveBetween(window: SpendWindow): Promise<readonly SpendBoxRecord[]> {\n const rows = await db\n .select()\n .from(table)\n .where(and(lte(table.createdAt, window.endAt), or(isNull(table.deletedAt), gte(table.deletedAt, window.startAt))))\n return rows.map((row) => rowToRecord(row as SpendBoxLedgerRow))\n },\n\n async insert(record: SpendBoxRecord, extras?: Record<string, unknown>): Promise<SpendBoxRecord> {\n const [row] = await db\n .insert(table)\n .values({\n sandboxId: record.sandboxId,\n workspaceId: record.workspaceId,\n createdAt: record.createdAt,\n idleTimeoutSeconds: record.idleTimeoutSeconds,\n maxLifetimeSeconds: record.maxLifetimeSeconds,\n lastActivityAt: record.lastActivityAt,\n openDetachedRunIds: [...record.openDetachedRunIds],\n stoppedAt: record.stoppedAt,\n deletedAt: record.deletedAt,\n // Written in the SAME statement — a second UPDATE to attach extras\n // would leave a window where the reconciler cannot tell whose wallet\n // this box bills.\n extras: extras ?? null,\n } as never)\n .returning()\n return rowToRecord(row as SpendBoxLedgerRow)\n },\n\n async update(sandboxId: string, patch: SpendBoxPatch): Promise<SpendBoxRecord | null> {\n const hasActivity = patch.observedActivityAt !== undefined\n const hasStop = patch.stoppedAt !== undefined\n const activityValue = patch.observedActivityAt\n const stopValue = patch.stoppedAt\n\n const set: Partial<Record<keyof SpendBoxLedgerRow, SQL>> = {}\n\n // last_activity_at moves forward only. SQLite's two-argument MAX() is the\n // SCALAR max, not the aggregate, so this needs no GROUP BY — and a\n // replayed or out-of-order event therefore cannot rewind the ceiling.\n if (hasActivity) {\n set.lastActivityAt = sql`MAX(${table.lastActivityAt}, ${activityValue})`\n }\n\n // stopped_at is touched whenever activity might CLEAR it (work observed\n // after a recorded stop means the box is running again, and keeping the\n // stale stop would invent an over-ceiling finding out of the product's\n // own bookkeeping) or a new stop is being recorded (latest-wins, but never\n // behind the newly computed activity — a stop reported behind observed\n // work is not the stop that closed this box, so it does not move the column).\n //\n // The \"new last_activity_at\" sub-expression is repeated verbatim rather\n // than referenced, because SQLite evaluates every SET-clause expression\n // against the row's PRE-update values: one clause can never see\n // another's result.\n if (hasActivity || hasStop) {\n const newLastActivityAtExpr = hasActivity\n ? sql`MAX(${table.lastActivityAt}, ${activityValue})`\n : sql`${table.lastActivityAt}`\n const afterActivityClearExpr = hasActivity\n ? sql`(CASE WHEN ${table.stoppedAt} IS NOT NULL AND ${activityValue} > ${table.stoppedAt} THEN NULL ELSE ${table.stoppedAt} END)`\n : sql`${table.stoppedAt}`\n set.stoppedAt = hasStop\n ? sql`(CASE WHEN ${stopValue} >= (${newLastActivityAtExpr}) THEN ${stopValue} ELSE ${afterActivityClearExpr} END)`\n : afterActivityClearExpr\n }\n\n // deleted_at is set-once: a deleted sandbox id never returns, so a second\n // observation is duplicate delivery, not a second deletion.\n if (patch.deletedAt !== undefined) {\n set.deletedAt = sql`COALESCE(${table.deletedAt}, ${patch.deletedAt})`\n }\n\n // open_detached_run_ids is a SET encoded as a JSON array. Add is\n // insert-if-absent; remove rebuilds the array excluding the value. Both\n // read and write the same column expression inside one statement, and the\n // remove chains off whatever the add branch produced so the fold's own\n // field order holds: a patch that both adds and removes the same id nets\n // to removed.\n let runIdsExpr: SQL | undefined\n if (patch.openDetachedRunAdd !== undefined) {\n runIdsExpr = sql`(\n CASE\n WHEN EXISTS (SELECT 1 FROM json_each(${table.openDetachedRunIds}) WHERE value = ${patch.openDetachedRunAdd})\n THEN ${table.openDetachedRunIds}\n ELSE json_insert(${table.openDetachedRunIds}, '$[#]', ${patch.openDetachedRunAdd})\n END\n )`\n }\n if (patch.openDetachedRunRemove !== undefined) {\n const source = runIdsExpr ?? sql`${table.openDetachedRunIds}`\n runIdsExpr = sql`(\n SELECT COALESCE(json_group_array(value), '[]') FROM json_each(${source}) WHERE value != ${patch.openDetachedRunRemove}\n )`\n }\n if (runIdsExpr) set.openDetachedRunIds = runIdsExpr\n\n // A patch with every field undefined is a no-op — return the current row\n // rather than issuing an empty UPDATE.\n if (Object.keys(set).length === 0) return await load(sandboxId)\n\n const rows = await db\n .update(table)\n .set(set as never)\n .where(eq(table.sandboxId, sandboxId))\n .returning()\n // Absent row returns null, never a throw: the ledger legitimately does\n // not know every box (see the `unknown-box` finding class).\n const [row] = rows as SpendBoxLedgerRow[]\n return row ? rowToRecord(row) : null\n },\n }\n}\n\n/** Every distinct platform-user id the ledger has recorded as a box's\n * `extras.billingOwnerId` — the set of wallets a full pass needs to read. */\nexport async function listLedgerBillingOwnerIds(options: SpendLedgerTableOptions): Promise<string[]> {\n const { db, table } = options\n const rows = await db\n .select({ billingOwnerId: sql<string | null>`json_extract(${table.extras}, '$.billingOwnerId')` })\n .from(table)\n .where(sql`json_extract(${table.extras}, '$.billingOwnerId') IS NOT NULL`)\n return [...new Set(rows.map((row) => row.billingOwnerId).filter((id): id is string => Boolean(id)))]\n}\n\n/** Every sandbox id the ledger attributes to this workspace — the only place\n * the workspace-to-sandbox mapping exists; the platform does not model a workspace. */\nexport async function listWorkspaceSandboxIds(\n options: SpendLedgerTableOptions & { readonly workspaceId: string },\n): Promise<Set<string>> {\n const { db, table, workspaceId } = options\n const rows = await db.select({ sandboxId: table.sandboxId }).from(table).where(eq(table.workspaceId, workspaceId))\n return new Set(rows.map((row) => row.sandboxId as string))\n}\n\n/** The product's workspace table columns holding the compute-budget opt-in. */\nexport type SpendBudgetWorkspaceTable = AnySQLiteTable & {\n id: AnySQLiteColumn\n spendBudgetEnabled: AnySQLiteColumn\n spendBudgetLimitNanoUsd: AnySQLiteColumn\n}\n\nexport interface WorkspaceSpendBudgetConfig {\n readonly enabled: boolean\n readonly limitNanoUsd: number\n}\n\n/**\n * Opt-in per-workspace budget read. Absent or disabled — the default for every\n * workspace until it opts in — short-circuits the caller before any settlement\n * read runs, so an unopted workspace's provisioning path makes no extra network\n * call. A null limit falls back to {@link DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD}.\n */\nexport async function loadWorkspaceSpendBudgetConfig(options: {\n readonly db: SpendDatabase\n readonly workspaces: SpendBudgetWorkspaceTable\n readonly workspaceId: string\n}): Promise<WorkspaceSpendBudgetConfig> {\n const { db, workspaces, workspaceId } = options\n const [row] = await db\n .select({ enabled: workspaces.spendBudgetEnabled, limit: workspaces.spendBudgetLimitNanoUsd })\n .from(workspaces)\n .where(eq(workspaces.id, workspaceId))\n .limit(1)\n return {\n enabled: (row?.enabled as boolean | null | undefined) ?? false,\n limitNanoUsd: (row?.limit as number | null | undefined) ?? DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD,\n }\n}\n"],"mappings":";;;;;AAsBA,SAAS,KAAK,IAAI,KAAK,QAAQ,KAAK,IAAI,WAAqB;AA4C7D,SAAS,YAAY,KAAwC;AAC3D,SAAO;AAAA,IACL,WAAW,IAAI;AAAA,IACf,aAAa,IAAI;AAAA,IACjB,WAAW,IAAI;AAAA,IACf,oBAAoB,IAAI;AAAA,IACxB,oBAAoB,IAAI;AAAA,IACxB,gBAAgB,IAAI;AAAA,IACpB,oBAAoB,IAAI,sBAAsB,CAAC;AAAA,IAC/C,WAAW,IAAI;AAAA,IACf,WAAW,IAAI;AAAA,IACf,GAAI,IAAI,SAAS,EAAE,QAAQ,IAAI,OAAO,IAAI,CAAC;AAAA,EAC7C;AACF;AAGO,SAAS,wBAAwB,SAAwD;AAC9F,QAAM,EAAE,IAAI,MAAM,IAAI;AAEtB,iBAAe,KAAK,WAAmD;AACrE,UAAM,CAAC,GAAG,IAAI,MAAM,GAAG,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,GAAG,MAAM,WAAW,SAAS,CAAC,EAAE,MAAM,CAAC;AACzF,WAAO,MAAM,YAAY,GAAwB,IAAI;AAAA,EACvD;AAEA,SAAO;AAAA,IAC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K,IAAI,CAAC,QAAQ,IAAI,cAAc,EAAE,OAAO,CAAC,OAAqB,QAAQ,EAAE,CAAC,CAAC,CAAC;AACrG;AAIA,eAAsB,wBACpB,SACsB;AACtB,QAAM,EAAE,IAAI,OAAO,YAAY,IAAI;AACnC,QAAM,OAAO,MAAM,GAAG,OAAO,EAAE,WAAW,MAAM,UAAU,CAAC,EAAE,KAAK,KAAK,EAAE,MAAM,GAAG,MAAM,aAAa,WAAW,CAAC;AACjH,SAAO,IAAI,IAAI,KAAK,IAAI,CAAC,QAAQ,IAAI,SAAmB,CAAC;AAC3D;AAoBA,eAAsB,+BAA+B,SAIb;AACtC,QAAM,EAAE,IAAI,YAAY,YAAY,IAAI;AACxC,QAAM,CAAC,GAAG,IAAI,MAAM,GACjB,OAAO,EAAE,SAAS,WAAW,oBAAoB,OAAO,WAAW,wBAAwB,CAAC,EAC5F,KAAK,UAAU,EACf,MAAM,GAAG,WAAW,IAAI,WAAW,CAAC,EACpC,MAAM,CAAC;AACV,SAAO;AAAA,IACL,SAAU,KAAK,WAA0C;AAAA,IACzD,cAAe,KAAK,SAAuC;AAAA,EAC7D;AACF;","names":[]}
|
package/dist/spend/index.d.ts
CHANGED
|
@@ -35,6 +35,7 @@ export { createInMemorySpendLedgerStore, createSpendLedger, foldSpendBoxRecord,
|
|
|
35
35
|
export { DEFAULT_CEILING_TOLERANCE_MS, computeExpectedCeiling, type ComputeExpectedCeilingOptions, } from './ceiling';
|
|
36
36
|
export { chargeNanoUsd, isCharge, parseSandboxGroupKey, parseSettlementReference, settlementSandboxId, } from './reference';
|
|
37
37
|
export { reconcileSpend, type BoxRateResolver, type ObservedBalance, type ReconcileSpendOptions, type VelocityOptions, } from './reconcile';
|
|
38
|
-
export { ComputeBudgetExceededError, assertComputeBudget, createSandboxSpendHooks, type ComputeBudget, type ComputeBudgetRefusal, type SandboxSpendHooksOptions, type SandboxSpendSeam, type SpendProvisionObservation, } from './budget';
|
|
38
|
+
export { ComputeBudgetExceededError, DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD, assertComputeBudget, createSandboxSpendHooks, type ComputeBudget, type ComputeBudgetRefusal, type SandboxSpendHooksOptions, type SandboxSpendSeam, type SpendProvisionObservation, } from './budget';
|
|
39
39
|
export { MIN_CHILD_KEY_BUDGET_USD, ParentBudgetExhaustedError, deriveChildKeyBudgetUsd, type DeriveChildKeyBudgetInput, } from './delegate-budget';
|
|
40
40
|
export { formatSpendReport, spendReportToJson } from './report';
|
|
41
|
+
export { SPEND_BUDGET_LOOKBACK_MS, SPEND_RECONCILE_LOOKBACK_MS, fetchPlatformSettlementRows, sandboxChargeNanoUsd, type FetchPlatformSettlementRowsInput, } from './platform-settlements';
|
package/dist/spend/index.js
CHANGED
|
@@ -18,6 +18,12 @@ import {
|
|
|
18
18
|
spendReportToJson,
|
|
19
19
|
undeclaredExpectation
|
|
20
20
|
} from "../chunk-RHFN7TUV.js";
|
|
21
|
+
import {
|
|
22
|
+
ComputeBudgetExceededError,
|
|
23
|
+
DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD,
|
|
24
|
+
assertComputeBudget,
|
|
25
|
+
createSandboxSpendHooks
|
|
26
|
+
} from "../chunk-LSBI5MWS.js";
|
|
21
27
|
|
|
22
28
|
// src/spend/store.ts
|
|
23
29
|
function foldSpendBoxRecord(record, patch) {
|
|
@@ -129,64 +135,6 @@ function createSpendLedger(options) {
|
|
|
129
135
|
};
|
|
130
136
|
}
|
|
131
137
|
|
|
132
|
-
// src/spend/budget.ts
|
|
133
|
-
var ComputeBudgetExceededError = class extends Error {
|
|
134
|
-
workspaceId;
|
|
135
|
-
limitNanoUsd;
|
|
136
|
-
settledNanoUsd;
|
|
137
|
-
overageNanoUsd;
|
|
138
|
-
constructor(refusal) {
|
|
139
|
-
super(
|
|
140
|
-
`Compute budget exceeded for workspace ${refusal.workspaceId}: $${(refusal.settledNanoUsd / 1e9).toFixed(2)} settled against a cap of $${(refusal.limitNanoUsd / 1e9).toFixed(2)} (over by $${(refusal.overageNanoUsd / 1e9).toFixed(2)}). No sandbox was provisioned. Raise the cap or reconcile the spend before retrying.`
|
|
141
|
-
);
|
|
142
|
-
this.name = "ComputeBudgetExceededError";
|
|
143
|
-
this.workspaceId = refusal.workspaceId;
|
|
144
|
-
this.limitNanoUsd = refusal.limitNanoUsd;
|
|
145
|
-
this.settledNanoUsd = refusal.settledNanoUsd;
|
|
146
|
-
this.overageNanoUsd = refusal.overageNanoUsd;
|
|
147
|
-
}
|
|
148
|
-
};
|
|
149
|
-
async function assertComputeBudget(budget, workspaceId) {
|
|
150
|
-
if (!budget) return;
|
|
151
|
-
const settledNanoUsd = await budget.settledNanoUsd(workspaceId);
|
|
152
|
-
if (settledNanoUsd < budget.limitNanoUsd) return;
|
|
153
|
-
const refusal = {
|
|
154
|
-
workspaceId,
|
|
155
|
-
limitNanoUsd: budget.limitNanoUsd,
|
|
156
|
-
settledNanoUsd,
|
|
157
|
-
overageNanoUsd: settledNanoUsd - budget.limitNanoUsd,
|
|
158
|
-
at: (budget.now ?? Date.now)()
|
|
159
|
-
};
|
|
160
|
-
budget.onRefusal?.(refusal);
|
|
161
|
-
throw new ComputeBudgetExceededError(refusal);
|
|
162
|
-
}
|
|
163
|
-
function createSandboxSpendHooks(options) {
|
|
164
|
-
const { ledger, budget, onError } = options;
|
|
165
|
-
return {
|
|
166
|
-
async beforeProvision(input) {
|
|
167
|
-
await assertComputeBudget(budget, input.workspaceId);
|
|
168
|
-
},
|
|
169
|
-
async onProvisioned(observation) {
|
|
170
|
-
if (!ledger) return;
|
|
171
|
-
try {
|
|
172
|
-
await ledger.observeSandbox({
|
|
173
|
-
sandboxId: observation.sandboxId,
|
|
174
|
-
workspaceId: observation.workspaceId,
|
|
175
|
-
idleTimeoutSeconds: observation.idleTimeoutSeconds,
|
|
176
|
-
maxLifetimeSeconds: observation.maxLifetimeSeconds ?? null,
|
|
177
|
-
at: observation.at
|
|
178
|
-
});
|
|
179
|
-
} catch (err) {
|
|
180
|
-
onError?.(err);
|
|
181
|
-
}
|
|
182
|
-
},
|
|
183
|
-
onActivity(input) {
|
|
184
|
-
if (!ledger) return;
|
|
185
|
-
void ledger.recordActivity(input.sandboxId, input.at).catch((err) => onError?.(err));
|
|
186
|
-
}
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
|
|
190
138
|
// src/spend/delegate-budget.ts
|
|
191
139
|
var MIN_CHILD_KEY_BUDGET_USD = 0.5;
|
|
192
140
|
var ParentBudgetExhaustedError = class extends Error {
|
|
@@ -219,13 +167,82 @@ function deriveChildKeyBudgetUsd(input) {
|
|
|
219
167
|
if (ceiling <= 0) throw new ParentBudgetExhaustedError(input.requestedUsd, ceiling);
|
|
220
168
|
return Math.max(minChildUsd, Math.min(input.requestedUsd, Math.floor(ceiling * 100) / 100));
|
|
221
169
|
}
|
|
170
|
+
|
|
171
|
+
// src/spend/platform-settlements.ts
|
|
172
|
+
var TRANSACTIONS_PAGE_SIZE = 200;
|
|
173
|
+
var MAX_TRANSACTION_PAGES = 25;
|
|
174
|
+
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
175
|
+
var SPEND_RECONCILE_LOOKBACK_MS = 3 * DAY_MS;
|
|
176
|
+
var SPEND_BUDGET_LOOKBACK_MS = 30 * DAY_MS;
|
|
177
|
+
function toSettlementRow(item) {
|
|
178
|
+
return {
|
|
179
|
+
id: item.id,
|
|
180
|
+
// `sandbox:<kind>:<sandboxId>:<intervalStartMs>` — the ONLY place the
|
|
181
|
+
// billed interval's start is recorded, and what `settlementSandboxId`
|
|
182
|
+
// prefers over `groupKey`. Dropping it silently disables `over-ceiling`.
|
|
183
|
+
referenceId: item.referenceId ?? null,
|
|
184
|
+
// SIGNED exactly as the ledger stores it: negative is a charge, positive a
|
|
185
|
+
// credit. Never abs() at this boundary — `chargeNanoUsd` gives the unsigned
|
|
186
|
+
// magnitude and 0 for credits.
|
|
187
|
+
amountNanoUsd: Math.round(item.amount * 1e9),
|
|
188
|
+
type: item.type,
|
|
189
|
+
product: item.product,
|
|
190
|
+
groupKey: item.groupKey ?? null,
|
|
191
|
+
createdAt: Date.parse(item.createdAt),
|
|
192
|
+
description: item.description ?? null,
|
|
193
|
+
costBasisNanoUsd: item.costBasis != null ? Math.round(item.costBasis * 1e9) : null,
|
|
194
|
+
// This endpoint never returns a duration. `reconcileSpend` recovers one via
|
|
195
|
+
// `reference-span` (the interval start embedded in `referenceId`); inventing
|
|
196
|
+
// a value here would replace a bounded estimate with a guess.
|
|
197
|
+
billedMs: null,
|
|
198
|
+
// The API key the charge was created under: the only field that attributes
|
|
199
|
+
// a row to a PRODUCT rather than to a wallet. `null` is a real answer
|
|
200
|
+
// (legacy rows carry none) the ownership rule treats as undecidable, never
|
|
201
|
+
// foreign.
|
|
202
|
+
keyId: item.keyId ?? null
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
async function fetchPlatformSettlementRows(input) {
|
|
206
|
+
const fetchImpl = input.fetch ?? fetch;
|
|
207
|
+
const base = input.platformUrl.replace(/\/+$/, "");
|
|
208
|
+
const product = input.product ?? "sandbox";
|
|
209
|
+
const dateFrom = encodeURIComponent(new Date(input.dateFromMs).toISOString());
|
|
210
|
+
const rows = [];
|
|
211
|
+
let offset = 0;
|
|
212
|
+
for (let page = 0; ; page++) {
|
|
213
|
+
if (page >= MAX_TRANSACTION_PAGES) {
|
|
214
|
+
throw new Error(
|
|
215
|
+
`platform billing transactions truncated at ${MAX_TRANSACTION_PAGES} pages (${offset} rows) \u2014 narrow the lookback window, or this owner's settlement volume needs its own investigation`
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
const url = `${base}/v1/billing/transactions?product=${encodeURIComponent(product)}&limit=${TRANSACTIONS_PAGE_SIZE}&offset=${offset}&dateFrom=${dateFrom}`;
|
|
219
|
+
const res = await fetchImpl(url, { headers: { Authorization: `Bearer ${input.apiKey}` } });
|
|
220
|
+
if (!res.ok) {
|
|
221
|
+
throw new Error(`platform billing transactions fetch failed (${res.status}) at offset ${offset}`);
|
|
222
|
+
}
|
|
223
|
+
const result = await res.json();
|
|
224
|
+
for (const item of result.data.items) rows.push(toSettlementRow(item));
|
|
225
|
+
offset += result.data.items.length;
|
|
226
|
+
if (result.data.items.length === 0 || offset >= result.data.total) break;
|
|
227
|
+
}
|
|
228
|
+
return rows;
|
|
229
|
+
}
|
|
230
|
+
function sandboxChargeNanoUsd(rows, sandboxIds) {
|
|
231
|
+
return rows.reduce((sum, row) => {
|
|
232
|
+
const sandboxId = settlementSandboxId(row);
|
|
233
|
+
return sandboxId && sandboxIds.has(sandboxId) ? sum + chargeNanoUsd(row) : sum;
|
|
234
|
+
}, 0);
|
|
235
|
+
}
|
|
222
236
|
export {
|
|
223
237
|
ComputeBudgetExceededError,
|
|
224
238
|
DEFAULT_CEILING_TOLERANCE_MS,
|
|
225
239
|
DEFAULT_EXPECTATION_GRACE_MS,
|
|
240
|
+
DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD,
|
|
226
241
|
MIN_CHILD_KEY_BUDGET_USD,
|
|
227
242
|
ParentBudgetExhaustedError,
|
|
243
|
+
SPEND_BUDGET_LOOKBACK_MS,
|
|
228
244
|
SPEND_CHECKS,
|
|
245
|
+
SPEND_RECONCILE_LOOKBACK_MS,
|
|
229
246
|
assertComputeBudget,
|
|
230
247
|
assertSpendWindow,
|
|
231
248
|
assessAllExcluded,
|
|
@@ -237,6 +254,7 @@ export {
|
|
|
237
254
|
createSpendLedger,
|
|
238
255
|
decideBoxOwnership,
|
|
239
256
|
deriveChildKeyBudgetUsd,
|
|
257
|
+
fetchPlatformSettlementRows,
|
|
240
258
|
foldSpendBoxRecord,
|
|
241
259
|
formatSpendReport,
|
|
242
260
|
isCharge,
|
|
@@ -244,6 +262,7 @@ export {
|
|
|
244
262
|
parseSandboxGroupKey,
|
|
245
263
|
parseSettlementReference,
|
|
246
264
|
reconcileSpend,
|
|
265
|
+
sandboxChargeNanoUsd,
|
|
247
266
|
settlementSandboxId,
|
|
248
267
|
spendReportToJson,
|
|
249
268
|
undeclaredExpectation
|
package/dist/spend/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/spend/store.ts","../../src/spend/budget.ts","../../src/spend/delegate-budget.ts"],"sourcesContent":["import type { SpendBoxPatch, SpendBoxRecord, SpendWindow } from './types'\n\n/**\n * Persistence seam for the expectation ledger — the product implements it over\n * its own tables.\n *\n * Deliberately NOT compare-and-set, unlike `MissionStorePort`. A mission has one\n * serialized owner and a lost write corrupts a state machine; a box record is a\n * MONOTONIC FOLD (activity takes a max, a detached-run id joins or leaves a set,\n * delete is set-once) so concurrent writers converge no matter what order they\n * land in. The worst a lost race can do here is leave `lastActivityAt` behind\n * the truth — which makes the derived ceiling TIGHTER, so the failure mode is a\n * false alarm a human dismisses, never a missed charge. That asymmetry is the\n * whole reason the fold is shaped this way.\n *\n * `update` returns null when the row does not exist, never a throw.\n */\nexport interface SpendLedgerStorePort {\n load(sandboxId: string): Promise<SpendBoxRecord | null>\n /** `extras` are the opaque product-column values — write them in the SAME\n * statement as the record, or ignore them if the table has no extra columns. */\n insert(record: SpendBoxRecord, extras?: Record<string, unknown>): Promise<SpendBoxRecord>\n update(sandboxId: string, patch: SpendBoxPatch): Promise<SpendBoxRecord | null>\n /**\n * OPTIONAL — every box that could have been live during the window.\n *\n * This is the one capability that lets a reconciliation answer \"were we NOT\n * billed for something we DID ask for\". Without it the pass is driven entirely\n * by settlement rows, so a feed that returns nothing fires nothing and reads\n * as a clean bill. Omitting it is safe and additive: the pass reports\n * `expectation.declared: false` and refuses to certify a bill it could not\n * check (see {@link SpendReport.coverage}).\n *\n * **It may over-return.** The reconciler re-derives liveness itself with\n * `boxLivenessInWindow`, so a store that returns every row it has is correct,\n * merely slower. That is deliberate: the definition of \"live\" must live in one\n * place, not once per product's SQL. The intended predicate is the coarse one\n * a WHERE clause can express —\n *\n * ```sql\n * WHERE created_at <= :endAt AND (deleted_at IS NULL OR deleted_at >= :startAt)\n * ```\n *\n * — and the exact answer (idle timeout, max lifetime, stop, open detached run)\n * is the reconciler's.\n */\n listLiveBetween?(window: SpendWindow): Promise<readonly SpendBoxRecord[]>\n}\n\n/**\n * Apply one fold step. Exported so a SQL implementation and an in-memory one\n * reach the same record, and so a product can unit-test its own store against\n * the canonical answer.\n *\n * The two rules worth stating out loud:\n *\n * - `observedActivityAt` only ever moves `lastActivityAt` FORWARD. A replayed\n * or out-of-order event cannot rewind the ceiling.\n * - activity later than a recorded `stoppedAt` CLEARS the stop. A box that\n * worked after the product thought it stopped is running again, and keeping\n * the stale stop would make the ceiling too tight — inventing an over-ceiling\n * finding out of the product's own bookkeeping rather than the platform's.\n */\nexport function foldSpendBoxRecord(record: SpendBoxRecord, patch: SpendBoxPatch): SpendBoxRecord {\n let lastActivityAt = record.lastActivityAt\n let stoppedAt = record.stoppedAt\n let openDetachedRunIds = record.openDetachedRunIds\n\n if (patch.observedActivityAt !== undefined) {\n lastActivityAt = Math.max(lastActivityAt, patch.observedActivityAt)\n if (stoppedAt !== null && patch.observedActivityAt > stoppedAt) stoppedAt = null\n }\n if (patch.openDetachedRunAdd !== undefined && !openDetachedRunIds.includes(patch.openDetachedRunAdd)) {\n openDetachedRunIds = [...openDetachedRunIds, patch.openDetachedRunAdd]\n }\n if (patch.openDetachedRunRemove !== undefined) {\n openDetachedRunIds = openDetachedRunIds.filter((id) => id !== patch.openDetachedRunRemove)\n }\n if (patch.stoppedAt !== undefined) {\n // Latest-wins, but never behind observed activity: a stop we are told about\n // that predates work we watched is not the stop that closed this box.\n stoppedAt = patch.stoppedAt >= lastActivityAt ? patch.stoppedAt : stoppedAt\n }\n\n return {\n ...record,\n lastActivityAt,\n stoppedAt,\n openDetachedRunIds,\n // Set-once: a deleted sandbox id never comes back, so a second observation\n // is a duplicate delivery, not a second deletion.\n deletedAt: record.deletedAt ?? patch.deletedAt ?? null,\n }\n}\n\n/** An in-memory store that also lets a test inspect and force state. */\nexport interface InMemorySpendLedgerStore extends SpendLedgerStorePort {\n /** Every record, insertion order. */\n records(): SpendBoxRecord[]\n /** Unguarded direct write — simulates a crash-shaped or platform-seeded row. */\n put(record: SpendBoxRecord): void\n}\n\n/** Create an in-memory expectation ledger. Production writers use the same port. */\nexport function createInMemorySpendLedgerStore(): InMemorySpendLedgerStore {\n const rows = new Map<string, SpendBoxRecord>()\n return {\n async load(sandboxId) {\n const row = rows.get(sandboxId)\n return row ? structuredClone(row) : null\n },\n async insert(record) {\n const stored = structuredClone(record)\n rows.set(record.sandboxId, stored)\n return structuredClone(stored)\n },\n async update(sandboxId, patch) {\n const current = rows.get(sandboxId)\n if (!current) return null\n const next = foldSpendBoxRecord(current, patch)\n rows.set(sandboxId, next)\n return structuredClone(next)\n },\n async listLiveBetween(window) {\n // Deliberately the COARSE predicate a product's SQL can express, not the\n // exact one: the idle-timeout / max-lifetime / detached-run derivation is\n // the reconciler's, and this over-returning is what proves the reconciler\n // re-filters rather than trusting whatever a store hands it.\n return [...rows.values()]\n .filter(\n (row) =>\n row.createdAt <= window.endAt && (row.deletedAt === null || row.deletedAt >= window.startAt),\n )\n .map((row) => structuredClone(row))\n },\n records() {\n return [...rows.values()].map((row) => structuredClone(row))\n },\n put(record) {\n rows.set(record.sandboxId, structuredClone(record))\n },\n }\n}\n\n/** What the product tells the ledger when it first sees a box. */\nexport interface ObserveSandboxInput {\n readonly sandboxId: string\n readonly workspaceId: string\n /** The idle timeout the product asked the platform for, seconds. */\n readonly idleTimeoutSeconds: number\n /** The max lifetime the product asked for, seconds, when it asked for one. */\n readonly maxLifetimeSeconds?: number | null\n /** Defaults to the ledger's clock. */\n readonly at?: number\n}\n\nexport interface SpendLedgerOptions {\n readonly store: SpendLedgerStorePort\n /** Injectable clock (epoch ms). Default `Date.now`. */\n readonly now?: () => number\n /** Product columns written verbatim on every insert. */\n readonly extras?: Record<string, unknown>\n}\n\n/**\n * The recording half of spend verification: the product's own account of what\n * it asked the platform for.\n *\n * Every method is best-effort from the caller's point of view — a product wires\n * these into paths that must not fail because bookkeeping failed. They still\n * reject on a store error rather than swallowing it, so a caller that wants\n * fire-and-forget says so at the call site (`/sandbox`'s hook does).\n */\nexport interface SpendLedger {\n /**\n * Record that a box exists and is billable from now. Inserts on first sight,\n * and otherwise records activity — reuse and resume are both \"the platform is\n * charging for this box again\", and the record's own existence is what\n * distinguishes them, so no caller has to know which happened.\n */\n observeSandbox(input: ObserveSandboxInput): Promise<SpendBoxRecord>\n /** Record that the product saw this box do work. */\n recordActivity(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /**\n * Record that the product handed the platform work it will NOT watch finish.\n * Until the matching end is recorded, this box's ceiling cannot rest on\n * observed activity — see `computeExpectedCeiling`.\n */\n recordDetachedRunStarted(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that a detached run was confirmed finished. */\n recordDetachedRunEnded(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box stopped. */\n recordStopped(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box was deleted. */\n recordDeleted(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n}\n\n/** Create the recording half over a product-supplied store. */\nexport function createSpendLedger(options: SpendLedgerOptions): SpendLedger {\n const { store } = options\n const clock = options.now ?? Date.now\n\n return {\n async observeSandbox(input) {\n const at = input.at ?? clock()\n const existing = await store.load(input.sandboxId)\n if (existing) {\n const updated = await store.update(input.sandboxId, { observedActivityAt: at })\n return updated ?? existing\n }\n return await store.insert(\n {\n sandboxId: input.sandboxId,\n workspaceId: input.workspaceId,\n createdAt: at,\n idleTimeoutSeconds: input.idleTimeoutSeconds,\n maxLifetimeSeconds: input.maxLifetimeSeconds ?? null,\n lastActivityAt: at,\n openDetachedRunIds: [],\n stoppedAt: null,\n deletedAt: null,\n },\n options.extras,\n )\n },\n async recordActivity(sandboxId, at) {\n return await store.update(sandboxId, { observedActivityAt: at ?? clock() })\n },\n async recordDetachedRunStarted(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunAdd: runId,\n })\n },\n async recordDetachedRunEnded(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunRemove: runId,\n })\n },\n async recordStopped(sandboxId, at) {\n return await store.update(sandboxId, { stoppedAt: at ?? clock() })\n },\n async recordDeleted(sandboxId, at) {\n return await store.update(sandboxId, { deletedAt: at ?? clock() })\n },\n }\n}\n","import type { SpendLedger } from './store'\n\n/** Why provisioning was refused, with every number the decision used. */\nexport interface ComputeBudgetRefusal {\n readonly workspaceId: string\n /** The cap, unsigned nanodollars. */\n readonly limitNanoUsd: number\n /** Cumulative settled compute spend for this workspace, unsigned nanodollars. */\n readonly settledNanoUsd: number\n /** How far past the cap it already is. */\n readonly overageNanoUsd: number\n readonly at: number\n}\n\n/**\n * Provisioning refused because the workspace is already past its compute cap.\n *\n * Correctable by design: every number the decision used is on the error, so a\n * product can render \"this workspace has spent $X of its $Y compute budget\" and\n * an operator can raise the cap or investigate without reading logs.\n *\n * This is the failure mode the module exists to produce. A platform billing\n * defect that used to end in a silent negative balance now ends in provisioning\n * stopping and something loud happening instead.\n */\nexport class ComputeBudgetExceededError extends Error {\n readonly workspaceId: string\n readonly limitNanoUsd: number\n readonly settledNanoUsd: number\n readonly overageNanoUsd: number\n\n constructor(refusal: ComputeBudgetRefusal) {\n super(\n `Compute budget exceeded for workspace ${refusal.workspaceId}: ` +\n `$${(refusal.settledNanoUsd / 1_000_000_000).toFixed(2)} settled against a cap of ` +\n `$${(refusal.limitNanoUsd / 1_000_000_000).toFixed(2)} ` +\n `(over by $${(refusal.overageNanoUsd / 1_000_000_000).toFixed(2)}). ` +\n 'No sandbox was provisioned. Raise the cap or reconcile the spend before retrying.',\n )\n this.name = 'ComputeBudgetExceededError'\n this.workspaceId = refusal.workspaceId\n this.limitNanoUsd = refusal.limitNanoUsd\n this.settledNanoUsd = refusal.settledNanoUsd\n this.overageNanoUsd = refusal.overageNanoUsd\n }\n}\n\n/**\n * A per-workspace cap on sandbox compute.\n *\n * `/billing`'s budget primitive caps MODEL keys, and it works because the\n * platform enforces the cap at the key it minted. Sandbox compute has no such\n * key: a box bills the shared company wallet, so nothing upstream refuses. This\n * carries the same shape to the one place a consumer can still act — the moment\n * before it asks for another box.\n *\n * `settledNanoUsd` is a callback rather than a number because the authority is\n * the platform ledger, not this package: the product reads the same rows it\n * hands the reconciler. Cache it if the read is expensive; a cap is a\n * coarse-grained control and a slightly stale total still refuses.\n */\nexport interface ComputeBudget {\n /** The cap, unsigned nanodollars. */\n readonly limitNanoUsd: number\n /** Cumulative settled compute spend for the workspace, unsigned nanodollars. */\n readonly settledNanoUsd: (workspaceId: string) => Promise<number> | number\n /**\n * Called on every refusal, before the error is thrown. This is the alert\n * seam: a refusal nobody hears is a product that silently stopped working.\n */\n readonly onRefusal?: (refusal: ComputeBudgetRefusal) => void\n /** Injectable clock (epoch ms). Default `Date.now`. */\n readonly now?: () => number\n}\n\n/**\n * Throw {@link ComputeBudgetExceededError} when the workspace is already past\n * its cap. Returns normally — and reads nothing — when no budget is configured.\n *\n * Deliberately a pre-check against spend ALREADY SETTLED, not a reservation\n * against spend about to happen: settlement lags provisioning by design (the\n * platform's durable settlement queue), so there is no instant at which a\n * consumer could hold an accurate running total. The cap therefore overshoots by\n * at most the unsettled tail, which is bounded by the box's own idle timeout.\n * A cap that refuses one box late is worth far more than one that cannot be\n * implemented honestly.\n */\nexport async function assertComputeBudget(\n budget: ComputeBudget | undefined,\n workspaceId: string,\n): Promise<void> {\n if (!budget) return\n const settledNanoUsd = await budget.settledNanoUsd(workspaceId)\n if (settledNanoUsd < budget.limitNanoUsd) return\n\n const refusal: ComputeBudgetRefusal = {\n workspaceId,\n limitNanoUsd: budget.limitNanoUsd,\n settledNanoUsd,\n overageNanoUsd: settledNanoUsd - budget.limitNanoUsd,\n at: (budget.now ?? Date.now)(),\n }\n budget.onRefusal?.(refusal)\n throw new ComputeBudgetExceededError(refusal)\n}\n\n// ── the /sandbox seam ─────────────────────────────────────────────────────────\n\n/**\n * What `/sandbox` reports once a box is provisioned, reused or resumed.\n *\n * Structurally identical to `SandboxProvisionedObservation` in `/sandbox`, and\n * deliberately re-declared rather than imported: `/spend` composes `/sandbox`,\n * so a type import in the other direction would invert the dependency. The two\n * are pinned together by a compile-time assignment in this module's tests.\n */\nexport interface SpendProvisionObservation {\n readonly workspaceId: string\n readonly userId?: string\n readonly sandboxId: string\n readonly boxKey?: string | undefined\n readonly idleTimeoutSeconds: number\n readonly maxLifetimeSeconds?: number | undefined\n readonly at: number\n}\n\n/**\n * The optional seam `EnsureWorkspaceSandboxOptions.spend` and the turn\n * primitives' `spend` option both accept. One object, wired in both places.\n */\nexport interface SandboxSpendSeam {\n beforeProvision?(input: { workspaceId: string; userId?: string }): Promise<void> | void\n onProvisioned?(observation: SpendProvisionObservation): Promise<void> | void\n /** Synchronous by contract — it sits on the turn path. See `createSandboxSpendHooks`. */\n onActivity?(input: { sandboxId: string; at: number }): void\n}\n\nexport interface SandboxSpendHooksOptions {\n /** Records box lifecycle. Omit to run the budget guard alone. */\n readonly ledger?: SpendLedger\n /** Refuses provisioning past a cap. Omit to record alone. */\n readonly budget?: ComputeBudget\n /**\n * Called when RECORDING fails. Recording is best-effort — a bookkeeping\n * failure must never take down the provisioning it is bookkeeping — so this\n * is the only place such a failure is visible. A refusal is NOT routed here;\n * refusals throw, by design.\n */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * Build the object to hand `ensureWorkspaceSandbox`'s `spend` option.\n *\n * Wiring it is the entire adoption cost: one field, and the product's boxes are\n * both budget-capped and recorded.\n */\nexport function createSandboxSpendHooks(options: SandboxSpendHooksOptions): SandboxSpendSeam {\n const { ledger, budget, onError } = options\n return {\n async beforeProvision(input) {\n await assertComputeBudget(budget, input.workspaceId)\n },\n async onProvisioned(observation) {\n if (!ledger) return\n try {\n await ledger.observeSandbox({\n sandboxId: observation.sandboxId,\n workspaceId: observation.workspaceId,\n idleTimeoutSeconds: observation.idleTimeoutSeconds,\n maxLifetimeSeconds: observation.maxLifetimeSeconds ?? null,\n at: observation.at,\n })\n } catch (err) {\n onError?.(err)\n }\n },\n onActivity(input) {\n if (!ledger) return\n // The turn path calls this synchronously and does not await it, so the\n // promise is settled here rather than escaping as an unhandled rejection.\n // Recording activity is a monotonic max, so a write that lands late — or\n // out of order against another turn's — still converges.\n void ledger.recordActivity(input.sandboxId, input.at).catch((err: unknown) => onError?.(err))\n },\n }\n}\n","/**\n * The budget-derived delegated mint — the platform's reservation contract as\n * one function.\n *\n * The platform RESERVES a delegated child key's budget against its parent's\n * REMAINING budget: an ask above remaining is a hard refusal (no amounts in\n * the response), which is how every delegated mint in a fleet product died\n * until the derivation landed (hardware-agent #165, 2026-10-09: a flat $25\n * default asked of a $5-remaining parent refused 100% of mints). Products\n * that mint delegated keys must derive the ask from what the platform\n * actually guarantees:\n *\n * - the parent's remaining budget is UNKNOWN → the configured ask stands\n * (the platform isn't reporting a ceiling; nothing better is knowable);\n * - remaining ≤ 0 → refuse with a correctable top-up error, before any\n * mint is attempted;\n * - otherwise → ask min(configured, remaining) floored to whole cents,\n * never below the platform's minimum child budget (the floor keeps the\n * mint VALID — a below-minimum ask is refused by the key API).\n *\n * Note the boundary honestly: with remaining between $0.01 and the minimum,\n * the derived ask (the floor) still exceeds remaining and the platform will\n * refuse it — that case is indistinguishable from exhausted for the caller\n * and surfaces through the same error path with the numbers attached.\n */\n\n/** The platform's minimum child-key budget. Asks below it are refused by the\n * key API, so the derivation never produces one. */\nexport const MIN_CHILD_KEY_BUDGET_USD = 0.5\n\n/** The source key is exhausted — the only refusal this contract throws.\n * Correctable by design: both numbers the decision used are on the error. */\nexport class ParentBudgetExhaustedError extends Error {\n readonly requestedUsd: number\n readonly parentRemainingUsd: number\n\n constructor(requestedUsd: number, parentRemainingUsd: number) {\n super(\n `workspace source key has no budget remaining ($${parentRemainingUsd.toFixed(2)}) — ` +\n `top up or raise its cap before sandbox turns (the mint would have asked $${requestedUsd.toFixed(2)})`,\n )\n this.name = 'ParentBudgetExhaustedError'\n this.requestedUsd = requestedUsd\n this.parentRemainingUsd = parentRemainingUsd\n }\n}\n\nexport interface DeriveChildKeyBudgetInput {\n /** The configured/default ask (the product's mint budget). Must be a\n * finite positive number. */\n readonly requestedUsd: number\n /** The parent's REMAINING budget as the platform's verify/key info\n * reports it. `null`/`undefined`/non-finite = unknown (not reported). */\n readonly parentRemainingUsd?: number | null\n /** Minimum child budget override. Default {@link MIN_CHILD_KEY_BUDGET_USD}. */\n readonly minChildUsd?: number\n}\n\n/** Derive the delegated child-key budget from the parent's remaining budget:\n * the ask the mint should make — never above a known remaining, never below\n * the platform minimum. Throws {@link ParentBudgetExhaustedError} when the\n * parent is exhausted, before any mint is attempted. */\nexport function deriveChildKeyBudgetUsd(input: DeriveChildKeyBudgetInput): number {\n const minChildUsd = input.minChildUsd ?? MIN_CHILD_KEY_BUDGET_USD\n if (!Number.isFinite(input.requestedUsd) || input.requestedUsd <= 0) {\n throw new Error(\n `deriveChildKeyBudgetUsd: requestedUsd must be a finite positive USD amount (got ${input.requestedUsd})`,\n )\n }\n if (!Number.isFinite(minChildUsd) || minChildUsd <= 0) {\n throw new Error(\n `deriveChildKeyBudgetUsd: minChildUsd must be a finite positive USD amount (got ${minChildUsd})`,\n )\n }\n const ceiling = input.parentRemainingUsd\n const known = typeof ceiling === 'number' && Number.isFinite(ceiling)\n if (!known) return input.requestedUsd\n if (ceiling <= 0) throw new ParentBudgetExhaustedError(input.requestedUsd, ceiling)\n // Never above remaining (floored to whole cents), never below the platform\n // minimum: max(min, min(requested, floor(remaining·100)/100)).\n return Math.max(minChildUsd, Math.min(input.requestedUsd, Math.floor(ceiling * 100) / 100))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+DO,SAAS,mBAAmB,QAAwB,OAAsC;AAC/F,MAAI,iBAAiB,OAAO;AAC5B,MAAI,YAAY,OAAO;AACvB,MAAI,qBAAqB,OA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,IAAI;AAAA,MACR,kFAAkF,WAAW;AAAA,IAC/F;AAAA,EACF;AACA,QAAM,UAAU,MAAM;AACtB,QAAM,QAAQ,OAAO,YAAY,YAAY,OAAO,SAAS,OAAO;AACpE,MAAI,CAAC,MAAO,QAAO,MAAM;AACzB,MAAI,WAAW,EAAG,OAAM,IAAI,2BAA2B,MAAM,cAAc,OAAO;AAGlF,SAAO,KAAK,IAAI,aAAa,KAAK,IAAI,MAAM,cAAc,KAAK,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;AAC5F;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/spend/store.ts","../../src/spend/delegate-budget.ts","../../src/spend/platform-settlements.ts"],"sourcesContent":["import type { SpendBoxPatch, SpendBoxRecord, SpendWindow } from './types'\n\n/**\n * Persistence seam for the expectation ledger — the product implements it over\n * its own tables.\n *\n * Deliberately NOT compare-and-set, unlike `MissionStorePort`. A mission has one\n * serialized owner and a lost write corrupts a state machine; a box record is a\n * MONOTONIC FOLD (activity takes a max, a detached-run id joins or leaves a set,\n * delete is set-once) so concurrent writers converge no matter what order they\n * land in. The worst a lost race can do here is leave `lastActivityAt` behind\n * the truth — which makes the derived ceiling TIGHTER, so the failure mode is a\n * false alarm a human dismisses, never a missed charge. That asymmetry is the\n * whole reason the fold is shaped this way.\n *\n * `update` returns null when the row does not exist, never a throw.\n */\nexport interface SpendLedgerStorePort {\n load(sandboxId: string): Promise<SpendBoxRecord | null>\n /** `extras` are the opaque product-column values — write them in the SAME\n * statement as the record, or ignore them if the table has no extra columns. */\n insert(record: SpendBoxRecord, extras?: Record<string, unknown>): Promise<SpendBoxRecord>\n update(sandboxId: string, patch: SpendBoxPatch): Promise<SpendBoxRecord | null>\n /**\n * OPTIONAL — every box that could have been live during the window.\n *\n * This is the one capability that lets a reconciliation answer \"were we NOT\n * billed for something we DID ask for\". Without it the pass is driven entirely\n * by settlement rows, so a feed that returns nothing fires nothing and reads\n * as a clean bill. Omitting it is safe and additive: the pass reports\n * `expectation.declared: false` and refuses to certify a bill it could not\n * check (see {@link SpendReport.coverage}).\n *\n * **It may over-return.** The reconciler re-derives liveness itself with\n * `boxLivenessInWindow`, so a store that returns every row it has is correct,\n * merely slower. That is deliberate: the definition of \"live\" must live in one\n * place, not once per product's SQL. The intended predicate is the coarse one\n * a WHERE clause can express —\n *\n * ```sql\n * WHERE created_at <= :endAt AND (deleted_at IS NULL OR deleted_at >= :startAt)\n * ```\n *\n * — and the exact answer (idle timeout, max lifetime, stop, open detached run)\n * is the reconciler's.\n */\n listLiveBetween?(window: SpendWindow): Promise<readonly SpendBoxRecord[]>\n}\n\n/**\n * Apply one fold step. Exported so a SQL implementation and an in-memory one\n * reach the same record, and so a product can unit-test its own store against\n * the canonical answer.\n *\n * The two rules worth stating out loud:\n *\n * - `observedActivityAt` only ever moves `lastActivityAt` FORWARD. A replayed\n * or out-of-order event cannot rewind the ceiling.\n * - activity later than a recorded `stoppedAt` CLEARS the stop. A box that\n * worked after the product thought it stopped is running again, and keeping\n * the stale stop would make the ceiling too tight — inventing an over-ceiling\n * finding out of the product's own bookkeeping rather than the platform's.\n */\nexport function foldSpendBoxRecord(record: SpendBoxRecord, patch: SpendBoxPatch): SpendBoxRecord {\n let lastActivityAt = record.lastActivityAt\n let stoppedAt = record.stoppedAt\n let openDetachedRunIds = record.openDetachedRunIds\n\n if (patch.observedActivityAt !== undefined) {\n lastActivityAt = Math.max(lastActivityAt, patch.observedActivityAt)\n if (stoppedAt !== null && patch.observedActivityAt > stoppedAt) stoppedAt = null\n }\n if (patch.openDetachedRunAdd !== undefined && !openDetachedRunIds.includes(patch.openDetachedRunAdd)) {\n openDetachedRunIds = [...openDetachedRunIds, patch.openDetachedRunAdd]\n }\n if (patch.openDetachedRunRemove !== undefined) {\n openDetachedRunIds = openDetachedRunIds.filter((id) => id !== patch.openDetachedRunRemove)\n }\n if (patch.stoppedAt !== undefined) {\n // Latest-wins, but never behind observed activity: a stop we are told about\n // that predates work we watched is not the stop that closed this box.\n stoppedAt = patch.stoppedAt >= lastActivityAt ? patch.stoppedAt : stoppedAt\n }\n\n return {\n ...record,\n lastActivityAt,\n stoppedAt,\n openDetachedRunIds,\n // Set-once: a deleted sandbox id never comes back, so a second observation\n // is a duplicate delivery, not a second deletion.\n deletedAt: record.deletedAt ?? patch.deletedAt ?? null,\n }\n}\n\n/** An in-memory store that also lets a test inspect and force state. */\nexport interface InMemorySpendLedgerStore extends SpendLedgerStorePort {\n /** Every record, insertion order. */\n records(): SpendBoxRecord[]\n /** Unguarded direct write — simulates a crash-shaped or platform-seeded row. */\n put(record: SpendBoxRecord): void\n}\n\n/** Create an in-memory expectation ledger. Production writers use the same port. */\nexport function createInMemorySpendLedgerStore(): InMemorySpendLedgerStore {\n const rows = new Map<string, SpendBoxRecord>()\n return {\n async load(sandboxId) {\n const row = rows.get(sandboxId)\n return row ? structuredClone(row) : null\n },\n async insert(record) {\n const stored = structuredClone(record)\n rows.set(record.sandboxId, stored)\n return structuredClone(stored)\n },\n async update(sandboxId, patch) {\n const current = rows.get(sandboxId)\n if (!current) return null\n const next = foldSpendBoxRecord(current, patch)\n rows.set(sandboxId, next)\n return structuredClone(next)\n },\n async listLiveBetween(window) {\n // Deliberately the COARSE predicate a product's SQL can express, not the\n // exact one: the idle-timeout / max-lifetime / detached-run derivation is\n // the reconciler's, and this over-returning is what proves the reconciler\n // re-filters rather than trusting whatever a store hands it.\n return [...rows.values()]\n .filter(\n (row) =>\n row.createdAt <= window.endAt && (row.deletedAt === null || row.deletedAt >= window.startAt),\n )\n .map((row) => structuredClone(row))\n },\n records() {\n return [...rows.values()].map((row) => structuredClone(row))\n },\n put(record) {\n rows.set(record.sandboxId, structuredClone(record))\n },\n }\n}\n\n/** What the product tells the ledger when it first sees a box. */\nexport interface ObserveSandboxInput {\n readonly sandboxId: string\n readonly workspaceId: string\n /** The idle timeout the product asked the platform for, seconds. */\n readonly idleTimeoutSeconds: number\n /** The max lifetime the product asked for, seconds, when it asked for one. */\n readonly maxLifetimeSeconds?: number | null\n /** Defaults to the ledger's clock. */\n readonly at?: number\n}\n\nexport interface SpendLedgerOptions {\n readonly store: SpendLedgerStorePort\n /** Injectable clock (epoch ms). Default `Date.now`. */\n readonly now?: () => number\n /** Product columns written verbatim on every insert. */\n readonly extras?: Record<string, unknown>\n}\n\n/**\n * The recording half of spend verification: the product's own account of what\n * it asked the platform for.\n *\n * Every method is best-effort from the caller's point of view — a product wires\n * these into paths that must not fail because bookkeeping failed. They still\n * reject on a store error rather than swallowing it, so a caller that wants\n * fire-and-forget says so at the call site (`/sandbox`'s hook does).\n */\nexport interface SpendLedger {\n /**\n * Record that a box exists and is billable from now. Inserts on first sight,\n * and otherwise records activity — reuse and resume are both \"the platform is\n * charging for this box again\", and the record's own existence is what\n * distinguishes them, so no caller has to know which happened.\n */\n observeSandbox(input: ObserveSandboxInput): Promise<SpendBoxRecord>\n /** Record that the product saw this box do work. */\n recordActivity(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /**\n * Record that the product handed the platform work it will NOT watch finish.\n * Until the matching end is recorded, this box's ceiling cannot rest on\n * observed activity — see `computeExpectedCeiling`.\n */\n recordDetachedRunStarted(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that a detached run was confirmed finished. */\n recordDetachedRunEnded(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box stopped. */\n recordStopped(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box was deleted. */\n recordDeleted(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n}\n\n/** Create the recording half over a product-supplied store. */\nexport function createSpendLedger(options: SpendLedgerOptions): SpendLedger {\n const { store } = options\n const clock = options.now ?? Date.now\n\n return {\n async observeSandbox(input) {\n const at = input.at ?? clock()\n const existing = await store.load(input.sandboxId)\n if (existing) {\n const updated = await store.update(input.sandboxId, { observedActivityAt: at })\n return updated ?? existing\n }\n return await store.insert(\n {\n sandboxId: input.sandboxId,\n workspaceId: input.workspaceId,\n createdAt: at,\n idleTimeoutSeconds: input.idleTimeoutSeconds,\n maxLifetimeSeconds: input.maxLifetimeSeconds ?? null,\n lastActivityAt: at,\n openDetachedRunIds: [],\n stoppedAt: null,\n deletedAt: null,\n },\n options.extras,\n )\n },\n async recordActivity(sandboxId, at) {\n return await store.update(sandboxId, { observedActivityAt: at ?? clock() })\n },\n async recordDetachedRunStarted(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunAdd: runId,\n })\n },\n async recordDetachedRunEnded(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunRemove: runId,\n })\n },\n async recordStopped(sandboxId, at) {\n return await store.update(sandboxId, { stoppedAt: at ?? clock() })\n },\n async recordDeleted(sandboxId, at) {\n return await store.update(sandboxId, { deletedAt: at ?? clock() })\n },\n }\n}\n","/**\n * The budget-derived delegated mint — the platform's reservation contract as\n * one function.\n *\n * The platform RESERVES a delegated child key's budget against its parent's\n * REMAINING budget: an ask above remaining is a hard refusal (no amounts in\n * the response), which is how every delegated mint in a fleet product died\n * until the derivation landed (hardware-agent #165, 2026-10-09: a flat $25\n * default asked of a $5-remaining parent refused 100% of mints). Products\n * that mint delegated keys must derive the ask from what the platform\n * actually guarantees:\n *\n * - the parent's remaining budget is UNKNOWN → the configured ask stands\n * (the platform isn't reporting a ceiling; nothing better is knowable);\n * - remaining ≤ 0 → refuse with a correctable top-up error, before any\n * mint is attempted;\n * - otherwise → ask min(configured, remaining) floored to whole cents,\n * never below the platform's minimum child budget (the floor keeps the\n * mint VALID — a below-minimum ask is refused by the key API).\n *\n * Note the boundary honestly: with remaining between $0.01 and the minimum,\n * the derived ask (the floor) still exceeds remaining and the platform will\n * refuse it — that case is indistinguishable from exhausted for the caller\n * and surfaces through the same error path with the numbers attached.\n */\n\n/** The platform's minimum child-key budget. Asks below it are refused by the\n * key API, so the derivation never produces one. */\nexport const MIN_CHILD_KEY_BUDGET_USD = 0.5\n\n/** The source key is exhausted — the only refusal this contract throws.\n * Correctable by design: both numbers the decision used are on the error. */\nexport class ParentBudgetExhaustedError extends Error {\n readonly requestedUsd: number\n readonly parentRemainingUsd: number\n\n constructor(requestedUsd: number, parentRemainingUsd: number) {\n super(\n `workspace source key has no budget remaining ($${parentRemainingUsd.toFixed(2)}) — ` +\n `top up or raise its cap before sandbox turns (the mint would have asked $${requestedUsd.toFixed(2)})`,\n )\n this.name = 'ParentBudgetExhaustedError'\n this.requestedUsd = requestedUsd\n this.parentRemainingUsd = parentRemainingUsd\n }\n}\n\nexport interface DeriveChildKeyBudgetInput {\n /** The configured/default ask (the product's mint budget). Must be a\n * finite positive number. */\n readonly requestedUsd: number\n /** The parent's REMAINING budget as the platform's verify/key info\n * reports it. `null`/`undefined`/non-finite = unknown (not reported). */\n readonly parentRemainingUsd?: number | null\n /** Minimum child budget override. Default {@link MIN_CHILD_KEY_BUDGET_USD}. */\n readonly minChildUsd?: number\n}\n\n/** Derive the delegated child-key budget from the parent's remaining budget:\n * the ask the mint should make — never above a known remaining, never below\n * the platform minimum. Throws {@link ParentBudgetExhaustedError} when the\n * parent is exhausted, before any mint is attempted. */\nexport function deriveChildKeyBudgetUsd(input: DeriveChildKeyBudgetInput): number {\n const minChildUsd = input.minChildUsd ?? MIN_CHILD_KEY_BUDGET_USD\n if (!Number.isFinite(input.requestedUsd) || input.requestedUsd <= 0) {\n throw new Error(\n `deriveChildKeyBudgetUsd: requestedUsd must be a finite positive USD amount (got ${input.requestedUsd})`,\n )\n }\n if (!Number.isFinite(minChildUsd) || minChildUsd <= 0) {\n throw new Error(\n `deriveChildKeyBudgetUsd: minChildUsd must be a finite positive USD amount (got ${minChildUsd})`,\n )\n }\n const ceiling = input.parentRemainingUsd\n const known = typeof ceiling === 'number' && Number.isFinite(ceiling)\n if (!known) return input.requestedUsd\n if (ceiling <= 0) throw new ParentBudgetExhaustedError(input.requestedUsd, ceiling)\n // Never above remaining (floored to whole cents), never below the platform\n // minimum: max(min, min(requested, floor(remaining·100)/100)).\n return Math.max(minChildUsd, Math.min(input.requestedUsd, Math.floor(ceiling * 100) / 100))\n}\n","/**\n * The authenticated read of settled rows from the Tangle platform's\n * `/v1/billing/transactions` — `reconcileSpend`'s `rows` input and the budget\n * guard's `settledNanoUsd`.\n *\n * SCOPING. The narrowest scope this endpoint offers is a WALLET: `product` is\n * the platform's own service taxonomy, stamped on every charge from every\n * consumer app, so a wallet that runs two of our products returns both. Which\n * wallets to read, and with which key, is the product's decision; separating\n * one product's boxes from a sibling's inside one wallet is `ownership.ts`'s.\n * Rows therefore carry `keyId` through this boundary untouched — dropping it\n * would make every row `undecidable` and the ownership rule useless.\n *\n * BOUNDED. Unfiltered, a heavily used account's transaction history can carry\n * tens of thousands of rows. Every read is bounded by `dateFrom` and a hard\n * page cap that THROWS on hit — a loud truncation, never a silent undercount\n * that would blow a Worker's per-invocation subrequest budget while reading as\n * a clean pass.\n */\nimport { chargeNanoUsd, settlementSandboxId } from './reference'\nimport type { SettlementRow } from './types'\n\nconst TRANSACTIONS_PAGE_SIZE = 200\n\n/** Hard stop at 25 pages (5,000 rows) per key per read. Hitting it throws. */\nconst MAX_TRANSACTION_PAGES = 25\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\n/** The reconciliation pass runs daily; three days of lookback is ample margin\n * over that cadence plus the platform's own settlement lag, without\n * re-reading months of already-reconciled history on every run. */\nexport const SPEND_RECONCILE_LOOKBACK_MS = 3 * DAY_MS\n\n/** The budget guard enforces a ROLLING cap, not a lifetime one. It runs on the\n * provisioning path, where an unbounded read would risk the subrequest limit\n * on an active account, and 30 days is generous for a cap meant to catch an\n * ongoing leak rather than audit a workspace's full history. */\nexport const SPEND_BUDGET_LOOKBACK_MS = 30 * DAY_MS\n\ninterface PlatformTransactionItem {\n readonly id: string\n readonly amount: number\n readonly type: string\n readonly product: string | null\n readonly description: string | null\n readonly createdAt: string\n readonly referenceId?: string | null\n readonly groupKey?: string | null\n readonly costBasis?: number | null\n readonly keyId?: string | null\n}\n\ninterface PlatformTransactionsResponse {\n readonly success: boolean\n readonly data: {\n readonly items: readonly PlatformTransactionItem[]\n readonly total: number\n readonly limit: number\n readonly offset: number\n }\n}\n\n/** Read the settled rows one platform API key can see. */\nexport interface FetchPlatformSettlementRowsInput {\n /** The platform origin, e.g. `https://id.tangle.tools`. Trailing slashes are ignored. */\n readonly platformUrl: string\n /** The wallet owner's own platform key — the only credential that can read its ledger. */\n readonly apiKey: string\n /** Earliest `createdAt` to read, epoch ms. */\n readonly dateFromMs: number\n /**\n * The platform's billing product, one per read: `credit_transactions.product`\n * spans router | sandbox | intelligence | blueprint-agent | evals | agent-builder.\n * Defaults to `sandbox`, the compute the reconciler bounds.\n *\n * Deliberately no `keyId` filter: the endpoint accepts one, but it drops rows\n * the platform left unattributed, and those are exactly the rows worth\n * seeing. Ownership is declared in the reconciler, where the exclusion is\n * reported, not hidden in a query string.\n */\n readonly product?: string\n readonly fetch?: typeof fetch\n}\n\nfunction toSettlementRow(item: PlatformTransactionItem): SettlementRow {\n return {\n id: item.id,\n // `sandbox:<kind>:<sandboxId>:<intervalStartMs>` — the ONLY place the\n // billed interval's start is recorded, and what `settlementSandboxId`\n // prefers over `groupKey`. Dropping it silently disables `over-ceiling`.\n referenceId: item.referenceId ?? null,\n // SIGNED exactly as the ledger stores it: negative is a charge, positive a\n // credit. Never abs() at this boundary — `chargeNanoUsd` gives the unsigned\n // magnitude and 0 for credits.\n amountNanoUsd: Math.round(item.amount * 1_000_000_000),\n type: item.type,\n product: item.product,\n groupKey: item.groupKey ?? null,\n createdAt: Date.parse(item.createdAt),\n description: item.description ?? null,\n costBasisNanoUsd: item.costBasis != null ? Math.round(item.costBasis * 1_000_000_000) : null,\n // This endpoint never returns a duration. `reconcileSpend` recovers one via\n // `reference-span` (the interval start embedded in `referenceId`); inventing\n // a value here would replace a bounded estimate with a guess.\n billedMs: null,\n // The API key the charge was created under: the only field that attributes\n // a row to a PRODUCT rather than to a wallet. `null` is a real answer\n // (legacy rows carry none) the ownership rule treats as undecidable, never\n // foreign.\n keyId: item.keyId ?? null,\n }\n}\n\n/**\n * Every settled row of one product the key's wallet holds since `dateFromMs`.\n * Throws on a non-2xx response or when the page cap is hit; a caller sweeping\n * several wallets catches per wallet so one bad credential never aborts the pass.\n */\nexport async function fetchPlatformSettlementRows(input: FetchPlatformSettlementRowsInput): Promise<SettlementRow[]> {\n const fetchImpl = input.fetch ?? fetch\n const base = input.platformUrl.replace(/\\/+$/, '')\n const product = input.product ?? 'sandbox'\n const dateFrom = encodeURIComponent(new Date(input.dateFromMs).toISOString())\n const rows: SettlementRow[] = []\n let offset = 0\n for (let page = 0; ; page++) {\n if (page >= MAX_TRANSACTION_PAGES) {\n throw new Error(\n `platform billing transactions truncated at ${MAX_TRANSACTION_PAGES} pages (${offset} rows) — ` +\n \"narrow the lookback window, or this owner's settlement volume needs its own investigation\",\n )\n }\n const url =\n `${base}/v1/billing/transactions?product=${encodeURIComponent(product)}` +\n `&limit=${TRANSACTIONS_PAGE_SIZE}&offset=${offset}&dateFrom=${dateFrom}`\n const res = await fetchImpl(url, { headers: { Authorization: `Bearer ${input.apiKey}` } })\n if (!res.ok) {\n throw new Error(`platform billing transactions fetch failed (${res.status}) at offset ${offset}`)\n }\n const result = (await res.json()) as PlatformTransactionsResponse\n for (const item of result.data.items) rows.push(toSettlementRow(item))\n offset += result.data.items.length\n if (result.data.items.length === 0 || offset >= result.data.total) break\n }\n return rows\n}\n\n/**\n * Unsigned charge of the rows whose sandbox is in `sandboxIds`.\n *\n * The budget cap is per WORKSPACE while the settlement feed is per WALLET, so a\n * row counts only when the product's own ledger attributes its box to this\n * workspace. The residue is excluded on purpose: an undercount lets one more\n * box through, an overcount refuses a box for someone else's spend.\n */\nexport function sandboxChargeNanoUsd(rows: readonly SettlementRow[], sandboxIds: ReadonlySet<string>): number {\n return rows.reduce((sum, row) => {\n const sandboxId = settlementSandboxId(row)\n return sandboxId && sandboxIds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,SAAS;AACb,WAAS,OAAO,KAAK,QAAQ;AAC3B,QAAI,QAAQ,uBAAuB;AACjC,YAAM,IAAI;AAAA,QACR,8CAA8C,qBAAqB,WAAW,MAAM;AAAA,MAEtF;AAAA,IACF;AACA,UAAM,MACJ,GAAG,IAAI,oCAAoC,mBAAmB,OAAO,CAAC,UAC5D,sBAAsB,WAAW,MAAM,aAAa,QAAQ;AACxE,UAAM,MAAM,MAAM,UAAU,KAAK,EAAE,SAAS,EAAE,eAAe,UAAU,MAAM,MAAM,GAAG,EAAE,CAAC;AACzF,QAAI,CAAC,IAAI,IAAI;AACX,YAAM,IAAI,MAAM,+CAA+C,IAAI,MAAM,eAAe,MAAM,EAAE;AAAA,IAClG;AACA,UAAM,SAAU,MAAM,IAAI,KAAK;AAC/B,eAAW,QAAQ,OAAO,KAAK,MAAO,MAAK,KAAK,gBAAgB,IAAI,CAAC;AACrE,cAAU,OAAO,KAAK,MAAM;AAC5B,QAAI,OAAO,KAAK,MAAM,WAAW,KAAK,UAAU,OAAO,KAAK,MAAO;AAAA,EACrE;AACA,SAAO;AACT;AAUO,SAAS,qBAAqB,MAAgC,YAAyC;AAC5G,SAAO,KAAK,OAAO,CAAC,KAAK,QAAQ;AAC/B,UAAM,YAAY,oBAAoB,GAAG;AACzC,WAAO,aAAa,WAAW,IAAI,SAAS,IAAI,MAAM,cAAc,GAAG,IAAI;AAAA,EAC7E,GAAG,CAAC;AACN;","names":[]}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { SettlementRow } from './types';
|
|
2
|
+
/** The reconciliation pass runs daily; three days of lookback is ample margin
|
|
3
|
+
* over that cadence plus the platform's own settlement lag, without
|
|
4
|
+
* re-reading months of already-reconciled history on every run. */
|
|
5
|
+
export declare const SPEND_RECONCILE_LOOKBACK_MS: number;
|
|
6
|
+
/** The budget guard enforces a ROLLING cap, not a lifetime one. It runs on the
|
|
7
|
+
* provisioning path, where an unbounded read would risk the subrequest limit
|
|
8
|
+
* on an active account, and 30 days is generous for a cap meant to catch an
|
|
9
|
+
* ongoing leak rather than audit a workspace's full history. */
|
|
10
|
+
export declare const SPEND_BUDGET_LOOKBACK_MS: number;
|
|
11
|
+
/** Read the settled rows one platform API key can see. */
|
|
12
|
+
export interface FetchPlatformSettlementRowsInput {
|
|
13
|
+
/** The platform origin, e.g. `https://id.tangle.tools`. Trailing slashes are ignored. */
|
|
14
|
+
readonly platformUrl: string;
|
|
15
|
+
/** The wallet owner's own platform key — the only credential that can read its ledger. */
|
|
16
|
+
readonly apiKey: string;
|
|
17
|
+
/** Earliest `createdAt` to read, epoch ms. */
|
|
18
|
+
readonly dateFromMs: number;
|
|
19
|
+
/**
|
|
20
|
+
* The platform's billing product, one per read: `credit_transactions.product`
|
|
21
|
+
* spans router | sandbox | intelligence | blueprint-agent | evals | agent-builder.
|
|
22
|
+
* Defaults to `sandbox`, the compute the reconciler bounds.
|
|
23
|
+
*
|
|
24
|
+
* Deliberately no `keyId` filter: the endpoint accepts one, but it drops rows
|
|
25
|
+
* the platform left unattributed, and those are exactly the rows worth
|
|
26
|
+
* seeing. Ownership is declared in the reconciler, where the exclusion is
|
|
27
|
+
* reported, not hidden in a query string.
|
|
28
|
+
*/
|
|
29
|
+
readonly product?: string;
|
|
30
|
+
readonly fetch?: typeof fetch;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Every settled row of one product the key's wallet holds since `dateFromMs`.
|
|
34
|
+
* Throws on a non-2xx response or when the page cap is hit; a caller sweeping
|
|
35
|
+
* several wallets catches per wallet so one bad credential never aborts the pass.
|
|
36
|
+
*/
|
|
37
|
+
export declare function fetchPlatformSettlementRows(input: FetchPlatformSettlementRowsInput): Promise<SettlementRow[]>;
|
|
38
|
+
/**
|
|
39
|
+
* Unsigned charge of the rows whose sandbox is in `sandboxIds`.
|
|
40
|
+
*
|
|
41
|
+
* The budget cap is per WORKSPACE while the settlement feed is per WALLET, so a
|
|
42
|
+
* row counts only when the product's own ledger attributes its box to this
|
|
43
|
+
* workspace. The residue is excluded on purpose: an undercount lets one more
|
|
44
|
+
* box through, an overcount refuses a box for someone else's spend.
|
|
45
|
+
*/
|
|
46
|
+
export declare function sandboxChargeNanoUsd(rows: readonly SettlementRow[], sandboxIds: ReadonlySet<string>): number;
|
package/dist/stream/index.js
CHANGED
|
@@ -12,23 +12,6 @@ import {
|
|
|
12
12
|
normalizeClientTurnId,
|
|
13
13
|
resolveChatTurn
|
|
14
14
|
} from "../chunk-YG66IHDU.js";
|
|
15
|
-
import {
|
|
16
|
-
DEFAULT_RUNNING_TURN_LEASE_MS,
|
|
17
|
-
DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,
|
|
18
|
-
TURN_EVENTS_MIGRATION_SQL,
|
|
19
|
-
TURN_STATUS_LEASE_MIGRATION_SQL,
|
|
20
|
-
TURN_STATUS_RETENTION_MIGRATION_SQL,
|
|
21
|
-
TURN_STATUS_SCOPE_MIGRATION_SQL,
|
|
22
|
-
coalesceChatStreamEvents,
|
|
23
|
-
coalesceDeltas,
|
|
24
|
-
createBufferedTurnTap,
|
|
25
|
-
createD1TurnEventStore,
|
|
26
|
-
createMemoryTurnEventStore,
|
|
27
|
-
isLiveProgressEvent,
|
|
28
|
-
pumpBufferedTurn,
|
|
29
|
-
replayTurnEvents,
|
|
30
|
-
stampReplaySeq
|
|
31
|
-
} from "../chunk-ISP6ZH3G.js";
|
|
32
15
|
import {
|
|
33
16
|
MISSING_TOOL_TERMINAL_ERROR,
|
|
34
17
|
MISSING_TOOL_TERMINAL_REASON,
|
|
@@ -50,9 +33,26 @@ import {
|
|
|
50
33
|
terminalizeDanglingAssistantToolUpdates,
|
|
51
34
|
terminalizeDanglingToolPart,
|
|
52
35
|
terminalizeDanglingToolParts
|
|
53
|
-
} from "../chunk-
|
|
36
|
+
} from "../chunk-VUBJZEZB.js";
|
|
54
37
|
import "../chunk-6VQCFJWP.js";
|
|
55
|
-
import
|
|
38
|
+
import {
|
|
39
|
+
DEFAULT_RUNNING_TURN_LEASE_MS,
|
|
40
|
+
DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,
|
|
41
|
+
TURN_EVENTS_MIGRATION_SQL,
|
|
42
|
+
TURN_STATUS_LEASE_MIGRATION_SQL,
|
|
43
|
+
TURN_STATUS_RETENTION_MIGRATION_SQL,
|
|
44
|
+
TURN_STATUS_SCOPE_MIGRATION_SQL,
|
|
45
|
+
coalesceChatStreamEvents,
|
|
46
|
+
coalesceDeltas,
|
|
47
|
+
createBufferedTurnTap,
|
|
48
|
+
createD1TurnEventStore,
|
|
49
|
+
createMemoryTurnEventStore,
|
|
50
|
+
isLiveProgressEvent,
|
|
51
|
+
pumpBufferedTurn,
|
|
52
|
+
replayTurnEvents,
|
|
53
|
+
stampReplaySeq
|
|
54
|
+
} from "../chunk-ISP6ZH3G.js";
|
|
55
|
+
import "../chunk-WL7PZK7Q.js";
|
|
56
56
|
export {
|
|
57
57
|
DEFAULT_RUNNING_TURN_LEASE_MS,
|
|
58
58
|
DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,
|