@tangle-network/agent-app 4.0.13 → 4.0.14

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.
@@ -8,7 +8,7 @@ import {
8
8
  } from "../chunk-AWIQQEFP.js";
9
9
  import {
10
10
  createWorkspaceKeyManager
11
- } from "../chunk-QPD42X6A.js";
11
+ } from "../chunk-UXVSX5N6.js";
12
12
  import "../chunk-VGS2NXLB.js";
13
13
  import {
14
14
  assistantRowIdForTurn,
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createChatTurnRoutes,
3
3
  streamChatRouteAsSandboxEvents
4
- } from "../chunk-CD4SJXYC.js";
4
+ } from "../chunk-FAI54DBZ.js";
5
5
  import "../chunk-SBHFMDR7.js";
6
6
  import "../chunk-H6BRJU5M.js";
7
7
  import "../chunk-4DBHC63F.js";
@@ -35,7 +35,7 @@ import "../chunk-S5SRJJQG.js";
35
35
  import "../chunk-GD4ONMKJ.js";
36
36
  import "../chunk-UGWQLQDS.js";
37
37
  import "../chunk-R32MULDK.js";
38
- import "../chunk-XCUT2I52.js";
38
+ import "../chunk-5QQBQS7W.js";
39
39
  import "../chunk-D6UJEOZQ.js";
40
40
  import "../chunk-YYA2CVOY.js";
41
41
  import "../chunk-KSLTD4FI.js";
@@ -2,7 +2,7 @@ import {
2
2
  ProtectedModelSettlementError,
3
3
  createRouterProtectedModelPort,
4
4
  runProtectedRouterTurn
5
- } from "../chunk-GWATTXFR.js";
5
+ } from "../chunk-FYF564KJ.js";
6
6
  import {
7
7
  DURABLE_HOP_BUDGET_MS,
8
8
  asksForLanguage,
@@ -27,7 +27,7 @@ import {
27
27
  turnKnowledgeInstructions,
28
28
  workspaceKnowledgeForTurn,
29
29
  workspaceTurnCheckpoints
30
- } from "../chunk-XCUT2I52.js";
30
+ } from "../chunk-5QQBQS7W.js";
31
31
  import {
32
32
  DEFAULT_TANGLE_BILLING_ENFORCEMENT_ENV_VAR,
33
33
  DEFAULT_TANGLE_ROUTER_BASE_URL,
@@ -14,7 +14,7 @@ import {
14
14
  turnKnowledgeInstructions,
15
15
  workspaceKnowledgeForTurn,
16
16
  workspaceTurnCheckpoints
17
- } from "../chunk-XCUT2I52.js";
17
+ } from "../chunk-5QQBQS7W.js";
18
18
  import "../chunk-D6UJEOZQ.js";
19
19
  import "../chunk-YYA2CVOY.js";
20
20
  import "../chunk-KSLTD4FI.js";
@@ -22,6 +22,10 @@
22
22
  * the derived ask (the floor) still exceeds remaining and the platform will
23
23
  * refuse it — that case is indistinguishable from exhausted for the caller
24
24
  * and surfaces through the same error path with the numbers attached.
25
+ *
26
+ * A known remaining means the source has a budget: pass `spendThrough: true`
27
+ * with the derived ask to the workspace key manager's `ensureKey`, so each
28
+ * live child spends the source's cap instead of reserving its own share.
25
29
  */
26
30
  /** The platform's minimum child-key budget. Asks below it are refused by the
27
31
  * key API, so the derivation never produces one. */
@@ -1 +1 @@
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.has(sandboxId) ? sum + chargeNanoUsd(row) : sum\n }, 0)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DO,SAAS,mBAAmB,QAAwB,OAAsC;AAC/F,MAAI,iBAAiB,OAAO;AAC5B,MAAI,YAAY,OAAO;AACvB,MAAI,qBAAqB,OAAO;AAEhC,MAAI,MAAM,uBAAuB,QAAW;AAC1C,qBAAiB,KAAK,IAAI,gBAAgB,MAAM,kBAAkB;AAClE,QAAI,cAAc,QAAQ,MAAM,qBAAqB,UAAW,aAAY;AAAA,EAC9E;AACA,MAAI,MAAM,uBAAuB,UAAa,CAAC,mBAAmB,SAAS,MAAM,kBAAkB,GAAG;AACpG,yBAAqB,CAAC,GAAG,oBAAoB,MAAM,kBAAkB;AAAA,EACvE;AACA,MAAI,MAAM,0BAA0B,QAAW;AAC7C,yBAAqB,mBAAmB,OAAO,CAAC,OAAO,OAAO,MAAM,qBAAqB;AAAA,EAC3F;AACA,MAAI,MAAM,cAAc,QAAW;AAGjC,gBAAY,MAAM,aAAa,iBAAiB,MAAM,YAAY;AAAA,EACpE;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA,IAGA,WAAW,OAAO,aAAa,MAAM,aAAa;AAAA,EACpD;AACF;AAWO,SAAS,iCAA2D;AACzE,QAAM,OAAO,oBAAI,IAA4B;AAC7C,SAAO;AAAA,IACL,MAAM,KAAK,WAAW;AACpB,YAAM,MAAM,KAAK,IAAI,SAAS;AAC9B,aAAO,MAAM,gBAAgB,GAAG,IAAI;AAAA,IACtC;AAAA,IACA,MAAM,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nH,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,OAAO,MAAM,YAAY,QAAQ,QAAQ,EAAE;AACjD,QAAM,UAAU,MAAM,WAAW;AACjC,QAAM,WAAW,mBAAmB,IAAI,KAAK,MAAM,UAAU,EAAE,YAAY,CAAC;AAC5E,QAAM,OAAwB,CAAC;AAC/B,MAAI,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":[]}
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 * A known remaining means the source has a budget: pass `spendThrough: true`\n * with the derived ask to the workspace key manager's `ensureKey`, so each\n * live child spends the source's cap instead of reserving its own share.\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.has(sandboxId) ? sum + chargeNanoUsd(row) : sum\n }, 0)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DO,SAAS,mBAAmB,QAAwB,OAAsC;AAC/F,MAAI,iBAAiB,OAAO;AAC5B,MAAI,YAAY,OAAO;AACvB,MAAI,qBAAqB,OAAO;AAEhC,MAAI,MAAM,uBAAuB,QAAW;AAC1C,qBAAiB,KAAK,IAAI,gBAAgB,MAAM,kBAAkB;AAClE,QAAI,cAAc,QAAQ,MAAM,qBAAqB,UAAW,aAAY;AAAA,EAC9E;AACA,MAAI,MAAM,uBAAu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AAM,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":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "4.0.13",
3
+ "version": "4.0.14",
4
4
  "packageManager": "pnpm@11.28.8",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/billing/identity-locks.ts","../src/billing/identity-bound.ts","../src/billing/index.ts"],"sourcesContent":["import type { DurableWorkspaceKeyManagerOptions } from './identity-bound'\n\nexport function createWorkspaceKeyLocks(\n leaseWaitMs: number,\n options: DurableWorkspaceKeyManagerOptions,\n now: () => Date,\n leaseMs: number,\n leasePollMs: number,\n leaseRenewIntervalMs: number,\n operationId: () => string,\n sleep: (ms: number) => Promise<void>,\n) {\n const localLocks = new Map<string, Promise<void>>()\n\n async function withLocalLock<T>(scope: string, work: () => Promise<T>): Promise<T> {\n const previous = localLocks.get(scope) ?? Promise.resolve()\n let release!: () => void\n const current = new Promise<void>((resolve) => { release = resolve })\n localLocks.set(scope, current)\n await previous\n try {\n return await work()\n } finally {\n release()\n if (localLocks.get(scope) === current) localLocks.delete(scope)\n }\n }\n\n async function withDurableLease<T>(\n scope: string,\n work: () => Promise<T>,\n onLeaseLost?: () => Promise<void>,\n ): Promise<T> {\n const leaseOperationId = operationId()\n const startedAt = Date.now()\n let acquired = false\n while (!acquired && Date.now() - startedAt <= leaseWaitMs) {\n acquired = await options.store.acquireLease(scope, leaseOperationId, now(), leaseMs)\n if (!acquired) await sleep(leasePollMs)\n }\n if (!acquired) throw new Error('workspace child-key issuance is busy; retry the request')\n\n let stopped = false\n let leaseLost: Error | null = null\n let leaseTimer: ReturnType<typeof setTimeout> | undefined\n let renewalPromise: Promise<void> | undefined\n const scheduleRenewal = () => {\n if (stopped || leaseLost) return\n leaseTimer = setTimeout(() => {\n leaseTimer = undefined\n const renewal = (async () => {\n try {\n if (!await options.store.renewLease(scope, leaseOperationId, now(), leaseMs)) {\n leaseLost = new Error('workspace child-key lease was lost during reconciliation')\n return\n }\n scheduleRenewal()\n } catch (error) {\n leaseLost = error instanceof Error ? error : new Error('workspace child-key lease renewal failed')\n }\n })()\n renewalPromise = renewal\n void renewal.finally(() => {\n if (renewalPromise === renewal) renewalPromise = undefined\n }).catch(() => undefined)\n }, leaseRenewIntervalMs)\n }\n scheduleRenewal()\n\n let workError: unknown\n let leaseLossCleanupError: unknown\n try {\n const result = await work()\n if (leaseLost) throw leaseLost\n return result\n } catch (error) {\n workError = error\n throw error\n } finally {\n stopped = true\n if (leaseTimer) clearTimeout(leaseTimer)\n if (renewalPromise) await renewalPromise\n if (leaseLost && onLeaseLost) {\n try {\n await onLeaseLost()\n } catch (error) {\n leaseLossCleanupError = error\n }\n }\n try {\n await options.store.releaseLease(scope, leaseOperationId)\n } catch (error) {\n if (workError === undefined) throw error\n }\n if (workError === undefined && leaseLossCleanupError) {\n throw new Error('workspace child-key lease was lost and cleanup failed', { cause: leaseLossCleanupError })\n }\n if (workError === undefined && leaseLost) throw leaseLost\n }\n }\n return { withLocalLock, withDurableLease }\n}\n","import { createWorkspaceKeyLocks } from './identity-locks'\nimport { assertWorkspaceKeyCryptoUsable } from './crypto-probe'\nimport type { KeyCrypto, KeyProvisioner } from './index'\n\n/** Lifecycle state for a durable delegated key row. */\nexport type WorkspaceKeyStatus =\n | 'legacy'\n | 'provisioning'\n | 'active'\n | 'revocation_pending'\n | 'revoked'\n | 'orphaned'\n\n/** Product partition used by the key store and remote provisioner. */\nexport type WorkspaceKeyProduct = string\n\n/** The identity fields that bind a child key to its paying owner and source. */\nexport interface WorkspaceKeyIdentity {\n workspaceId: string\n ownerUserId: string\n platformUserId: string\n sourceKeyId?: string | null\n /** A non-secret digest of the source credential. */\n sourceKeyFingerprint: string\n}\n\n/** A product/workspace/owner lookup scope. */\nexport interface DurableWorkspaceKeyScope {\n workspaceId: string\n ownerUserId: string\n product: WorkspaceKeyProduct\n}\n\n/** A persisted child-key row owned by this manager. */\nexport interface DurableWorkspaceKeyRecord {\n id: string\n workspaceId: string\n ownerUserId: string\n product: WorkspaceKeyProduct\n platformUserId: string\n sourceKeyId: string | null\n sourceKeyFingerprint: string\n /** The remote name, used to recover a create after a crash. A store may return null: the placeholder id carries it. */\n name: string | null\n /** The persisted retry identity for the remote create. Absent on legacy rows without a persisted create identity. */\n idempotencyKey?: string | null\n keyId: string\n keyEncrypted: string\n budgetUsd: number\n expiresAt: Date\n status: WorkspaceKeyStatus\n revocationAttempts: number\n nextRevocationAt: Date | null\n lastRevocationError: string | null\n createdAt: Date\n}\n\n/** A row that has been written before its remote child key exists. */\nexport interface DurableWorkspaceKeyProvisioningRecord extends DurableWorkspaceKeyRecord {\n status: 'provisioning'\n}\n\ntype DurableWorkspaceKeyCreateResult = Awaited<ReturnType<KeyProvisioner['createKey']>> & {\n budgetUsd?: number | null\n budgetRemaining?: number\n expiresAt?: string | null\n}\n\n/** The exact request identity that must be reused when recovering a create. */\nexport interface DurableWorkspaceKeyCreateInput {\n name: string\n product: string\n budgetUsd: number\n expiresAt: string\n /** Stable across process restarts for one persisted provisioning row. */\n idempotencyKey: string\n}\n\n/** The remote operations required by the durable manager. */\nexport interface DurableWorkspaceKeyProvisioner {\n /** True only when replay returns the original child for the persisted request identity. */\n supportsIdempotentCreate?: true\n /** Create one child key. Non-idempotent providers recover through stable-name discovery only. */\n createKey(input: DurableWorkspaceKeyCreateInput): Promise<DurableWorkspaceKeyCreateResult>\n getKey(id: string): Promise<{\n budgetUsd?: number | null\n budgetSpent?: number\n expiresAt?: string | null\n }>\n /**\n * Retire one child. `slot` is the row that minted it: its name, its own source and Platform user, so a child minted\n * under an earlier source is retired through that source's slot. A typed refusal carries `refusal.status`.\n */\n revokeKey(id: string, slot?: Pick<DurableWorkspaceKeyRecord, 'name' | 'sourceKeyId' | 'platformUserId'>): Promise<unknown>\n /** Find remote keys for a specific persisted provisioning attempt. */\n findCreatedKeys(input: {\n name: string\n product: string\n sourceKeyId?: string | null\n }): Promise<Array<{ id: string }>>\n}\n\n/** Optional compare-and-set lifecycle writes for stores that support fencing. */\nexport interface DurableWorkspaceKeyConditionalWrites {\n /** Return false when the row was no longer provisioning. */\n markProvisioningRemote(input: { id: string; keyId: string }): Promise<boolean>\n /** Return false when the row was no longer provisioning. */\n markActive(input: {\n id: string\n keyId: string\n keyEncrypted: string\n expiresAt: Date\n budgetUsd: number\n }): Promise<boolean>\n}\n\n/** Persistence operations for identity-bound key lifecycle state. */\nexport interface DurableWorkspaceKeyStore {\n /** Return the active row for this exact product scope. */\n getActive(scope: DurableWorkspaceKeyScope): Promise<DurableWorkspaceKeyRecord | null>\n /** Return every unfinished provisioning row for this exact product scope. */\n listProvisioning(scope: DurableWorkspaceKeyScope): Promise<DurableWorkspaceKeyProvisioningRecord[]>\n /** Insert before the remote create so a crashed create can be recovered. */\n insertProvisioning(record: DurableWorkspaceKeyProvisioningRecord): Promise<void>\n /** Save the remote id while the row remains in provisioning state. */\n markProvisioningRemote(input: { id: string; keyId: string }): Promise<void>\n /** Promote a fully encrypted row to active state. */\n markActive(input: {\n id: string\n keyId: string\n keyEncrypted: string\n expiresAt: Date\n budgetUsd: number\n }): Promise<void>\n /**\n * Optional fenced writes. The manager uses false to compensate a stale\n * creator. Stores without this field retain the pre-fence behavior.\n */\n conditionalWrites?: DurableWorkspaceKeyConditionalWrites\n /** Keep a failed cleanup visible and schedule a later retry. Terminal rows are immutable. */\n markRevocationPending(input: {\n id: string\n error?: string | null\n nextAttemptAt: Date\n incrementAttempts: boolean\n }): Promise<void>\n /** Mark a remote key as revoked. Missing remote keys count as revoked. */\n markRevoked(id: string, now: Date): Promise<void>\n /** Mark a provisioning row terminal when no remote key remains to clean. */\n markOrphaned(id: string, error: string): Promise<void>\n /** Query due cleanup rows. The implementation should filter by the supplied scope. */\n listPendingRevocations(input: {\n product: WorkspaceKeyProduct\n workspaceId?: string\n ownerUserId?: string\n now: Date\n limit: number\n /** Include rows scheduled for a later retry when checking before issuance. */\n includeFuture?: boolean\n }): Promise<DurableWorkspaceKeyRecord[]>\n /** Acquire a cross-process lease for one product/workspace/owner scope. */\n acquireLease(scope: string, operationId: string, now: Date, leaseMs: number): Promise<boolean>\n /** Renew an acquired lease before its expiry. */\n renewLease(scope: string, operationId: string, now: Date, leaseMs: number): Promise<boolean>\n /** Release an acquired lease. */\n releaseLease(scope: string, operationId: string): Promise<void>\n}\n\n/** Live budget information for a child key. */\nexport interface WorkspaceKeyUsage {\n keyId: string\n budgetUsd: number\n budgetSpent: number\n budgetRemaining: number\n expiresAt: string\n exhausted: boolean\n}\n\n/** The decrypted key plus the usage snapshot used to issue it. */\nexport interface WorkspaceRuntimeKey {\n key: string\n usage: WorkspaceKeyUsage\n /** True when this call minted a new remote key. */\n refreshed: boolean\n}\n\n/** Identity-bound durable key manager API. */\nexport interface DurableWorkspaceKeyManager {\n /** Reuse a matching active key or reconcile and mint one under a lease. */\n ensureKey(identity: WorkspaceKeyIdentity, options?: { budgetUsd?: number }): Promise<WorkspaceRuntimeKey>\n /** Read usage without returning the child secret. */\n getUsage(identity: WorkspaceKeyIdentity): Promise<WorkspaceKeyUsage | null>\n /**\n * Retry due cleanup rows. A supplied owner/workspace limits the retry to its\n * scope. Empty provisioning rows also require the full identity so a retry\n * can use the original source binding safely.\n */\n retryPendingRevocations(\n scope?: Pick<WorkspaceKeyIdentity, 'ownerUserId' | 'workspaceId'>,\n identity?: WorkspaceKeyIdentity,\n ): Promise<number>\n}\n\n/** Configuration for {@link createIdentityBoundWorkspaceKeyManager}. */\nexport interface DurableWorkspaceKeyManagerOptions {\n store: DurableWorkspaceKeyStore\n provisioner: DurableWorkspaceKeyProvisioner\n /**\n * Control-plane client for historical get/revoke/list operations. Use this\n * when the source credential can rotate or disappear. It never mints keys.\n */\n recoveryProvisioner?: Pick<DurableWorkspaceKeyProvisioner, 'getKey' | 'revokeKey' | 'findCreatedKeys'>\n crypto: KeyCrypto\n /** Product partition. Products must use separate values. */\n product: WorkspaceKeyProduct\n defaultBudgetUsd: number\n now?: () => Date\n /** Local lifetime used when the remote response omits an expiry. */\n keyLifetimeMs?: number\n /**\n * Least remaining life a reused key needs: the app's longest turn plus a margin, shorter than `keyLifetimeMs`. Below\n * it a fresh key is minted and the old one retired at its own expiry, never revoked under a turn that holds it.\n */\n minRemainingLifetimeMs?: number\n /** Lease lifetime for remote operations. */\n leaseMs?: number\n /** Maximum time to wait for another issuer to release the scope lease. */\n leaseWaitMs?: number\n /** Poll delay while waiting for a scope lease. */\n leasePollMs?: number\n /** Renewal interval. It must be shorter than `leaseMs`. */\n leaseRenewIntervalMs?: number\n /** Initial delay for a failed remote revoke. */\n revocationRetryBaseMs?: number\n /** Maximum delay for a failed remote revoke. */\n revocationRetryMaxMs?: number\n /** Remote name; the mint's operation id is appended when absent, as a create under a held name revokes its key. */\n nameForIdentity?: (identity: WorkspaceKeyIdentity, operationId: string) => string\n /** Resolve names for rows written before a mint stored its name. Null blocks issuance safely. */\n legacyNameForRecord?: (record: DurableWorkspaceKeyRecord) => string | null | undefined\n /** Recognize a missing remote key without depending on a provider SDK. */\n isRemoteMissing?: (error: unknown) => boolean\n}\n\nconst DEFAULT_KEY_LIFETIME_MS = 55 * 60_000\n/** Default reuse floor: a 15 min turn plus a 5 min margin; this package sets no turn limit, so longer turns pass their own. */\nexport const DEFAULT_MIN_REMAINING_KEY_LIFETIME_MS = 20 * 60_000\nconst DEFAULT_LEASE_MS = 60_000\nconst DEFAULT_LEASE_WAIT_MS = 15_000\nconst DEFAULT_LEASE_POLL_MS = 50\nconst DEFAULT_LEASE_RENEW_INTERVAL_MS = Math.floor(DEFAULT_LEASE_MS / 3)\nconst DEFAULT_REVOCATION_RETRY_BASE_MS = 2_000\nconst DEFAULT_REVOCATION_RETRY_MAX_MS = 60_000\nconst PENDING_REVOCATION_BATCH_SIZE = 20\n// Covers clock skew between this host and the platform that enforces the child's expiry.\nconst ORPHAN_AFTER_EXPIRY_GRACE_MS = 5 * 60_000\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction operationId(): string {\n return globalThis.crypto.randomUUID()\n}\n\nfunction requirePositive(value: number, label: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new Error(`${label} must be a positive finite number`)\n return value\n}\n\nfunction requireNonNegative(value: number, label: string): number {\n if (!Number.isFinite(value) || value < 0) throw new Error(`${label} must be a non-negative finite number`)\n return value\n}\n\nfunction normalizeIdentity(identity: WorkspaceKeyIdentity): WorkspaceKeyIdentity {\n const workspaceId = identity.workspaceId.trim()\n const ownerUserId = identity.ownerUserId.trim()\n const platformUserId = identity.platformUserId.trim()\n const sourceKeyFingerprint = identity.sourceKeyFingerprint.trim()\n const sourceKeyId = identity.sourceKeyId?.trim() || null\n if (!workspaceId || !ownerUserId || !platformUserId || !sourceKeyFingerprint) {\n throw new Error('workspace child key identity is incomplete')\n }\n return { workspaceId, ownerUserId, platformUserId, sourceKeyId, sourceKeyFingerprint }\n}\n\nfunction scopeFor(identity: Pick<WorkspaceKeyIdentity, 'workspaceId' | 'ownerUserId'>, product: string): DurableWorkspaceKeyScope {\n return { workspaceId: identity.workspaceId, ownerUserId: identity.ownerUserId, product }\n}\n\nfunction scopeKey(scope: DurableWorkspaceKeyScope): string {\n return JSON.stringify([scope.product, scope.workspaceId, scope.ownerUserId])\n}\n\nfunction safeNamePart(value: string): string {\n const normalized = value.replace(/[^A-Za-z0-9._-]/g, '-').replace(/-+/g, '-')\n return normalized.slice(0, 80) || 'unknown'\n}\n\nfunction defaultKeyName(identity: WorkspaceKeyIdentity, product: string, operationId: string): string {\n return `agent-app:${safeNamePart(product)}:${safeNamePart(identity.workspaceId)}:${safeNamePart(identity.platformUserId)}:${operationId}`\n}\n\nfunction sourceKeyId(identity: WorkspaceKeyIdentity): string | null {\n return identity.sourceKeyId?.trim() || null\n}\n\nfunction sameIdentity(row: DurableWorkspaceKeyRecord, identity: WorkspaceKeyIdentity, product: string): boolean {\n return row.workspaceId === identity.workspaceId\n && row.ownerUserId === identity.ownerUserId\n && row.product === product\n && row.platformUserId === identity.platformUserId\n && row.sourceKeyId === sourceKeyId(identity)\n && row.sourceKeyFingerprint === identity.sourceKeyFingerprint\n}\n\n/**\n * Whether an ACTIVE child may be reused: it belongs to its workspace, owner, product and Platform user, not to the\n * source credential that minted it. Every sign-in presents a new source credential (sourceKeyId, sourceKeyFingerprint),\n * so matching on it made the same member's second sign-in revoke the child a running turn held. The payer cannot\n * differ for one Platform user: delegation refuses a child not paid by that user (`platform/delegated-keys.ts`:\n * non-user payer and payer id checks). A revoked source takes its children with it: their read-back is a definite\n * gone verdict. Cleanup goes through the row's own slot (`slotOf`). Recovery of a half-provisioned row still needs the\n * exact minting source (`sameIdentity`).\n */\nfunction sameOwner(row: DurableWorkspaceKeyRecord, owner: Pick<DurableWorkspaceKeyRecord, 'workspaceId' | 'ownerUserId' | 'platformUserId'>,\n product: string): boolean {\n return row.workspaceId === owner.workspaceId\n && row.ownerUserId === owner.ownerUserId\n && row.product === product\n && row.platformUserId === owner.platformUserId\n}\n\n/** The slot a child was minted in, for the provisioner's revoke. Never the secret. */\nfunction slotOf(row: DurableWorkspaceKeyRecord): Pick<DurableWorkspaceKeyRecord, 'name' | 'sourceKeyId' | 'platformUserId'> {\n return { name: row.name, sourceKeyId: row.sourceKeyId, platformUserId: row.platformUserId }\n}\n\n/**\n * A refused cleanup of a live child waits for the child's own expiry and blocks no issuance meanwhile. Only that\n * deferral schedules the row AT the expiry (`settleFailedRevoke`); a transient retry that lands at or past it still\n * blocks, so a second child never mints while the first is live.\n */\nfunction waitsForExpiry(row: DurableWorkspaceKeyRecord): boolean {\n return row.nextRevocationAt !== null && row.nextRevocationAt.getTime() === row.expiresAt.getTime()\n}\n\nfunction errorMessage(error: unknown, fallback: string): string {\n return (error instanceof Error ? error.message : fallback)\n .replace(/Bearer\\s+[^\\s,;]+/gi, 'Bearer [redacted]')\n .replace(/((?:authorization|api[-_ ]?key|token|secret|password)\\s*[:=]\\s*)(?!Bearer\\b)[^\\s,;]+/gi, '$1[redacted]')\n .slice(0, 240)\n}\n\nfunction isProvisioningId(value: string): boolean {\n return value.startsWith('provisioning:')\n}\n\n/**\n * The name a mint writes into its placeholder id (`provisioning:<operation>:<name>`) before the remote create, so\n * recovery finds a half-created child by that name even in a store with no name column. Older placeholders carry none.\n */\nfunction placeholderName(keyId: string): string | undefined {\n return isProvisioningId(keyId) ? keyId.split(':').slice(2).join(':').trim() || undefined : undefined\n}\n\nasync function markProvisioningRemote(store: DurableWorkspaceKeyStore, input: { id: string; keyId: string }): Promise<boolean> {\n if (store.conditionalWrites) return store.conditionalWrites.markProvisioningRemote(input)\n await store.markProvisioningRemote(input)\n return true\n}\n\nasync function markActive(store: DurableWorkspaceKeyStore, input: Parameters<DurableWorkspaceKeyStore['markActive']>[0]): Promise<boolean> {\n if (store.conditionalWrites) return store.conditionalWrites.markActive(input)\n await store.markActive(input)\n return true\n}\n\nfunction usageFromRemote(\n row: DurableWorkspaceKeyRecord,\n remote: Awaited<ReturnType<DurableWorkspaceKeyProvisioner['getKey']>>,\n now: Date,\n): WorkspaceKeyUsage {\n const budgetUsd = remote.budgetUsd ?? row.budgetUsd\n const budgetSpent = remote.budgetSpent ?? 0\n if (!Number.isFinite(budgetUsd) || budgetUsd < 0) throw new Error('workspace child key budget is malformed')\n if (!Number.isFinite(budgetSpent) || budgetSpent < 0) throw new Error('workspace child key usage is malformed')\n const expiresAt = remote.expiresAt ?? row.expiresAt.toISOString()\n const expiryMs = Date.parse(expiresAt)\n if (!Number.isFinite(expiryMs)) throw new Error('workspace child key expiry is malformed')\n const budgetRemaining = Math.max(0, budgetUsd - budgetSpent)\n return {\n keyId: row.keyId,\n budgetUsd,\n budgetSpent,\n budgetRemaining,\n expiresAt,\n exhausted: budgetRemaining <= 0 || expiryMs <= now.getTime(),\n }\n}\n\nfunction defaultRemoteMissing(error: unknown): boolean {\n const value = error as { status?: unknown; code?: unknown } | null\n return value?.status === 404 || value?.code === 'not_found'\n}\n\n/** `<status> <code>` for a typed refusal Platform decided (a 4xx other than 408 and 429): a retry gets the same answer. */\nfunction definiteRefusal(error: unknown): string | null {\n const refusal = (error as { refusal?: { status?: unknown; code?: unknown; platformCode?: unknown } } | null)?.refusal\n const status = refusal?.status\n if (typeof status !== 'number' || status < 400 || status > 499 || status === 408 || status === 429) return null\n return `${status} ${String(refusal?.platformCode ?? refusal?.code ?? 'refused')}`\n}\n\n/**\n * Create a product-neutral manager for child-key issuance and cleanup.\n *\n * The provisioner must already be authenticated for the current source\n * credential. The manager persists the source id and its non-secret\n * fingerprint with each row, reuses an active row for the same workspace,\n * owner, product and Platform user, and cleans each row through its own slot.\n */\nexport function createIdentityBoundWorkspaceKeyManager(\n options: DurableWorkspaceKeyManagerOptions,\n): DurableWorkspaceKeyManager {\n const product = options.product.trim()\n if (!product) throw new Error('workspace child key product is required')\n const defaultBudgetUsd = requirePositive(options.defaultBudgetUsd, 'defaultBudgetUsd')\n const keyLifetimeMs = requirePositive(options.keyLifetimeMs ?? DEFAULT_KEY_LIFETIME_MS, 'keyLifetimeMs')\n const minRemainingLifetimeMs = requireNonNegative(\n options.minRemainingLifetimeMs ?? Math.min(DEFAULT_MIN_REMAINING_KEY_LIFETIME_MS, Math.floor(keyLifetimeMs / 2)),\n 'minRemainingLifetimeMs',\n )\n if (minRemainingLifetimeMs >= keyLifetimeMs) throw new Error('minRemainingLifetimeMs must be shorter than keyLifetimeMs')\n const leaseMs = requirePositive(options.leaseMs ?? DEFAULT_LEASE_MS, 'leaseMs')\n const leaseWaitMs = requireNonNegative(options.leaseWaitMs ?? DEFAULT_LEASE_WAIT_MS, 'leaseWaitMs')\n const leasePollMs = requirePositive(options.leasePollMs ?? DEFAULT_LEASE_POLL_MS, 'leasePollMs')\n const leaseRenewIntervalMs = requirePositive(\n options.leaseRenewIntervalMs ?? Math.min(DEFAULT_LEASE_RENEW_INTERVAL_MS, Math.floor(leaseMs / 3)),\n 'leaseRenewIntervalMs',\n )\n if (leaseRenewIntervalMs >= leaseMs) throw new Error('leaseRenewIntervalMs must be shorter than leaseMs')\n const revocationRetryBaseMs = requirePositive(\n options.revocationRetryBaseMs ?? DEFAULT_REVOCATION_RETRY_BASE_MS,\n 'revocationRetryBaseMs',\n )\n const revocationRetryMaxMs = requirePositive(\n options.revocationRetryMaxMs ?? DEFAULT_REVOCATION_RETRY_MAX_MS,\n 'revocationRetryMaxMs',\n )\n if (revocationRetryMaxMs < revocationRetryBaseMs) throw new Error('revocationRetryMaxMs must cover the base delay')\n\n const now = options.now ?? (() => new Date())\n const isRemoteMissing = options.isRemoteMissing ?? defaultRemoteMissing\n const recoveryProvisioner = options.recoveryProvisioner ?? options.provisioner\n const { withLocalLock, withDurableLease } = createWorkspaceKeyLocks(leaseWaitMs, options, now, leaseMs, leasePollMs, leaseRenewIntervalMs, operationId, sleep)\n\n const { revokePending, markPending, cleanupProvisioning, reconcileProvisioning } = createWorkspaceKeyRecovery(revocationRetryMaxMs, revocationRetryBaseMs, options, now, recoveryProvisioner, isRemoteMissing, product)\n\n async function retryPendingRevocationsUnlocked(\n scopeFilter?: Pick<WorkspaceKeyIdentity, 'ownerUserId' | 'workspaceId'>,\n activeIdentity?: WorkspaceKeyIdentity,\n ): Promise<{ completed: number; pending: number }> {\n const rows = await options.store.listPendingRevocations({\n product,\n workspaceId: scopeFilter?.workspaceId,\n ownerUserId: scopeFilter?.ownerUserId,\n now: now(),\n limit: PENDING_REVOCATION_BATCH_SIZE,\n })\n let completed = 0\n let pending = 0\n for (const row of rows) {\n if (row.product !== product) continue\n if (scopeFilter && (row.workspaceId !== scopeFilter.workspaceId || row.ownerUserId !== scopeFilter.ownerUserId)) continue\n if (await revokePending(row, activeIdentity)) completed += 1\n else pending += 1\n }\n return { completed, pending }\n }\n\n async function assertNoPendingRevocations(identity: WorkspaceKeyIdentity): Promise<void> {\n const rows = await options.store.listPendingRevocations({\n product,\n workspaceId: identity.workspaceId,\n ownerUserId: identity.ownerUserId,\n now: now(),\n limit: PENDING_REVOCATION_BATCH_SIZE,\n includeFuture: true,\n })\n if (rows.some((row) => row.product === product\n && row.workspaceId === identity.workspaceId\n && row.ownerUserId === identity.ownerUserId && !waitsForExpiry(row))) {\n throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n }\n }\n\n async function retryPendingRevocations(\n scopeInput?: Pick<WorkspaceKeyIdentity, 'ownerUserId' | 'workspaceId'>,\n identityInput?: WorkspaceKeyIdentity,\n ): Promise<number> {\n const identity = identityInput ? normalizeIdentity(identityInput) : undefined\n if (identity && scopeInput\n && (identity.workspaceId !== scopeInput.workspaceId || identity.ownerUserId !== scopeInput.ownerUserId)) {\n throw new Error('workspace child key retry identity does not match its scope')\n }\n if (scopeInput) {\n const workspaceId = scopeInput.workspaceId.trim()\n const ownerUserId = scopeInput.ownerUserId.trim()\n if (!workspaceId || !ownerUserId) throw new Error('workspace child key retry scope is incomplete')\n const scope = scopeKey({ workspaceId, ownerUserId, product })\n return withLocalLock(scope, () => withDurableLease(scope, async () => (\n await retryPendingRevocationsUnlocked({ workspaceId, ownerUserId }, identity)).completed))\n }\n\n if (identity) {\n const scope = scopeKey(scopeFor(identity, product))\n return withLocalLock(scope, () => withDurableLease(scope, async () => (\n await retryPendingRevocationsUnlocked({ workspaceId: identity.workspaceId, ownerUserId: identity.ownerUserId }, identity)).completed))\n }\n\n const rows = await options.store.listPendingRevocations({ product, now: now(), limit: PENDING_REVOCATION_BATCH_SIZE })\n let completed = 0\n const scopes = new Set<string>()\n for (const row of rows) {\n if (row.product !== product) continue\n const scope = scopeKey({ workspaceId: row.workspaceId, ownerUserId: row.ownerUserId, product })\n if (scopes.has(scope)) continue\n scopes.add(scope)\n completed += await withLocalLock(scope, () => withDurableLease(scope, async () => (await retryPendingRevocationsUnlocked({\n workspaceId: row.workspaceId,\n ownerUserId: row.ownerUserId,\n })).completed))\n }\n return completed\n }\n\n async function readActive(identity: WorkspaceKeyIdentity): Promise<{ row: DurableWorkspaceKeyRecord; usage: WorkspaceKeyUsage } | null> {\n const row = await options.store.getActive(scopeFor(identity, product))\n if (!row) return null\n if (!sameOwner(row, identity, product)) {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'active child key belongs to another workspace owner or Platform user',\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n return null\n }\n\n let remote: Awaited<ReturnType<DurableWorkspaceKeyProvisioner['getKey']>>\n try {\n remote = await recoveryProvisioner.getKey(row.keyId)\n } catch (error) {\n if (isRemoteMissing(error)) {\n await options.store.markRevoked(row.id, now())\n return null\n }\n throw error\n }\n const usage = usageFromRemote(row, remote, now())\n if (usage.exhausted) {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'active child key is expired or exhausted',\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n return null\n }\n return { row, usage }\n }\n\n const { mint } = createWorkspaceKeyMinter(options, now, keyLifetimeMs, product, markPending, cleanupProvisioning, revokePending)\n\n async function ensureKey(identityInput: WorkspaceKeyIdentity, keyOptions?: { budgetUsd?: number }): Promise<WorkspaceRuntimeKey> {\n const identity = normalizeIdentity(identityInput)\n const budgetUsd = keyOptions?.budgetUsd ?? defaultBudgetUsd\n requirePositive(budgetUsd, 'budgetUsd')\n const scope = scopeKey(scopeFor(identity, product))\n let mintedRemote: { row: DurableWorkspaceKeyProvisioningRecord; remoteId: string } | null = null\n return withLocalLock(scope, () => withDurableLease(scope, async () => {\n const initialCleanup = await retryPendingRevocationsUnlocked(identity, identity)\n if (initialCleanup.pending > 0) throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n await reconcileProvisioning(identity)\n const active = await readActive(identity)\n if (active) {\n const key = await options.crypto.decrypt(active.row.keyEncrypted)\n if (!key.trim()) throw new Error('workspace child key secret is empty')\n // Checked after the awaited decrypt: a key handed out must outlive the turn that takes it.\n const remainingMs = Date.parse(active.usage.expiresAt) - now().getTime()\n if (remainingMs > 0 && remainingMs >= minRemainingLifetimeMs) return { key, usage: active.usage, refreshed: false }\n // A running turn may hold a key below the floor: retire it at its expiry (`waitsForExpiry`), never revoke it.\n await options.store.markRevocationPending({\n id: active.row.id,\n error: remainingMs > 0 ? 'active child key is below the reuse floor; it is retired at its expiry'\n : 'active child key expired while it was read',\n nextAttemptAt: remainingMs > 0 ? active.row.expiresAt : now(),\n incrementAttempts: false,\n })\n }\n const finalCleanup = await retryPendingRevocationsUnlocked(identity, identity)\n if (finalCleanup.pending > 0) throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n await assertNoPendingRevocations(identity)\n return mint(identity, budgetUsd, (row, remoteId) => {\n mintedRemote = { row, remoteId }\n })\n }, async () => {\n const remote = mintedRemote\n if (!remote) return\n const cleaned = await revokePending({\n ...remote.row,\n keyId: remote.remoteId,\n status: 'revocation_pending',\n }, identity)\n if (!cleaned) throw new Error('lease-loss child-key cleanup is pending')\n }))\n }\n\n async function getUsage(identityInput: WorkspaceKeyIdentity): Promise<WorkspaceKeyUsage | null> {\n const identity = normalizeIdentity(identityInput)\n const scope = scopeKey(scopeFor(identity, product))\n return withLocalLock(scope, () => withDurableLease(scope, async () => {\n const active = await readActive(identity)\n return active?.usage ?? null\n }))\n }\n\n return { ensureKey, getUsage, retryPendingRevocations }\n}\n\nfunction createWorkspaceKeyRecovery(\n revocationRetryMaxMs: ReturnType<typeof requirePositive>,\n revocationRetryBaseMs: ReturnType<typeof requirePositive>,\n options: DurableWorkspaceKeyManagerOptions,\n now: () => Date,\n recoveryProvisioner: Pick<DurableWorkspaceKeyProvisioner, \"getKey\" | \"revokeKey\" | \"findCreatedKeys\">,\n isRemoteMissing: (error: unknown) => boolean,\n product: string,\n) {\n function retryDelay(attempts: number): number {\n return Math.min(revocationRetryMaxMs, revocationRetryBaseMs * 2 ** Math.min(Math.max(attempts - 1, 0), 5))\n }\n\n async function markPending(id: string, error: unknown, incrementAttempts: boolean): Promise<void> {\n const delay = incrementAttempts ? retryDelay(1) : 0\n await options.store.markRevocationPending({\n id,\n error: errorMessage(error, 'remote key cleanup failed'),\n nextAttemptAt: new Date(now().getTime() + delay),\n incrementAttempts,\n })\n }\n\n /**\n * A refusal to revoke never blocks the scope. Missing is gone. After a definite refusal the child's own verdict\n * decides: past its expiry, or unable to authenticate or spend, it is gone; live or refused for now, it is retired\n * at its expiry. Null keeps today's retry: a transient failure, or a verdict read that failed transiently.\n */\n async function settleFailedRevoke(row: DurableWorkspaceKeyRecord, keyId: string, error: unknown): Promise<'gone' | 'waits' | null> {\n // An expired child can neither authenticate nor spend, whatever answered: it never holds the scope.\n if (isRemoteMissing(error) || now().getTime() >= row.expiresAt.getTime()) return 'gone'\n const refused = definiteRefusal(error)\n if (!refused) return null\n try {\n if (usageFromRemote(row, await recoveryProvisioner.getKey(keyId), now()).exhausted) return 'gone'\n } catch (readError) {\n if (isRemoteMissing(readError)) return 'gone'\n if (!definiteRefusal(readError)) return null\n }\n await options.store.markRevocationPending({\n id: row.id,\n error: errorMessage(new Error(`cleanup refused (${refused}); the child is retired at its expiry`), 'cleanup refused'),\n nextAttemptAt: row.expiresAt,\n incrementAttempts: true,\n })\n return 'waits'\n }\n\n async function revokePending(row: DurableWorkspaceKeyRecord, identity?: WorkspaceKeyIdentity): Promise<boolean> {\n if (!row.keyId || isProvisioningId(row.keyId)) return cleanupProvisioning(row, identity)\n const active = await options.store.getActive({\n workspaceId: row.workspaceId,\n ownerUserId: row.ownerUserId,\n product: row.product,\n })\n if (active && active.id !== row.id && active.keyId === row.keyId) {\n await options.store.markRevoked(row.id, now())\n return true\n }\n try {\n await recoveryProvisioner.revokeKey(row.keyId, slotOf(row))\n await options.store.markRevoked(row.id, now())\n return true\n } catch (error) {\n const settled = await settleFailedRevoke(row, row.keyId, error)\n if (settled === 'gone') await options.store.markRevoked(row.id, now())\n if (settled) return true\n await options.store.markRevocationPending({\n id: row.id,\n error: errorMessage(error, 'remote key revocation failed'),\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return false\n }\n }\n\n async function provisioningCandidates(row: DurableWorkspaceKeyRecord): Promise<{\n name: string\n candidates: Array<{ id: string }>\n } | null> {\n if (row.keyId && !isProvisioningId(row.keyId)) {\n return { name: row.name?.trim() ?? '', candidates: [{ id: row.keyId }] }\n }\n const name = row.name?.trim() || placeholderName(row.keyId) || options.legacyNameForRecord?.(row)?.trim()\n if (!name) return null\n return {\n name,\n candidates: await recoveryProvisioner.findCreatedKeys({\n name,\n product: row.product,\n sourceKeyId: row.sourceKeyId,\n }),\n }\n }\n\n async function probeProvisioning(\n row: DurableWorkspaceKeyRecord,\n identity: WorkspaceKeyIdentity | undefined,\n name: string,\n ): Promise<Array<{ id: string }> | null> {\n const idempotencyKey = row.idempotencyKey?.trim()\n if (!identity || !sameIdentity(row, identity, product)\n || !options.provisioner.supportsIdempotentCreate || !idempotencyKey) return []\n try {\n const created = await options.provisioner.createKey({\n name,\n product: row.product,\n budgetUsd: row.budgetUsd,\n expiresAt: row.expiresAt.toISOString(),\n idempotencyKey,\n })\n const remoteId = created.id?.trim()\n if (remoteId) return [{ id: remoteId }]\n } catch (error) {\n await options.store.markRevocationPending({\n id: row.id,\n error: errorMessage(error, 'remote provisioning recovery failed'),\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return null\n }\n return (await provisioningCandidates({ ...row, name, keyId: `provisioning:${idempotencyKey}` }))?.candidates ?? []\n }\n\n async function cleanupProvisioning(row: DurableWorkspaceKeyRecord, identity?: WorkspaceKeyIdentity): Promise<boolean> {\n const resolved = await provisioningCandidates(row)\n if (!resolved) {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'provisioning row has no recoverable remote name; migrate the row or configure legacyNameForRecord',\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n return false\n }\n let { name, candidates } = resolved\n if (candidates.length === 0) {\n const probed = await probeProvisioning(row, identity, name)\n if (probed === null) return false\n candidates = probed\n }\n\n const scope = { workspaceId: row.workspaceId, ownerUserId: row.ownerUserId, product: row.product }\n const active = await options.store.getActive(scope)\n const activeMatches = active && sameOwner(active, identity ?? row, product)\n const activeKeyId = activeMatches ? active.keyId : null\n const toRevoke = candidates\n .map((candidate) => candidate.id.trim())\n .filter((candidateId) => candidateId && candidateId !== activeKeyId)\n\n for (const keyId of toRevoke) {\n try {\n await recoveryProvisioner.revokeKey(keyId, slotOf({ ...row, name: name || row.name }))\n } catch (error) {\n const settled = await settleFailedRevoke(row, keyId, error)\n if (settled === 'gone') continue\n if (settled) return true\n await options.store.markRevocationPending({\n id: row.id,\n error: errorMessage(error, 'remote provisioning cleanup failed'),\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return false\n }\n }\n\n if (candidates.length > 0) {\n await options.store.markRevoked(row.id, now())\n } else if (now().getTime() >= row.expiresAt.getTime() + ORPHAN_AFTER_EXPIRY_GRACE_MS) {\n // An empty lookup cannot prove no child exists, but any child this row's create made\n // carries this expiry and can no longer spend; retrying forever would block issuance.\n await options.store.markOrphaned(row.id, 'no remote child matched the durable provisioning record before its expiry')\n } else {\n await options.store.markRevocationPending({\n id: row.id,\n error: 'no remote child matched the durable provisioning record; retrying crash recovery',\n nextAttemptAt: new Date(now().getTime() + retryDelay(row.revocationAttempts + 1)),\n incrementAttempts: true,\n })\n return false\n }\n return true\n }\n\n async function reconcileProvisioning(identity: WorkspaceKeyIdentity): Promise<void> {\n const scope = scopeFor(identity, product)\n const rows = await options.store.listProvisioning(scope)\n for (const row of rows) {\n if (!(await cleanupProvisioning(row, identity))) {\n throw new Error('a previous workspace child-key cleanup is pending; issuance is blocked until it completes')\n }\n }\n }\n return { revokePending, markPending, cleanupProvisioning, reconcileProvisioning }\n}\n\nfunction createWorkspaceKeyMinter(\n options: DurableWorkspaceKeyManagerOptions,\n now: () => Date,\n keyLifetimeMs: ReturnType<typeof requirePositive>,\n product: string,\n markPending: ReturnType<typeof createWorkspaceKeyRecovery>['markPending'],\n cleanupProvisioning: ReturnType<typeof createWorkspaceKeyRecovery>['cleanupProvisioning'],\n revokePending: ReturnType<typeof createWorkspaceKeyRecovery>['revokePending'],\n) {\n async function mint(\n identity: WorkspaceKeyIdentity,\n budgetUsd: number,\n onRemoteKey?: (row: DurableWorkspaceKeyProvisioningRecord, remoteId: string) => void,\n ): Promise<WorkspaceRuntimeKey> {\n await assertWorkspaceKeyCryptoUsable(options.crypto)\n const mintOperationId = operationId()\n const createdAt = now()\n const expiresAt = new Date(createdAt.getTime() + keyLifetimeMs)\n const named = (options.nameForIdentity?.(identity, mintOperationId) ?? defaultKeyName(identity, product, mintOperationId)).trim()\n if (!named) throw new Error('workspace child key remote name is required')\n const name = named.includes(mintOperationId) ? named : `${named}:${mintOperationId}`\n const rowId = operationId()\n const idempotencyKey = `workspace-key:${rowId}`\n const provisioningRow: DurableWorkspaceKeyProvisioningRecord = {\n id: rowId,\n workspaceId: identity.workspaceId,\n ownerUserId: identity.ownerUserId,\n product,\n platformUserId: identity.platformUserId,\n sourceKeyId: sourceKeyId(identity),\n sourceKeyFingerprint: identity.sourceKeyFingerprint,\n name,\n idempotencyKey,\n keyId: `provisioning:${mintOperationId}:${name}`,\n keyEncrypted: '',\n budgetUsd,\n expiresAt,\n status: 'provisioning',\n revocationAttempts: 0,\n nextRevocationAt: null,\n lastRevocationError: null,\n createdAt,\n }\n await options.store.insertProvisioning(provisioningRow)\n\n let created: Awaited<ReturnType<DurableWorkspaceKeyProvisioner['createKey']>>\n try {\n created = await options.provisioner.createKey({\n name,\n product,\n budgetUsd,\n expiresAt: expiresAt.toISOString(),\n idempotencyKey,\n })\n } catch (error) {\n // Keep cleanup running even when the state write fails. The remote\n // request may have committed before its response failed.\n try {\n await markPending(rowId, error, false)\n } catch {\n // cleanupProvisioning below can still find the remote name.\n }\n try {\n await cleanupProvisioning({ ...provisioningRow, status: 'revocation_pending' }, identity)\n } catch (cleanupError) {\n throw new Error('remote create failed and its cleanup could not be completed', { cause: cleanupError })\n }\n throw error\n }\n\n const remoteId = created.id?.trim() ?? ''\n const secret = created.key?.trim() ?? ''\n if (!remoteId || !secret) {\n if (remoteId) {\n try {\n await markProvisioningRemote(options.store, { id: rowId, keyId: remoteId })\n } catch {\n // revokePending uses the returned id even when this state write fails.\n }\n }\n try {\n await markPending(rowId, new Error('remote create returned no usable child key'), false)\n } catch {\n // Always attempt remote cleanup below.\n }\n const pendingRow = { ...provisioningRow, keyId: remoteId || provisioningRow.keyId, status: 'revocation_pending' as const }\n await revokePending(pendingRow, identity)\n throw new Error('remote create returned no usable child key')\n }\n\n let cleanupRow = provisioningRow\n onRemoteKey?.(cleanupRow, remoteId)\n\n async function retainRetiredCreatorCleanup(): Promise<void> {\n // A retired row cannot hold another pending transition. Persist the\n // returned child separately before revocation so a failed revoke survives restart.\n const retainedRow = { ...provisioningRow, id: operationId(), keyId: remoteId }\n try {\n await options.store.insertProvisioning(retainedRow)\n } catch (cause) {\n throw new Error('returned child cleanup record could not be persisted', { cause })\n }\n cleanupRow = retainedRow\n onRemoteKey?.(cleanupRow, remoteId)\n }\n\n try {\n const recorded = await markProvisioningRemote(options.store, { id: rowId, keyId: remoteId })\n if (!recorded) {\n await retainRetiredCreatorCleanup()\n throw new Error('workspace child-key provisioning row was retired before the remote id was recorded')\n }\n const keyEncrypted = await options.crypto.encrypt(secret)\n const remoteExpiresAt = created.expiresAt?.trim()\n const activeExpiresAt = remoteExpiresAt ? new Date(remoteExpiresAt) : expiresAt\n if (!Number.isFinite(activeExpiresAt.getTime())) throw new Error('remote child key expiry is malformed')\n const activeBudgetUsd = created.budgetUsd ?? budgetUsd\n if (!Number.isFinite(activeBudgetUsd) || activeBudgetUsd < 0) throw new Error('remote child key budget is malformed')\n const activated = await markActive(options.store, {\n id: rowId,\n keyId: remoteId,\n keyEncrypted,\n expiresAt: activeExpiresAt,\n budgetUsd: activeBudgetUsd,\n })\n if (!activated) {\n await retainRetiredCreatorCleanup()\n throw new Error('workspace child-key provisioning row was retired before activation')\n }\n } catch (error) {\n // A persistence failure must not strand the already-created remote key.\n try {\n await markPending(cleanupRow.id, error, false)\n } catch {\n // revokePending below still has the remote id and attempts cleanup.\n }\n await revokePending({ ...cleanupRow, keyId: remoteId, status: 'revocation_pending' }, identity)\n throw error\n }\n\n const row = await options.store.getActive(scopeFor(identity, product))\n if (!row || row.keyId !== remoteId || !sameIdentity(row, identity, product)) {\n const error = new Error('workspace child key was not persisted as active')\n try {\n await options.store.markRevocationPending({\n id: rowId,\n error: error.message,\n nextAttemptAt: now(),\n incrementAttempts: false,\n })\n } catch {\n // The remote id is still available for the cleanup attempt below.\n }\n await revokePending({ ...provisioningRow, keyId: remoteId, status: 'revocation_pending' }, identity)\n throw error\n }\n const usage = usageFromRemote(row, {\n budgetUsd: created.budgetUsd,\n budgetSpent: 0,\n expiresAt: created.expiresAt ?? expiresAt.toISOString(),\n }, now())\n return { key: secret, usage, refreshed: true }\n }\n return { mint }\n}\n","import { assertWorkspaceKeyCryptoUsable } from './crypto-probe'\n\n/**\n * Per-workspace budget-capped model keys — app-owned billing, metered on Tangle.\n *\n * Each workspace (the paying entity) runs the agent on its OWN child API key\n * minted from the platform parent key. The child carries a hard USD budget the\n * Tangle Router enforces AT THE KEY — model spend can't exceed the allowance,\n * zero app-side accounting. The app charges its own subscription (e.g. 5× the\n * allowance) and re-provisions each period. Child budgets are IMMUTABLE on the\n * platform, so a new budget = a fresh key + revoke the prior (rotate).\n *\n * The mint / rotate / rollover / usage LOGIC is generic and lives here.\n * Persistence (which D1 table), secret encryption, and key provisioning are\n * SEAMS each product supplies — so this module imports no DB and no key-mgmt\n * SDK (structural contracts only, like `../tangle`). The `@tangle-network/tcloud`\n * SDK is the provisioner a product passes in; it is not a dependency here.\n */\n\n/** The key-provisioning operations the key manager needs. Wire it from the\n * platform via {@link createTcloudKeyProvisioner} rather than casting. */\nexport interface KeyProvisioner {\n createKey(input: { name: string; product: string; budgetUsd: number; expiresAt: string }): Promise<{ id?: string; key?: string }>\n revokeKey(keyId: string): Promise<unknown>\n getKey(keyId: string): Promise<{ budgetUsd?: number; budgetSpent?: number; expiresAt?: string | null }>\n}\n\n/**\n * The subset of the `@tangle-network/tcloud` `TCloudClient` the provisioner uses\n * — declared with METHOD syntax so the real client (whose `product` is a narrow\n * union and whose budgets are `number | null`) is assignable bivariantly. The\n * real SDK client satisfies this; pass it straight in.\n */\nexport interface TcloudKeyClient {\n createKey(opts: {\n name: string\n product?: string\n budgetUsd?: number\n expiresAt?: string\n parentKeyId?: string\n allowedModels?: string[]\n rpmLimit?: number\n }): Promise<{ id: string; key: string }>\n getKey(id: string): Promise<{ budgetUsd?: number | null; budgetSpent?: number; expiresAt?: string | null }>\n revokeKey(id: string): Promise<unknown>\n}\n\n/**\n * Adapt the tcloud SDK client to {@link KeyProvisioner} — the typed seam that\n * replaces the `as unknown as KeyProvisioner` cast every consumer otherwise\n * repeats. The platform already exposes child-key minting (parent→child key,\n * per-key USD budget, expiry); this maps its shapes (`product` union,\n * `number | null` budgets) onto the manager's contract (`null → undefined`).\n */\nexport function createTcloudKeyProvisioner(client: TcloudKeyClient): KeyProvisioner {\n return {\n createKey: async (input) => {\n const created = await client.createKey(input)\n return { id: created.id, key: created.key }\n },\n revokeKey: (keyId) => client.revokeKey(keyId),\n getKey: async (keyId) => {\n const info = await client.getKey(keyId)\n return {\n budgetUsd: info.budgetUsd ?? undefined,\n budgetSpent: info.budgetSpent ?? undefined,\n expiresAt: info.expiresAt ?? null,\n }\n },\n }\n}\n\n/** A stored child-key record (the app's row, shape-normalized). */\nexport interface WorkspaceKeyRecord {\n /** App row id (opaque). */\n id: string\n keyId: string\n /** The encrypted secret — decrypted via {@link KeyCrypto.decrypt}. */\n keyEncrypted: string\n budgetUsd: number\n expiresAt: Date | null\n}\n\n/** Persistence seam — the product implements this against its own D1 table. */\nexport interface WorkspaceKeyStore {\n /** Most-recent active key for the workspace, or null. */\n getActive(workspaceId: string): Promise<WorkspaceKeyRecord | null>\n /** All active keys (to revoke priors on rotate). */\n listActive(workspaceId: string): Promise<Array<{ id: string; keyId: string }>>\n /** Persist a freshly minted active key. */\n insert(record: { workspaceId: string; keyId: string; keyEncrypted: string; budgetUsd: number; expiresAt: Date }): Promise<void>\n /** Mark a prior row revoked. */\n markRevoked(id: string, now: Date): Promise<void>\n}\n\n/** Secret encryption seam (the app's at-rest crypto). */\nexport interface KeyCrypto {\n encrypt(secret: string): Promise<string>\n decrypt(encrypted: string): Promise<string>\n}\n\n/** Define configuration options for managing workspace keys including provisioning, storage, and cryptography */\nexport interface WorkspaceKeyManagerOptions {\n provisioner: KeyProvisioner\n store: WorkspaceKeyStore\n crypto: KeyCrypto\n /** Default monthly allowance (USD) when a call doesn't specify one. */\n defaultBudgetUsd: number\n /** Injectable clock. Default `() => new Date()`. */\n now?: () => Date\n /** tcloud product the key is scoped to. Default `'router'`. */\n product?: string\n}\n\n/** Describe usage and budget details for a workspace model key including expiration and exhaustion status */\nexport interface WorkspaceModelKeyUsage {\n keyId: string\n budgetUsd: number\n budgetSpent: number\n budgetRemaining: number\n expiresAt: string | null\n exhausted: boolean\n}\n\n/** Manage workspace keys by ensuring, rotating, and tracking usage of active child-key secrets */\nexport interface WorkspaceKeyManager {\n /** The workspace's active child-key secret, provisioning one if absent/expired. */\n ensureKey(workspaceId: string, opts?: { budgetUsd?: number }): Promise<string>\n /** Mint a fresh key + revoke priors (period renewal / top-up). `rollover`\n * carries the prior key's unused budget into the new one, bounded by\n * `rolloverCapUsd`. Returns the new secret. */\n rotateKey(workspaceId: string, opts?: { budgetUsd?: number; rollover?: boolean; rolloverCapUsd?: number }): Promise<string>\n /** Live budget usage for the active key (drives the \"$X of $Y used\" panel). */\n getUsage(workspaceId: string): Promise<WorkspaceModelKeyUsage | null>\n}\n\n/** Period end = first day of next month, midnight UTC. Keys expire at the period\n * boundary so a forgotten rotation fails closed rather than running free. */\nfunction nextPeriodEnd(now: Date): Date {\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 0, 0, 0, 0))\n}\n\n// ---------------------------------------------------------------------------\n// Shared-platform-balance billing\n//\n// A DIFFERENT model from the per-workspace child-key manager above: here every\n// user runs against a SHARED platform balance (id.tangle.tools), keyed by the\n// user's platform identity. The app owns no key minting — it reads the balance,\n// gates a billable turn, and deducts spend through the platform billing API.\n// Plan limits, the platform transport, and identity resolution are SEAMS the\n// product supplies; this module imports no DB and no HTTP client.\n// ---------------------------------------------------------------------------\n\n/** A user's resolved platform identity (from the app's SSO account store). */\nexport interface PlatformIdentity {\n platformUserId: string\n /** The user's per-user platform API key (reads), or null when unlinked. */\n apiKey: string | null\n}\n\n/** Spendable balance for a platform user. */\nexport interface PlatformBalanceInfo {\n balance: number\n lifetimeSpent: number\n}\n\n/** Per-product spend aggregate. */\nexport interface PlatformProductUsage {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Plan limits — a PARAMETER per product (dollar allowance, concurrency,\n * overage policy). Never baked into the framework. */\nexport interface PlanLimit {\n monthlyBalanceUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * The platform billing transport — the product wires these to id.tangle.tools\n * (or any balance backend). Reads authenticate as the user (their `apiKey`);\n * the deduct write is a service-token call naming the target user. This module\n * never touches HTTP — it only sequences these calls.\n */\nexport interface PlatformBillingClient<Plan extends string> {\n /** Resolve the user's platform identity, or null when there is no SSO account. */\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n /** Subscription plan for the user (via their platform key). */\n getPlan(apiKey: string): Promise<Plan>\n /** Spendable balance for the user (via their platform key). */\n getBalance(apiKey: string): Promise<PlatformBalanceInfo>\n /** Per-product usage rows for the user (via their platform key). */\n getUsageByProduct(apiKey: string): Promise<PlatformProductUsage[]>\n /** Deduct spend against the user's balance (service-token write). */\n deduct(input: { platformUserId: string; amountUsd: number; type: string; description: string; referenceId: string; keyId?: string }): Promise<void>\n}\n\n/** Define shared billing state including user ID, plan, balances, concurrency, and overage permission */\nexport interface SharedBillingState<Plan extends string> {\n /** Platform user id, or null when the user has no Tangle SSO account. */\n platformUserId: string | null\n plan: Plan\n monthlyBalanceUsd: number\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Reads one platform key's plan and balance for {@link readSharedBillingState}. */\nexport interface SharedBillingReads<Plan extends string> {\n getPlan(apiKey: string): Promise<Plan>\n getBalance(apiKey: string): Promise<PlatformBalanceInfo>\n /** Plan → limits map (the product's pricing). */\n planLimits: Record<Plan, PlanLimit>\n /** The plan a key-less user falls to. */\n freePlan: Plan\n}\n\n/**\n * The plan, limits and balance behind one platform key. No key means the user\n * is not linked: the free plan with zero balance, and no read is issued with\n * an empty key.\n */\nexport async function readSharedBillingState<Plan extends string>(\n apiKey: string | null | undefined,\n reads: SharedBillingReads<Plan>,\n): Promise<Omit<SharedBillingState<Plan>, 'platformUserId'>> {\n if (!apiKey) {\n const limits = reads.planLimits[reads.freePlan]\n return {\n plan: reads.freePlan,\n monthlyBalanceUsd: limits.monthlyBalanceUsd,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n concurrency: limits.concurrency,\n overageAllowed: limits.overageAllowed,\n }\n }\n const [plan, balance] = await Promise.all([reads.getPlan(apiKey), reads.getBalance(apiKey)])\n const limits = reads.planLimits[plan]\n return {\n plan,\n monthlyBalanceUsd: limits.monthlyBalanceUsd,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n concurrency: limits.concurrency,\n overageAllowed: limits.overageAllowed,\n }\n}\n\n/** Define configuration options for managing platform balance based on billing plans */\nexport interface PlatformBalanceManagerOptions<Plan extends string> {\n client: PlatformBillingClient<Plan>\n /** Plan → limits map (the product's pricing). */\n planLimits: Record<Plan, PlanLimit>\n /** The plan an unlinked / outage user falls to (fails CLOSED). */\n freePlan: Plan\n /** The product slug to attribute usage to (for `getProductUsage`). */\n productSlug: string\n}\n\n/** Manage user plans and balances including state retrieval, billing authorization, deduction, and usage tracking */\nexport interface PlatformBalanceManager<Plan extends string> {\n /** Resolve the user's plan + balance. Unlinked or platform-outage users fail\n * CLOSED: free plan, zero remaining balance — a billable run is never started\n * against an unknown balance. */\n getState(userId: string): Promise<SharedBillingState<Plan>>\n /** Gate a billable turn: allowed when the plan permits overage or remaining\n * balance is positive. Returns the state so the caller deducts against it. */\n canStartBillableTurn(userId: string): Promise<{ allowed: boolean; state: SharedBillingState<Plan> }>\n /** Deduct `amountUsd` against the user's platform balance. Throws when the\n * user is not platform-linked. */\n deduct(userId: string, params: { amountUsd: number; type: string; description: string; referenceId: string; keyId?: string }): Promise<void>\n /** This product's spend for the user (drives a usage panel). */\n getProductUsage(userId: string): Promise<{ spentUsd: number; transactionCount: number }>\n}\n\n/** Create a platform balance manager to handle user plan limits and state based on provided options */\nexport function createPlatformBalanceManager<Plan extends string>(\n opts: PlatformBalanceManagerOptions<Plan>,\n): PlatformBalanceManager<Plan> {\n const { client, planLimits, freePlan, productSlug } = opts\n\n const getState: PlatformBalanceManager<Plan>['getState'] = async (userId) => {\n const identity = await client.resolveIdentity(userId)\n // No SSO account, or linked without a platform key: unlinked free tier with\n // zero balance.\n const state = await readSharedBillingState(identity?.apiKey, {\n getPlan: (apiKey) => client.getPlan(apiKey),\n getBalance: (apiKey) => client.getBalance(apiKey),\n planLimits,\n freePlan,\n })\n return { platformUserId: identity?.platformUserId ?? null, ...state }\n }\n\n const canStartBillableTurn: PlatformBalanceManager<Plan>['canStartBillableTurn'] = async (userId) => {\n const state = await getState(userId)\n if (!state.platformUserId) return { allowed: false, state }\n const allowed = state.overageAllowed || state.remainingBalanceUsd > 0\n return { allowed, state }\n }\n\n const deduct: PlatformBalanceManager<Plan>['deduct'] = async (userId, params) => {\n const identity = await client.resolveIdentity(userId)\n if (!identity) throw new Error('Shared billing requires a platform-linked user')\n await client.deduct({\n platformUserId: identity.platformUserId,\n amountUsd: params.amountUsd,\n type: params.type,\n description: params.description,\n referenceId: params.referenceId,\n keyId: params.keyId,\n })\n }\n\n const getProductUsage: PlatformBalanceManager<Plan>['getProductUsage'] = async (userId) => {\n const identity = await client.resolveIdentity(userId)\n if (!identity?.apiKey) return { spentUsd: 0, transactionCount: 0 }\n const rows = await client.getUsageByProduct(identity.apiKey)\n const product = rows.find((row) => row.product === productSlug)\n return { spentUsd: product?.totalSpent ?? 0, transactionCount: product?.count ?? 0 }\n }\n\n return { getState, canStartBillableTurn, deduct, getProductUsage }\n}\n\n/** Create a workspace key manager that handles key provisioning and budget tracking */\nexport function createWorkspaceKeyManager(opts: WorkspaceKeyManagerOptions): WorkspaceKeyManager {\n const clock = opts.now ?? (() => new Date())\n const product = opts.product ?? 'router'\n\n const getUsage: WorkspaceKeyManager['getUsage'] = async (workspaceId) => {\n const active = await opts.store.getActive(workspaceId)\n if (!active) return null\n const info = await opts.provisioner.getKey(active.keyId)\n const budgetUsd = info.budgetUsd ?? active.budgetUsd\n const budgetSpent = info.budgetSpent ?? 0\n const budgetRemaining = Math.max(0, budgetUsd - budgetSpent)\n return {\n keyId: active.keyId,\n budgetUsd,\n budgetSpent,\n budgetRemaining,\n expiresAt: info.expiresAt ?? (active.expiresAt ? active.expiresAt.toISOString() : null),\n exhausted: budgetRemaining <= 0,\n }\n }\n\n const rotateKey: WorkspaceKeyManager['rotateKey'] = async (workspaceId, ropts) => {\n const now = clock()\n const allowance = ropts?.budgetUsd ?? opts.defaultBudgetUsd\n\n let budgetUsd = allowance\n if (ropts?.rollover) {\n const prior = await getUsage(workspaceId).catch(() => null)\n budgetUsd = allowance + (prior?.budgetRemaining ?? 0)\n if (ropts.rolloverCapUsd != null) budgetUsd = Math.min(budgetUsd, ropts.rolloverCapUsd)\n }\n\n // Prove the at-rest crypto seam is usable BEFORE spending a platform mint.\n // The `KeyCrypto` impl may close over an env-resolved key (createFieldCrypto)\n // that is empty/invalid and only throws at encrypt time — after the mint —\n // orphaning the child key. A round-trip probe makes a misconfigured consumer\n // fail loud with ZERO platform spend.\n await assertWorkspaceKeyCryptoUsable(opts.crypto)\n\n const expiresAt = nextPeriodEnd(now)\n const created = await opts.provisioner.createKey({ name: `ws:${workspaceId}`, product, budgetUsd, expiresAt: expiresAt.toISOString() })\n if (!created.key || !created.id) throw new Error('tcloud createKey returned no key')\n const mintedKeyId = created.id\n\n // Past this point the platform has minted a budget-bearing child key. ANY\n // failure before the row is persisted (encrypt, insert) MUST revoke the\n // just-minted key, else it leaks as a zombie holding parent-key headroom —\n // a missing/invalid encryption key would otherwise burn the child budget\n // per mint attempt until the parent can no longer mint (fleet-wide outage).\n let keyEncrypted: string\n let priors: Array<{ id: string; keyId: string }>\n try {\n keyEncrypted = await opts.crypto.encrypt(created.key)\n priors = await opts.store.listActive(workspaceId)\n await opts.store.insert({ workspaceId, keyId: mintedKeyId, keyEncrypted, budgetUsd, expiresAt })\n } catch (err) {\n // Best-effort revoke of the orphan. A revoke failure must NOT mask the\n // original cause — log it loudly and rethrow the original error.\n try {\n await opts.provisioner.revokeKey(mintedKeyId)\n } catch (revokeErr) {\n console.error(\n `[workspace-key-manager] FAILED to revoke orphaned child key ${mintedKeyId} ` +\n `for workspace ${workspaceId} after a post-mint failure — it now leaks parent-key budget. ` +\n `Revoke error:`,\n revokeErr,\n )\n }\n throw err\n }\n\n for (const p of priors) {\n await opts.store.markRevoked(p.id, now)\n // Best-effort upstream revoke — the row is already revoked and an expired\n // key fails closed regardless, so a transient error is non-fatal.\n try {\n await opts.provisioner.revokeKey(p.keyId)\n } catch {\n /* non-fatal */\n }\n }\n return created.key\n }\n\n const ensureKey: WorkspaceKeyManager['ensureKey'] = async (workspaceId, eopts) => {\n const now = clock()\n const active = await opts.store.getActive(workspaceId)\n if (active && (!active.expiresAt || active.expiresAt.getTime() > now.getTime())) {\n return opts.crypto.decrypt(active.keyEncrypted)\n }\n // An expired child can no longer spend, yet the platform keeps its budget\n // reserved on the parent until it is revoked. Revoke it BEFORE minting the\n // renewal: minting first needs a second child's budget of headroom, so a\n // fully reserved parent could never renew and the expired key would hold\n // its reservation forever. Best-effort: on failure the row stays active and\n // rotateKey retries the revoke after its mint.\n if (active) {\n try {\n await opts.provisioner.revokeKey(active.keyId)\n await opts.store.markRevoked(active.id, now)\n } catch {\n /* rotateKey revokes remaining priors after the mint */\n }\n }\n return rotateKey(workspaceId, { budgetUsd: eopts?.budgetUsd })\n }\n\n return { ensureKey, rotateKey, getUsage }\n}\n\nexport {\n createIdentityBoundWorkspaceKeyManager,\n DEFAULT_MIN_REMAINING_KEY_LIFETIME_MS,\n type DurableWorkspaceKeyManager,\n type DurableWorkspaceKeyManagerOptions,\n type DurableWorkspaceKeyCreateInput,\n type DurableWorkspaceKeyConditionalWrites,\n type DurableWorkspaceKeyProvisioner,\n type DurableWorkspaceKeyProvisioningRecord,\n type DurableWorkspaceKeyRecord,\n type DurableWorkspaceKeyScope,\n type DurableWorkspaceKeyStore,\n type WorkspaceKeyIdentity,\n type WorkspaceKeyProduct,\n type WorkspaceKeyStatus,\n type WorkspaceKeyUsage,\n type WorkspaceRuntimeKey,\n} from './identity-bound'\n"],"mappings":";;;;;AAEO,SAAS,wBACd,aACA,SACA,KACA,SACA,aACA,sBACAA,cACAC,QACA;AACA,QAAM,aAAa,oBAAI,IAA2B;AAElD,iBAAe,cAAiB,OAAe,MAAoC;AACjF,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