@tangle-network/agent-app 0.60.188 → 0.60.190
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.
|
@@ -43,17 +43,8 @@ export interface DeriveChildKeyBudgetInput {
|
|
|
43
43
|
/** Minimum child budget override. Default {@link MIN_CHILD_KEY_BUDGET_USD}. */
|
|
44
44
|
readonly minChildUsd?: number;
|
|
45
45
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
* less than the configured default. */
|
|
52
|
-
readonly derivedFromParent: boolean;
|
|
53
|
-
/** True when the platform reports no ceiling and the configured ask stood. */
|
|
54
|
-
readonly parentRemainingUnknown: boolean;
|
|
55
|
-
}
|
|
56
|
-
/** Derive the delegated child-key budget from the parent's remaining budget.
|
|
57
|
-
* Throws {@link ParentBudgetExhaustedError} when the parent is exhausted,
|
|
58
|
-
* before any mint is attempted. */
|
|
59
|
-
export declare function deriveChildKeyBudgetUsd(input: DeriveChildKeyBudgetInput): DerivedChildKeyBudget;
|
|
46
|
+
/** Derive the delegated child-key budget from the parent's remaining budget:
|
|
47
|
+
* the ask the mint should make — never above a known remaining, never below
|
|
48
|
+
* the platform minimum. Throws {@link ParentBudgetExhaustedError} when the
|
|
49
|
+
* parent is exhausted, before any mint is attempted. */
|
|
50
|
+
export declare function deriveChildKeyBudgetUsd(input: DeriveChildKeyBudgetInput): number;
|
package/dist/spend/index.d.ts
CHANGED
|
@@ -36,5 +36,5 @@ export { DEFAULT_CEILING_TOLERANCE_MS, computeExpectedCeiling, type ComputeExpec
|
|
|
36
36
|
export { chargeNanoUsd, isCharge, parseSandboxGroupKey, parseSettlementReference, settlementSandboxId, } from './reference';
|
|
37
37
|
export { reconcileSpend, type BoxRateResolver, type ObservedBalance, type ReconcileSpendOptions, type VelocityOptions, } from './reconcile';
|
|
38
38
|
export { ComputeBudgetExceededError, assertComputeBudget, createSandboxSpendHooks, type ComputeBudget, type ComputeBudgetRefusal, type SandboxSpendHooksOptions, type SandboxSpendSeam, type SpendProvisionObservation, } from './budget';
|
|
39
|
-
export { MIN_CHILD_KEY_BUDGET_USD, ParentBudgetExhaustedError, deriveChildKeyBudgetUsd, type DeriveChildKeyBudgetInput,
|
|
39
|
+
export { MIN_CHILD_KEY_BUDGET_USD, ParentBudgetExhaustedError, deriveChildKeyBudgetUsd, type DeriveChildKeyBudgetInput, } from './delegate-budget';
|
|
40
40
|
export { formatSpendReport, spendReportToJson } from './report';
|
package/dist/spend/index.js
CHANGED
|
@@ -215,16 +215,9 @@ function deriveChildKeyBudgetUsd(input) {
|
|
|
215
215
|
}
|
|
216
216
|
const ceiling = input.parentRemainingUsd;
|
|
217
217
|
const known = typeof ceiling === "number" && Number.isFinite(ceiling);
|
|
218
|
-
if (!known)
|
|
219
|
-
return { budgetUsd: input.requestedUsd, derivedFromParent: false, parentRemainingUnknown: true };
|
|
220
|
-
}
|
|
218
|
+
if (!known) return input.requestedUsd;
|
|
221
219
|
if (ceiling <= 0) throw new ParentBudgetExhaustedError(input.requestedUsd, ceiling);
|
|
222
|
-
|
|
223
|
-
return {
|
|
224
|
-
budgetUsd,
|
|
225
|
-
derivedFromParent: budgetUsd < input.requestedUsd || ceiling < minChildUsd,
|
|
226
|
-
parentRemainingUnknown: false
|
|
227
|
-
};
|
|
220
|
+
return Math.max(minChildUsd, Math.min(input.requestedUsd, Math.floor(ceiling * 100) / 100));
|
|
228
221
|
}
|
|
229
222
|
export {
|
|
230
223
|
ComputeBudgetExceededError,
|
package/dist/spend/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/spend/store.ts","../../src/spend/budget.ts","../../src/spend/delegate-budget.ts"],"sourcesContent":["import type { SpendBoxPatch, SpendBoxRecord, SpendWindow } from './types'\n\n/**\n * Persistence seam for the expectation ledger — the product implements it over\n * its own tables.\n *\n * Deliberately NOT compare-and-set, unlike `MissionStorePort`. A mission has one\n * serialized owner and a lost write corrupts a state machine; a box record is a\n * MONOTONIC FOLD (activity takes a max, a detached-run id joins or leaves a set,\n * delete is set-once) so concurrent writers converge no matter what order they\n * land in. The worst a lost race can do here is leave `lastActivityAt` behind\n * the truth — which makes the derived ceiling TIGHTER, so the failure mode is a\n * false alarm a human dismisses, never a missed charge. That asymmetry is the\n * whole reason the fold is shaped this way.\n *\n * `update` returns null when the row does not exist, never a throw.\n */\nexport interface SpendLedgerStorePort {\n load(sandboxId: string): Promise<SpendBoxRecord | null>\n /** `extras` are the opaque product-column values — write them in the SAME\n * statement as the record, or ignore them if the table has no extra columns. */\n insert(record: SpendBoxRecord, extras?: Record<string, unknown>): Promise<SpendBoxRecord>\n update(sandboxId: string, patch: SpendBoxPatch): Promise<SpendBoxRecord | null>\n /**\n * OPTIONAL — every box that could have been live during the window.\n *\n * This is the one capability that lets a reconciliation answer \"were we NOT\n * billed for something we DID ask for\". Without it the pass is driven entirely\n * by settlement rows, so a feed that returns nothing fires nothing and reads\n * as a clean bill. Omitting it is safe and additive: the pass reports\n * `expectation.declared: false` and refuses to certify a bill it could not\n * check (see {@link SpendReport.coverage}).\n *\n * **It may over-return.** The reconciler re-derives liveness itself with\n * `boxLivenessInWindow`, so a store that returns every row it has is correct,\n * merely slower. That is deliberate: the definition of \"live\" must live in one\n * place, not once per product's SQL. The intended predicate is the coarse one\n * a WHERE clause can express —\n *\n * ```sql\n * WHERE created_at <= :endAt AND (deleted_at IS NULL OR deleted_at >= :startAt)\n * ```\n *\n * — and the exact answer (idle timeout, max lifetime, stop, open detached run)\n * is the reconciler's.\n */\n listLiveBetween?(window: SpendWindow): Promise<readonly SpendBoxRecord[]>\n}\n\n/**\n * Apply one fold step. Exported so a SQL implementation and an in-memory one\n * reach the same record, and so a product can unit-test its own store against\n * the canonical answer.\n *\n * The two rules worth stating out loud:\n *\n * - `observedActivityAt` only ever moves `lastActivityAt` FORWARD. A replayed\n * or out-of-order event cannot rewind the ceiling.\n * - activity later than a recorded `stoppedAt` CLEARS the stop. A box that\n * worked after the product thought it stopped is running again, and keeping\n * the stale stop would make the ceiling too tight — inventing an over-ceiling\n * finding out of the product's own bookkeeping rather than the platform's.\n */\nexport function foldSpendBoxRecord(record: SpendBoxRecord, patch: SpendBoxPatch): SpendBoxRecord {\n let lastActivityAt = record.lastActivityAt\n let stoppedAt = record.stoppedAt\n let openDetachedRunIds = record.openDetachedRunIds\n\n if (patch.observedActivityAt !== undefined) {\n lastActivityAt = Math.max(lastActivityAt, patch.observedActivityAt)\n if (stoppedAt !== null && patch.observedActivityAt > stoppedAt) stoppedAt = null\n }\n if (patch.openDetachedRunAdd !== undefined && !openDetachedRunIds.includes(patch.openDetachedRunAdd)) {\n openDetachedRunIds = [...openDetachedRunIds, patch.openDetachedRunAdd]\n }\n if (patch.openDetachedRunRemove !== undefined) {\n openDetachedRunIds = openDetachedRunIds.filter((id) => id !== patch.openDetachedRunRemove)\n }\n if (patch.stoppedAt !== undefined) {\n // Latest-wins, but never behind observed activity: a stop we are told about\n // that predates work we watched is not the stop that closed this box.\n stoppedAt = patch.stoppedAt >= lastActivityAt ? patch.stoppedAt : stoppedAt\n }\n\n return {\n ...record,\n lastActivityAt,\n stoppedAt,\n openDetachedRunIds,\n // Set-once: a deleted sandbox id never comes back, so a second observation\n // is a duplicate delivery, not a second deletion.\n deletedAt: record.deletedAt ?? patch.deletedAt ?? null,\n }\n}\n\n/** An in-memory store that also lets a test inspect and force state. */\nexport interface InMemorySpendLedgerStore extends SpendLedgerStorePort {\n /** Every record, insertion order. */\n records(): SpendBoxRecord[]\n /** Unguarded direct write — simulates a crash-shaped or platform-seeded row. */\n put(record: SpendBoxRecord): void\n}\n\n/** Create an in-memory expectation ledger. Production writers use the same port. */\nexport function createInMemorySpendLedgerStore(): InMemorySpendLedgerStore {\n const rows = new Map<string, SpendBoxRecord>()\n return {\n async load(sandboxId) {\n const row = rows.get(sandboxId)\n return row ? structuredClone(row) : null\n },\n async insert(record) {\n const stored = structuredClone(record)\n rows.set(record.sandboxId, stored)\n return structuredClone(stored)\n },\n async update(sandboxId, patch) {\n const current = rows.get(sandboxId)\n if (!current) return null\n const next = foldSpendBoxRecord(current, patch)\n rows.set(sandboxId, next)\n return structuredClone(next)\n },\n async listLiveBetween(window) {\n // Deliberately the COARSE predicate a product's SQL can express, not the\n // exact one: the idle-timeout / max-lifetime / detached-run derivation is\n // the reconciler's, and this over-returning is what proves the reconciler\n // re-filters rather than trusting whatever a store hands it.\n return [...rows.values()]\n .filter(\n (row) =>\n row.createdAt <= window.endAt && (row.deletedAt === null || row.deletedAt >= window.startAt),\n )\n .map((row) => structuredClone(row))\n },\n records() {\n return [...rows.values()].map((row) => structuredClone(row))\n },\n put(record) {\n rows.set(record.sandboxId, structuredClone(record))\n },\n }\n}\n\n/** What the product tells the ledger when it first sees a box. */\nexport interface ObserveSandboxInput {\n readonly sandboxId: string\n readonly workspaceId: string\n /** The idle timeout the product asked the platform for, seconds. */\n readonly idleTimeoutSeconds: number\n /** The max lifetime the product asked for, seconds, when it asked for one. */\n readonly maxLifetimeSeconds?: number | null\n /** Defaults to the ledger's clock. */\n readonly at?: number\n}\n\nexport interface SpendLedgerOptions {\n readonly store: SpendLedgerStorePort\n /** Injectable clock (epoch ms). Default `Date.now`. */\n readonly now?: () => number\n /** Product columns written verbatim on every insert. */\n readonly extras?: Record<string, unknown>\n}\n\n/**\n * The recording half of spend verification: the product's own account of what\n * it asked the platform for.\n *\n * Every method is best-effort from the caller's point of view — a product wires\n * these into paths that must not fail because bookkeeping failed. They still\n * reject on a store error rather than swallowing it, so a caller that wants\n * fire-and-forget says so at the call site (`/sandbox`'s hook does).\n */\nexport interface SpendLedger {\n /**\n * Record that a box exists and is billable from now. Inserts on first sight,\n * and otherwise records activity — reuse and resume are both \"the platform is\n * charging for this box again\", and the record's own existence is what\n * distinguishes them, so no caller has to know which happened.\n */\n observeSandbox(input: ObserveSandboxInput): Promise<SpendBoxRecord>\n /** Record that the product saw this box do work. */\n recordActivity(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /**\n * Record that the product handed the platform work it will NOT watch finish.\n * Until the matching end is recorded, this box's ceiling cannot rest on\n * observed activity — see `computeExpectedCeiling`.\n */\n recordDetachedRunStarted(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that a detached run was confirmed finished. */\n recordDetachedRunEnded(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box stopped. */\n recordStopped(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box was deleted. */\n recordDeleted(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n}\n\n/** Create the recording half over a product-supplied store. */\nexport function createSpendLedger(options: SpendLedgerOptions): SpendLedger {\n const { store } = options\n const clock = options.now ?? Date.now\n\n return {\n async observeSandbox(input) {\n const at = input.at ?? clock()\n const existing = await store.load(input.sandboxId)\n if (existing) {\n const updated = await store.update(input.sandboxId, { observedActivityAt: at })\n return updated ?? existing\n }\n return await store.insert(\n {\n sandboxId: input.sandboxId,\n workspaceId: input.workspaceId,\n createdAt: at,\n idleTimeoutSeconds: input.idleTimeoutSeconds,\n maxLifetimeSeconds: input.maxLifetimeSeconds ?? null,\n lastActivityAt: at,\n openDetachedRunIds: [],\n stoppedAt: null,\n deletedAt: null,\n },\n options.extras,\n )\n },\n async recordActivity(sandboxId, at) {\n return await store.update(sandboxId, { observedActivityAt: at ?? clock() })\n },\n async recordDetachedRunStarted(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunAdd: runId,\n })\n },\n async recordDetachedRunEnded(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunRemove: runId,\n })\n },\n async recordStopped(sandboxId, at) {\n return await store.update(sandboxId, { stoppedAt: at ?? clock() })\n },\n async recordDeleted(sandboxId, at) {\n return await store.update(sandboxId, { deletedAt: at ?? clock() })\n },\n }\n}\n","import type { SpendLedger } from './store'\n\n/** Why provisioning was refused, with every number the decision used. */\nexport interface ComputeBudgetRefusal {\n readonly workspaceId: string\n /** The cap, unsigned nanodollars. */\n readonly limitNanoUsd: number\n /** Cumulative settled compute spend for this workspace, unsigned nanodollars. */\n readonly settledNanoUsd: number\n /** How far past the cap it already is. */\n readonly overageNanoUsd: number\n readonly at: number\n}\n\n/**\n * Provisioning refused because the workspace is already past its compute cap.\n *\n * Correctable by design: every number the decision used is on the error, so a\n * product can render \"this workspace has spent $X of its $Y compute budget\" and\n * an operator can raise the cap or investigate without reading logs.\n *\n * This is the failure mode the module exists to produce. A platform billing\n * defect that used to end in a silent negative balance now ends in provisioning\n * stopping and something loud happening instead.\n */\nexport class ComputeBudgetExceededError extends Error {\n readonly workspaceId: string\n readonly limitNanoUsd: number\n readonly settledNanoUsd: number\n readonly overageNanoUsd: number\n\n constructor(refusal: ComputeBudgetRefusal) {\n super(\n `Compute budget exceeded for workspace ${refusal.workspaceId}: ` +\n `$${(refusal.settledNanoUsd / 1_000_000_000).toFixed(2)} settled against a cap of ` +\n `$${(refusal.limitNanoUsd / 1_000_000_000).toFixed(2)} ` +\n `(over by $${(refusal.overageNanoUsd / 1_000_000_000).toFixed(2)}). ` +\n 'No sandbox was provisioned. Raise the cap or reconcile the spend before retrying.',\n )\n this.name = 'ComputeBudgetExceededError'\n this.workspaceId = refusal.workspaceId\n this.limitNanoUsd = refusal.limitNanoUsd\n this.settledNanoUsd = refusal.settledNanoUsd\n this.overageNanoUsd = refusal.overageNanoUsd\n }\n}\n\n/**\n * A per-workspace cap on sandbox compute.\n *\n * `/billing`'s budget primitive caps MODEL keys, and it works because the\n * platform enforces the cap at the key it minted. Sandbox compute has no such\n * key: a box bills the shared company wallet, so nothing upstream refuses. This\n * carries the same shape to the one place a consumer can still act — the moment\n * before it asks for another box.\n *\n * `settledNanoUsd` is a callback rather than a number because the authority is\n * the platform ledger, not this package: the product reads the same rows it\n * hands the reconciler. Cache it if the read is expensive; a cap is a\n * coarse-grained control and a slightly stale total still refuses.\n */\nexport interface ComputeBudget {\n /** The cap, unsigned nanodollars. */\n readonly limitNanoUsd: number\n /** Cumulative settled compute spend for the workspace, unsigned nanodollars. */\n readonly settledNanoUsd: (workspaceId: string) => Promise<number> | number\n /**\n * Called on every refusal, before the error is thrown. This is the alert\n * seam: a refusal nobody hears is a product that silently stopped working.\n */\n readonly onRefusal?: (refusal: ComputeBudgetRefusal) => void\n /** Injectable clock (epoch ms). Default `Date.now`. */\n readonly now?: () => number\n}\n\n/**\n * Throw {@link ComputeBudgetExceededError} when the workspace is already past\n * its cap. Returns normally — and reads nothing — when no budget is configured.\n *\n * Deliberately a pre-check against spend ALREADY SETTLED, not a reservation\n * against spend about to happen: settlement lags provisioning by design (the\n * platform's durable settlement queue), so there is no instant at which a\n * consumer could hold an accurate running total. The cap therefore overshoots by\n * at most the unsettled tail, which is bounded by the box's own idle timeout.\n * A cap that refuses one box late is worth far more than one that cannot be\n * implemented honestly.\n */\nexport async function assertComputeBudget(\n budget: ComputeBudget | undefined,\n workspaceId: string,\n): Promise<void> {\n if (!budget) return\n const settledNanoUsd = await budget.settledNanoUsd(workspaceId)\n if (settledNanoUsd < budget.limitNanoUsd) return\n\n const refusal: ComputeBudgetRefusal = {\n workspaceId,\n limitNanoUsd: budget.limitNanoUsd,\n settledNanoUsd,\n overageNanoUsd: settledNanoUsd - budget.limitNanoUsd,\n at: (budget.now ?? Date.now)(),\n }\n budget.onRefusal?.(refusal)\n throw new ComputeBudgetExceededError(refusal)\n}\n\n// ── the /sandbox seam ─────────────────────────────────────────────────────────\n\n/**\n * What `/sandbox` reports once a box is provisioned, reused or resumed.\n *\n * Structurally identical to `SandboxProvisionedObservation` in `/sandbox`, and\n * deliberately re-declared rather than imported: `/spend` composes `/sandbox`,\n * so a type import in the other direction would invert the dependency. The two\n * are pinned together by a compile-time assignment in this module's tests.\n */\nexport interface SpendProvisionObservation {\n readonly workspaceId: string\n readonly userId?: string\n readonly sandboxId: string\n readonly boxKey?: string | undefined\n readonly idleTimeoutSeconds: number\n readonly maxLifetimeSeconds?: number | undefined\n readonly at: number\n}\n\n/**\n * The optional seam `EnsureWorkspaceSandboxOptions.spend` and the turn\n * primitives' `spend` option both accept. One object, wired in both places.\n */\nexport interface SandboxSpendSeam {\n beforeProvision?(input: { workspaceId: string; userId?: string }): Promise<void> | void\n onProvisioned?(observation: SpendProvisionObservation): Promise<void> | void\n /** Synchronous by contract — it sits on the turn path. See `createSandboxSpendHooks`. */\n onActivity?(input: { sandboxId: string; at: number }): void\n}\n\nexport interface SandboxSpendHooksOptions {\n /** Records box lifecycle. Omit to run the budget guard alone. */\n readonly ledger?: SpendLedger\n /** Refuses provisioning past a cap. Omit to record alone. */\n readonly budget?: ComputeBudget\n /**\n * Called when RECORDING fails. Recording is best-effort — a bookkeeping\n * failure must never take down the provisioning it is bookkeeping — so this\n * is the only place such a failure is visible. A refusal is NOT routed here;\n * refusals throw, by design.\n */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * Build the object to hand `ensureWorkspaceSandbox`'s `spend` option.\n *\n * Wiring it is the entire adoption cost: one field, and the product's boxes are\n * both budget-capped and recorded.\n */\nexport function createSandboxSpendHooks(options: SandboxSpendHooksOptions): SandboxSpendSeam {\n const { ledger, budget, onError } = options\n return {\n async beforeProvision(input) {\n await assertComputeBudget(budget, input.workspaceId)\n },\n async onProvisioned(observation) {\n if (!ledger) return\n try {\n await ledger.observeSandbox({\n sandboxId: observation.sandboxId,\n workspaceId: observation.workspaceId,\n idleTimeoutSeconds: observation.idleTimeoutSeconds,\n maxLifetimeSeconds: observation.maxLifetimeSeconds ?? null,\n at: observation.at,\n })\n } catch (err) {\n onError?.(err)\n }\n },\n onActivity(input) {\n if (!ledger) return\n // The turn path calls this synchronously and does not await it, so the\n // promise is settled here rather than escaping as an unhandled rejection.\n // Recording activity is a monotonic max, so a write that lands late — or\n // out of order against another turn's — still converges.\n void ledger.recordActivity(input.sandboxId, input.at).catch((err: unknown) => onError?.(err))\n },\n }\n}\n","/**\n * The budget-derived delegated mint — the platform's reservation contract as\n * one function.\n *\n * The platform RESERVES a delegated child key's budget against its parent's\n * REMAINING budget: an ask above remaining is a hard refusal (no amounts in\n * the response), which is how every delegated mint in a fleet product died\n * until the derivation landed (hardware-agent #165, 2026-10-09: a flat $25\n * default asked of a $5-remaining parent refused 100% of mints). Products\n * that mint delegated keys must derive the ask from what the platform\n * actually guarantees:\n *\n * - the parent's remaining budget is UNKNOWN → the configured ask stands\n * (the platform isn't reporting a ceiling; nothing better is knowable);\n * - remaining ≤ 0 → refuse with a correctable top-up error, before any\n * mint is attempted;\n * - otherwise → ask min(configured, remaining) floored to whole cents,\n * never below the platform's minimum child budget (the floor keeps the\n * mint VALID — a below-minimum ask is refused by the key API).\n *\n * Note the boundary honestly: with remaining between $0.01 and the minimum,\n * the derived ask (the floor) still exceeds remaining and the platform will\n * refuse it — that case is indistinguishable from exhausted for the caller\n * and surfaces through the same error path with the numbers attached.\n */\n\n/** The platform's minimum child-key budget. Asks below it are refused by the\n * key API, so the derivation never produces one. */\nexport const MIN_CHILD_KEY_BUDGET_USD = 0.5\n\n/** The source key is exhausted — the only refusal this contract throws.\n * Correctable by design: both numbers the decision used are on the error. */\nexport class ParentBudgetExhaustedError extends Error {\n readonly requestedUsd: number\n readonly parentRemainingUsd: number\n\n constructor(requestedUsd: number, parentRemainingUsd: number) {\n super(\n `workspace source key has no budget remaining ($${parentRemainingUsd.toFixed(2)}) — ` +\n `top up or raise its cap before sandbox turns (the mint would have asked $${requestedUsd.toFixed(2)})`,\n )\n this.name = 'ParentBudgetExhaustedError'\n this.requestedUsd = requestedUsd\n this.parentRemainingUsd = parentRemainingUsd\n }\n}\n\nexport interface DeriveChildKeyBudgetInput {\n /** The configured/default ask (the product's mint budget). Must be a\n * finite positive number. */\n readonly requestedUsd: number\n /** The parent's REMAINING budget as the platform's verify/key info\n * reports it. `null`/`undefined`/non-finite = unknown (not reported). */\n readonly parentRemainingUsd?: number | null\n /** Minimum child budget override. Default {@link MIN_CHILD_KEY_BUDGET_USD}. */\n readonly minChildUsd?: number\n}\n\nexport interface DerivedChildKeyBudget {\n /** The ask the mint should make — never above a known remaining, never\n * below the platform minimum. */\n readonly budgetUsd: number\n /** True when the ask was lowered (or floored) because the parent holds\n * less than the configured default. */\n readonly derivedFromParent: boolean\n /** True when the platform reports no ceiling and the configured ask stood. */\n readonly parentRemainingUnknown: boolean\n}\n\n/** Derive the delegated child-key budget from the parent's remaining budget.\n * Throws {@link ParentBudgetExhaustedError} when the parent is exhausted,\n * before any mint is attempted. */\nexport function deriveChildKeyBudgetUsd(input: DeriveChildKeyBudgetInput): DerivedChildKeyBudget {\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) {\n return { budgetUsd: input.requestedUsd, derivedFromParent: false, parentRemainingUnknown: true }\n }\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 const budgetUsd = Math.max(minChildUsd, Math.min(input.requestedUsd, Math.floor(ceiling * 100) / 100))\n return {\n budgetUsd,\n derivedFromParent: budgetUsd < input.requestedUsd || ceiling < minChildUsd,\n parentRemainingUnknown: false,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+DO,SAAS,mBAAmB,QAAwB,OAAsC;AAC/F,MAAI,iBAAiB,OAAO;AAC5B,MAAI,YAAY,OAAO;AACvB,MAA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AG;AACrD,UAAM,IAAI;AAAA,MACR,kFAAkF,WAAW;AAAA,IAC/F;AAAA,EACF;AACA,QAAM,UAAU,MAAM;AACtB,QAAM,QAAQ,OAAO,YAAY,YAAY,OAAO,SAAS,OAAO;AACpE,MAAI,CAAC,OAAO;AACV,WAAO,EAAE,WAAW,MAAM,cAAc,mBAAmB,OAAO,wBAAwB,KAAK;AAAA,EACjG;AACA,MAAI,WAAW,EAAG,OAAM,IAAI,2BAA2B,MAAM,cAAc,OAAO;AAGlF,QAAM,YAAY,KAAK,IAAI,aAAa,KAAK,IAAI,MAAM,cAAc,KAAK,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;AACrG,SAAO;AAAA,IACL;AAAA,IACA,mBAAmB,YAAY,MAAM,gBAAgB,UAAU;AAAA,IAC/D,wBAAwB;AAAA,EAC1B;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/spend/store.ts","../../src/spend/budget.ts","../../src/spend/delegate-budget.ts"],"sourcesContent":["import type { SpendBoxPatch, SpendBoxRecord, SpendWindow } from './types'\n\n/**\n * Persistence seam for the expectation ledger — the product implements it over\n * its own tables.\n *\n * Deliberately NOT compare-and-set, unlike `MissionStorePort`. A mission has one\n * serialized owner and a lost write corrupts a state machine; a box record is a\n * MONOTONIC FOLD (activity takes a max, a detached-run id joins or leaves a set,\n * delete is set-once) so concurrent writers converge no matter what order they\n * land in. The worst a lost race can do here is leave `lastActivityAt` behind\n * the truth — which makes the derived ceiling TIGHTER, so the failure mode is a\n * false alarm a human dismisses, never a missed charge. That asymmetry is the\n * whole reason the fold is shaped this way.\n *\n * `update` returns null when the row does not exist, never a throw.\n */\nexport interface SpendLedgerStorePort {\n load(sandboxId: string): Promise<SpendBoxRecord | null>\n /** `extras` are the opaque product-column values — write them in the SAME\n * statement as the record, or ignore them if the table has no extra columns. */\n insert(record: SpendBoxRecord, extras?: Record<string, unknown>): Promise<SpendBoxRecord>\n update(sandboxId: string, patch: SpendBoxPatch): Promise<SpendBoxRecord | null>\n /**\n * OPTIONAL — every box that could have been live during the window.\n *\n * This is the one capability that lets a reconciliation answer \"were we NOT\n * billed for something we DID ask for\". Without it the pass is driven entirely\n * by settlement rows, so a feed that returns nothing fires nothing and reads\n * as a clean bill. Omitting it is safe and additive: the pass reports\n * `expectation.declared: false` and refuses to certify a bill it could not\n * check (see {@link SpendReport.coverage}).\n *\n * **It may over-return.** The reconciler re-derives liveness itself with\n * `boxLivenessInWindow`, so a store that returns every row it has is correct,\n * merely slower. That is deliberate: the definition of \"live\" must live in one\n * place, not once per product's SQL. The intended predicate is the coarse one\n * a WHERE clause can express —\n *\n * ```sql\n * WHERE created_at <= :endAt AND (deleted_at IS NULL OR deleted_at >= :startAt)\n * ```\n *\n * — and the exact answer (idle timeout, max lifetime, stop, open detached run)\n * is the reconciler's.\n */\n listLiveBetween?(window: SpendWindow): Promise<readonly SpendBoxRecord[]>\n}\n\n/**\n * Apply one fold step. Exported so a SQL implementation and an in-memory one\n * reach the same record, and so a product can unit-test its own store against\n * the canonical answer.\n *\n * The two rules worth stating out loud:\n *\n * - `observedActivityAt` only ever moves `lastActivityAt` FORWARD. A replayed\n * or out-of-order event cannot rewind the ceiling.\n * - activity later than a recorded `stoppedAt` CLEARS the stop. A box that\n * worked after the product thought it stopped is running again, and keeping\n * the stale stop would make the ceiling too tight — inventing an over-ceiling\n * finding out of the product's own bookkeeping rather than the platform's.\n */\nexport function foldSpendBoxRecord(record: SpendBoxRecord, patch: SpendBoxPatch): SpendBoxRecord {\n let lastActivityAt = record.lastActivityAt\n let stoppedAt = record.stoppedAt\n let openDetachedRunIds = record.openDetachedRunIds\n\n if (patch.observedActivityAt !== undefined) {\n lastActivityAt = Math.max(lastActivityAt, patch.observedActivityAt)\n if (stoppedAt !== null && patch.observedActivityAt > stoppedAt) stoppedAt = null\n }\n if (patch.openDetachedRunAdd !== undefined && !openDetachedRunIds.includes(patch.openDetachedRunAdd)) {\n openDetachedRunIds = [...openDetachedRunIds, patch.openDetachedRunAdd]\n }\n if (patch.openDetachedRunRemove !== undefined) {\n openDetachedRunIds = openDetachedRunIds.filter((id) => id !== patch.openDetachedRunRemove)\n }\n if (patch.stoppedAt !== undefined) {\n // Latest-wins, but never behind observed activity: a stop we are told about\n // that predates work we watched is not the stop that closed this box.\n stoppedAt = patch.stoppedAt >= lastActivityAt ? patch.stoppedAt : stoppedAt\n }\n\n return {\n ...record,\n lastActivityAt,\n stoppedAt,\n openDetachedRunIds,\n // Set-once: a deleted sandbox id never comes back, so a second observation\n // is a duplicate delivery, not a second deletion.\n deletedAt: record.deletedAt ?? patch.deletedAt ?? null,\n }\n}\n\n/** An in-memory store that also lets a test inspect and force state. */\nexport interface InMemorySpendLedgerStore extends SpendLedgerStorePort {\n /** Every record, insertion order. */\n records(): SpendBoxRecord[]\n /** Unguarded direct write — simulates a crash-shaped or platform-seeded row. */\n put(record: SpendBoxRecord): void\n}\n\n/** Create an in-memory expectation ledger. Production writers use the same port. */\nexport function createInMemorySpendLedgerStore(): InMemorySpendLedgerStore {\n const rows = new Map<string, SpendBoxRecord>()\n return {\n async load(sandboxId) {\n const row = rows.get(sandboxId)\n return row ? structuredClone(row) : null\n },\n async insert(record) {\n const stored = structuredClone(record)\n rows.set(record.sandboxId, stored)\n return structuredClone(stored)\n },\n async update(sandboxId, patch) {\n const current = rows.get(sandboxId)\n if (!current) return null\n const next = foldSpendBoxRecord(current, patch)\n rows.set(sandboxId, next)\n return structuredClone(next)\n },\n async listLiveBetween(window) {\n // Deliberately the COARSE predicate a product's SQL can express, not the\n // exact one: the idle-timeout / max-lifetime / detached-run derivation is\n // the reconciler's, and this over-returning is what proves the reconciler\n // re-filters rather than trusting whatever a store hands it.\n return [...rows.values()]\n .filter(\n (row) =>\n row.createdAt <= window.endAt && (row.deletedAt === null || row.deletedAt >= window.startAt),\n )\n .map((row) => structuredClone(row))\n },\n records() {\n return [...rows.values()].map((row) => structuredClone(row))\n },\n put(record) {\n rows.set(record.sandboxId, structuredClone(record))\n },\n }\n}\n\n/** What the product tells the ledger when it first sees a box. */\nexport interface ObserveSandboxInput {\n readonly sandboxId: string\n readonly workspaceId: string\n /** The idle timeout the product asked the platform for, seconds. */\n readonly idleTimeoutSeconds: number\n /** The max lifetime the product asked for, seconds, when it asked for one. */\n readonly maxLifetimeSeconds?: number | null\n /** Defaults to the ledger's clock. */\n readonly at?: number\n}\n\nexport interface SpendLedgerOptions {\n readonly store: SpendLedgerStorePort\n /** Injectable clock (epoch ms). Default `Date.now`. */\n readonly now?: () => number\n /** Product columns written verbatim on every insert. */\n readonly extras?: Record<string, unknown>\n}\n\n/**\n * The recording half of spend verification: the product's own account of what\n * it asked the platform for.\n *\n * Every method is best-effort from the caller's point of view — a product wires\n * these into paths that must not fail because bookkeeping failed. They still\n * reject on a store error rather than swallowing it, so a caller that wants\n * fire-and-forget says so at the call site (`/sandbox`'s hook does).\n */\nexport interface SpendLedger {\n /**\n * Record that a box exists and is billable from now. Inserts on first sight,\n * and otherwise records activity — reuse and resume are both \"the platform is\n * charging for this box again\", and the record's own existence is what\n * distinguishes them, so no caller has to know which happened.\n */\n observeSandbox(input: ObserveSandboxInput): Promise<SpendBoxRecord>\n /** Record that the product saw this box do work. */\n recordActivity(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /**\n * Record that the product handed the platform work it will NOT watch finish.\n * Until the matching end is recorded, this box's ceiling cannot rest on\n * observed activity — see `computeExpectedCeiling`.\n */\n recordDetachedRunStarted(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that a detached run was confirmed finished. */\n recordDetachedRunEnded(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box stopped. */\n recordStopped(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box was deleted. */\n recordDeleted(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n}\n\n/** Create the recording half over a product-supplied store. */\nexport function createSpendLedger(options: SpendLedgerOptions): SpendLedger {\n const { store } = options\n const clock = options.now ?? Date.now\n\n return {\n async observeSandbox(input) {\n const at = input.at ?? clock()\n const existing = await store.load(input.sandboxId)\n if (existing) {\n const updated = await store.update(input.sandboxId, { observedActivityAt: at })\n return updated ?? existing\n }\n return await store.insert(\n {\n sandboxId: input.sandboxId,\n workspaceId: input.workspaceId,\n createdAt: at,\n idleTimeoutSeconds: input.idleTimeoutSeconds,\n maxLifetimeSeconds: input.maxLifetimeSeconds ?? null,\n lastActivityAt: at,\n openDetachedRunIds: [],\n stoppedAt: null,\n deletedAt: null,\n },\n options.extras,\n )\n },\n async recordActivity(sandboxId, at) {\n return await store.update(sandboxId, { observedActivityAt: at ?? clock() })\n },\n async recordDetachedRunStarted(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunAdd: runId,\n })\n },\n async recordDetachedRunEnded(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunRemove: runId,\n })\n },\n async recordStopped(sandboxId, at) {\n return await store.update(sandboxId, { stoppedAt: at ?? clock() })\n },\n async recordDeleted(sandboxId, at) {\n return await store.update(sandboxId, { deletedAt: at ?? clock() })\n },\n }\n}\n","import type { SpendLedger } from './store'\n\n/** Why provisioning was refused, with every number the decision used. */\nexport interface ComputeBudgetRefusal {\n readonly workspaceId: string\n /** The cap, unsigned nanodollars. */\n readonly limitNanoUsd: number\n /** Cumulative settled compute spend for this workspace, unsigned nanodollars. */\n readonly settledNanoUsd: number\n /** How far past the cap it already is. */\n readonly overageNanoUsd: number\n readonly at: number\n}\n\n/**\n * Provisioning refused because the workspace is already past its compute cap.\n *\n * Correctable by design: every number the decision used is on the error, so a\n * product can render \"this workspace has spent $X of its $Y compute budget\" and\n * an operator can raise the cap or investigate without reading logs.\n *\n * This is the failure mode the module exists to produce. A platform billing\n * defect that used to end in a silent negative balance now ends in provisioning\n * stopping and something loud happening instead.\n */\nexport class ComputeBudgetExceededError extends Error {\n readonly workspaceId: string\n readonly limitNanoUsd: number\n readonly settledNanoUsd: number\n readonly overageNanoUsd: number\n\n constructor(refusal: ComputeBudgetRefusal) {\n super(\n `Compute budget exceeded for workspace ${refusal.workspaceId}: ` +\n `$${(refusal.settledNanoUsd / 1_000_000_000).toFixed(2)} settled against a cap of ` +\n `$${(refusal.limitNanoUsd / 1_000_000_000).toFixed(2)} ` +\n `(over by $${(refusal.overageNanoUsd / 1_000_000_000).toFixed(2)}). ` +\n 'No sandbox was provisioned. Raise the cap or reconcile the spend before retrying.',\n )\n this.name = 'ComputeBudgetExceededError'\n this.workspaceId = refusal.workspaceId\n this.limitNanoUsd = refusal.limitNanoUsd\n this.settledNanoUsd = refusal.settledNanoUsd\n this.overageNanoUsd = refusal.overageNanoUsd\n }\n}\n\n/**\n * A per-workspace cap on sandbox compute.\n *\n * `/billing`'s budget primitive caps MODEL keys, and it works because the\n * platform enforces the cap at the key it minted. Sandbox compute has no such\n * key: a box bills the shared company wallet, so nothing upstream refuses. This\n * carries the same shape to the one place a consumer can still act — the moment\n * before it asks for another box.\n *\n * `settledNanoUsd` is a callback rather than a number because the authority is\n * the platform ledger, not this package: the product reads the same rows it\n * hands the reconciler. Cache it if the read is expensive; a cap is a\n * coarse-grained control and a slightly stale total still refuses.\n */\nexport interface ComputeBudget {\n /** The cap, unsigned nanodollars. */\n readonly limitNanoUsd: number\n /** Cumulative settled compute spend for the workspace, unsigned nanodollars. */\n readonly settledNanoUsd: (workspaceId: string) => Promise<number> | number\n /**\n * Called on every refusal, before the error is thrown. This is the alert\n * seam: a refusal nobody hears is a product that silently stopped working.\n */\n readonly onRefusal?: (refusal: ComputeBudgetRefusal) => void\n /** Injectable clock (epoch ms). Default `Date.now`. */\n readonly now?: () => number\n}\n\n/**\n * Throw {@link ComputeBudgetExceededError} when the workspace is already past\n * its cap. Returns normally — and reads nothing — when no budget is configured.\n *\n * Deliberately a pre-check against spend ALREADY SETTLED, not a reservation\n * against spend about to happen: settlement lags provisioning by design (the\n * platform's durable settlement queue), so there is no instant at which a\n * consumer could hold an accurate running total. The cap therefore overshoots by\n * at most the unsettled tail, which is bounded by the box's own idle timeout.\n * A cap that refuses one box late is worth far more than one that cannot be\n * implemented honestly.\n */\nexport async function assertComputeBudget(\n budget: ComputeBudget | undefined,\n workspaceId: string,\n): Promise<void> {\n if (!budget) return\n const settledNanoUsd = await budget.settledNanoUsd(workspaceId)\n if (settledNanoUsd < budget.limitNanoUsd) return\n\n const refusal: ComputeBudgetRefusal = {\n workspaceId,\n limitNanoUsd: budget.limitNanoUsd,\n settledNanoUsd,\n overageNanoUsd: settledNanoUsd - budget.limitNanoUsd,\n at: (budget.now ?? Date.now)(),\n }\n budget.onRefusal?.(refusal)\n throw new ComputeBudgetExceededError(refusal)\n}\n\n// ── the /sandbox seam ─────────────────────────────────────────────────────────\n\n/**\n * What `/sandbox` reports once a box is provisioned, reused or resumed.\n *\n * Structurally identical to `SandboxProvisionedObservation` in `/sandbox`, and\n * deliberately re-declared rather than imported: `/spend` composes `/sandbox`,\n * so a type import in the other direction would invert the dependency. The two\n * are pinned together by a compile-time assignment in this module's tests.\n */\nexport interface SpendProvisionObservation {\n readonly workspaceId: string\n readonly userId?: string\n readonly sandboxId: string\n readonly boxKey?: string | undefined\n readonly idleTimeoutSeconds: number\n readonly maxLifetimeSeconds?: number | undefined\n readonly at: number\n}\n\n/**\n * The optional seam `EnsureWorkspaceSandboxOptions.spend` and the turn\n * primitives' `spend` option both accept. One object, wired in both places.\n */\nexport interface SandboxSpendSeam {\n beforeProvision?(input: { workspaceId: string; userId?: string }): Promise<void> | void\n onProvisioned?(observation: SpendProvisionObservation): Promise<void> | void\n /** Synchronous by contract — it sits on the turn path. See `createSandboxSpendHooks`. */\n onActivity?(input: { sandboxId: string; at: number }): void\n}\n\nexport interface SandboxSpendHooksOptions {\n /** Records box lifecycle. Omit to run the budget guard alone. */\n readonly ledger?: SpendLedger\n /** Refuses provisioning past a cap. Omit to record alone. */\n readonly budget?: ComputeBudget\n /**\n * Called when RECORDING fails. Recording is best-effort — a bookkeeping\n * failure must never take down the provisioning it is bookkeeping — so this\n * is the only place such a failure is visible. A refusal is NOT routed here;\n * refusals throw, by design.\n */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * Build the object to hand `ensureWorkspaceSandbox`'s `spend` option.\n *\n * Wiring it is the entire adoption cost: one field, and the product's boxes are\n * both budget-capped and recorded.\n */\nexport function createSandboxSpendHooks(options: SandboxSpendHooksOptions): SandboxSpendSeam {\n const { ledger, budget, onError } = options\n return {\n async beforeProvision(input) {\n await assertComputeBudget(budget, input.workspaceId)\n },\n async onProvisioned(observation) {\n if (!ledger) return\n try {\n await ledger.observeSandbox({\n sandboxId: observation.sandboxId,\n workspaceId: observation.workspaceId,\n idleTimeoutSeconds: observation.idleTimeoutSeconds,\n maxLifetimeSeconds: observation.maxLifetimeSeconds ?? null,\n at: observation.at,\n })\n } catch (err) {\n onError?.(err)\n }\n },\n onActivity(input) {\n if (!ledger) return\n // The turn path calls this synchronously and does not await it, so the\n // promise is settled here rather than escaping as an unhandled rejection.\n // Recording activity is a monotonic max, so a write that lands late — or\n // out of order against another turn's — still converges.\n void ledger.recordActivity(input.sandboxId, input.at).catch((err: unknown) => onError?.(err))\n },\n }\n}\n","/**\n * The budget-derived delegated mint — the platform's reservation contract as\n * one function.\n *\n * The platform RESERVES a delegated child key's budget against its parent's\n * REMAINING budget: an ask above remaining is a hard refusal (no amounts in\n * the response), which is how every delegated mint in a fleet product died\n * until the derivation landed (hardware-agent #165, 2026-10-09: a flat $25\n * default asked of a $5-remaining parent refused 100% of mints). Products\n * that mint delegated keys must derive the ask from what the platform\n * actually guarantees:\n *\n * - the parent's remaining budget is UNKNOWN → the configured ask stands\n * (the platform isn't reporting a ceiling; nothing better is knowable);\n * - remaining ≤ 0 → refuse with a correctable top-up error, before any\n * mint is attempted;\n * - otherwise → ask min(configured, remaining) floored to whole cents,\n * never below the platform's minimum child budget (the floor keeps the\n * mint VALID — a below-minimum ask is refused by the key API).\n *\n * Note the boundary honestly: with remaining between $0.01 and the minimum,\n * the derived ask (the floor) still exceeds remaining and the platform will\n * refuse it — that case is indistinguishable from exhausted for the caller\n * and surfaces through the same error path with the numbers attached.\n */\n\n/** The platform's minimum child-key budget. Asks below it are refused by the\n * key API, so the derivation never produces one. */\nexport const MIN_CHILD_KEY_BUDGET_USD = 0.5\n\n/** The source key is exhausted — the only refusal this contract throws.\n * Correctable by design: both numbers the decision used are on the error. */\nexport class ParentBudgetExhaustedError extends Error {\n readonly requestedUsd: number\n readonly parentRemainingUsd: number\n\n constructor(requestedUsd: number, parentRemainingUsd: number) {\n super(\n `workspace source key has no budget remaining ($${parentRemainingUsd.toFixed(2)}) — ` +\n `top up or raise its cap before sandbox turns (the mint would have asked $${requestedUsd.toFixed(2)})`,\n )\n this.name = 'ParentBudgetExhaustedError'\n this.requestedUsd = requestedUsd\n this.parentRemainingUsd = parentRemainingUsd\n }\n}\n\nexport interface DeriveChildKeyBudgetInput {\n /** The configured/default ask (the product's mint budget). Must be a\n * finite positive number. */\n readonly requestedUsd: number\n /** The parent's REMAINING budget as the platform's verify/key info\n * reports it. `null`/`undefined`/non-finite = unknown (not reported). */\n readonly parentRemainingUsd?: number | null\n /** Minimum child budget override. Default {@link MIN_CHILD_KEY_BUDGET_USD}. */\n readonly minChildUsd?: number\n}\n\n/** Derive the delegated child-key budget from the parent's remaining budget:\n * the ask the mint should make — never above a known remaining, never below\n * the platform minimum. Throws {@link ParentBudgetExhaustedError} when the\n * parent is exhausted, before any mint is attempted. */\nexport function deriveChildKeyBudgetUsd(input: DeriveChildKeyBudgetInput): number {\n const minChildUsd = input.minChildUsd ?? MIN_CHILD_KEY_BUDGET_USD\n if (!Number.isFinite(input.requestedUsd) || input.requestedUsd <= 0) {\n throw new Error(\n `deriveChildKeyBudgetUsd: requestedUsd must be a finite positive USD amount (got ${input.requestedUsd})`,\n )\n }\n if (!Number.isFinite(minChildUsd) || minChildUsd <= 0) {\n throw new Error(\n `deriveChildKeyBudgetUsd: minChildUsd must be a finite positive USD amount (got ${minChildUsd})`,\n )\n }\n const ceiling = input.parentRemainingUsd\n const known = typeof ceiling === 'number' && Number.isFinite(ceiling)\n if (!known) return input.requestedUsd\n if (ceiling <= 0) throw new ParentBudgetExhaustedError(input.requestedUsd, ceiling)\n // Never above remaining (floored to whole cents), never below the platform\n // minimum: max(min, min(requested, floor(remaining·100)/100)).\n return Math.max(minChildUsd, Math.min(input.requestedUsd, Math.floor(ceiling * 100) / 100))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+DO,SAAS,mBAAmB,QAAwB,OAAsC;AAC/F,MAAI,iBAAiB,OAAO;AAC5B,MAAI,YAAY,OAAO;AACvB,MAAI,qBAAqB,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,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AET,YAAY,cAAsB,oBAA4B;AAC5D;AAAA,MACE,kDAAkD,mBAAmB,QAAQ,CAAC,CAAC,qFACH,aAAa,QAAQ,CAAC,CAAC;AAAA,IACrG;AACA,SAAK,OAAO;AACZ,SAAK,eAAe;AACpB,SAAK,qBAAqB;AAAA,EAC5B;AACF;AAiBO,SAAS,wBAAwB,OAA0C;AAChF,QAAM,cAAc,MAAM,eAAe;AACzC,MAAI,CAAC,OAAO,SAAS,MAAM,YAAY,KAAK,MAAM,gBAAgB,GAAG;AACnE,UAAM,IAAI;AAAA,MACR,mFAAmF,MAAM,YAAY;AAAA,IACvG;AAAA,EACF;AACA,MAAI,CAAC,OAAO,SAAS,WAAW,KAAK,eAAe,GAAG;AACrD,UAAM,IAAI;AAAA,MACR,kFAAkF,WAAW;AAAA,IAC/F;AAAA,EACF;AACA,QAAM,UAAU,MAAM;AACtB,QAAM,QAAQ,OAAO,YAAY,YAAY,OAAO,SAAS,OAAO;AACpE,MAAI,CAAC,MAAO,QAAO,MAAM;AACzB,MAAI,WAAW,EAAG,OAAM,IAAI,2BAA2B,MAAM,cAAc,OAAO;AAGlF,SAAO,KAAK,IAAI,aAAa,KAAK,IAAI,MAAM,cAAc,KAAK,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;AAC5F;","names":[]}
|
package/dist/toolbelt/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// src/toolbelt/index.ts
|
|
2
2
|
import { spawn } from "child_process";
|
|
3
|
+
import { createInterface } from "readline";
|
|
3
4
|
function probeStdioToolProgram(options) {
|
|
4
5
|
const timeoutMs = options.timeoutMs ?? 15e3;
|
|
5
6
|
return new Promise((resolve, reject) => {
|
|
@@ -8,15 +9,16 @@ function probeStdioToolProgram(options) {
|
|
|
8
9
|
cwd: options.cwd,
|
|
9
10
|
stdio: ["pipe", "pipe", "pipe"]
|
|
10
11
|
});
|
|
11
|
-
|
|
12
|
+
const recent = (text) => text.slice(-2e3).trim() || "(empty)";
|
|
12
13
|
let stderr = "";
|
|
14
|
+
let stdoutSeen = "";
|
|
13
15
|
let settled = false;
|
|
14
16
|
let initializeReply = null;
|
|
15
|
-
const lines = [];
|
|
16
17
|
const finish = (run) => {
|
|
17
18
|
if (settled) return;
|
|
18
19
|
settled = true;
|
|
19
20
|
clearTimeout(timer);
|
|
21
|
+
rl.close();
|
|
20
22
|
try {
|
|
21
23
|
child.kill();
|
|
22
24
|
} catch {
|
|
@@ -25,55 +27,51 @@ function probeStdioToolProgram(options) {
|
|
|
25
27
|
};
|
|
26
28
|
const timer = setTimeout(
|
|
27
29
|
() => finish(() => reject(new Error(
|
|
28
|
-
`tool program probe timed out after ${timeoutMs}ms waiting for tools/list. stderr so far: ${stderr
|
|
30
|
+
`tool program probe timed out after ${timeoutMs}ms waiting for tools/list. stderr so far: ${recent(stderr)}; stdout so far: ${recent(stdoutSeen)}`
|
|
29
31
|
))),
|
|
30
32
|
timeoutMs
|
|
31
33
|
);
|
|
32
|
-
child.stdout
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
} else if (message.id === 2 && message.error !== void 0) {
|
|
62
|
-
finish(() => reject(new Error(
|
|
63
|
-
`tool program refused tools/list: ${JSON.stringify(message.error)}`
|
|
64
|
-
)));
|
|
65
|
-
}
|
|
34
|
+
const rl = createInterface({ input: child.stdout });
|
|
35
|
+
rl.on("line", (line) => {
|
|
36
|
+
const trimmed = line.trim();
|
|
37
|
+
if (!trimmed) return;
|
|
38
|
+
stdoutSeen = (stdoutSeen + trimmed + "\n").slice(-2e3);
|
|
39
|
+
let message;
|
|
40
|
+
try {
|
|
41
|
+
message = JSON.parse(trimmed);
|
|
42
|
+
} catch {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (message.method !== void 0) return;
|
|
46
|
+
if (message.id === 1) initializeReply = message.result ?? null;
|
|
47
|
+
if (message.id === 2 && message.result !== void 0 && message.error === void 0) {
|
|
48
|
+
const rawTools = message.result.tools;
|
|
49
|
+
const tools = Array.isArray(rawTools) ? rawTools.filter((t) => !!t && typeof t === "object" && typeof t.name === "string").map((t) => {
|
|
50
|
+
const tool = t;
|
|
51
|
+
return {
|
|
52
|
+
name: tool.name,
|
|
53
|
+
...tool.description !== void 0 ? { description: tool.description } : {},
|
|
54
|
+
...tool.inputSchema !== void 0 ? { inputSchema: tool.inputSchema } : {},
|
|
55
|
+
...tool.annotations !== void 0 ? { annotations: tool.annotations } : {}
|
|
56
|
+
};
|
|
57
|
+
}) : [];
|
|
58
|
+
finish(() => resolve({ tools, initializeReply }));
|
|
59
|
+
} else if (message.id === 2 && message.error !== void 0) {
|
|
60
|
+
finish(() => reject(new Error(
|
|
61
|
+
`tool program refused tools/list: ${JSON.stringify(message.error)}`
|
|
62
|
+
)));
|
|
66
63
|
}
|
|
67
64
|
});
|
|
65
|
+
child.stdout.setEncoding("utf8");
|
|
68
66
|
child.stderr.setEncoding("utf8");
|
|
69
67
|
child.stderr.on("data", (chunk) => {
|
|
70
|
-
stderr
|
|
68
|
+
stderr = (stderr + chunk).slice(-2e3);
|
|
71
69
|
});
|
|
72
70
|
child.on("error", (error) => finish(() => reject(new Error(
|
|
73
71
|
`tool program probe failed to spawn ${options.program}: ${error.message}`
|
|
74
72
|
))));
|
|
75
73
|
child.on("exit", (code, signal) => finish(() => reject(new Error(
|
|
76
|
-
`tool program exited before answering tools/list (code ${code}${signal ? `, signal ${signal}` : ""}). stderr: ${stderr
|
|
74
|
+
`tool program exited before answering tools/list (code ${code}${signal ? `, signal ${signal}` : ""}). stderr: ${recent(stderr)}`
|
|
77
75
|
))));
|
|
78
76
|
const send = (payload) => {
|
|
79
77
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/toolbelt/index.ts"],"sourcesContent":["/**\n * The toolbelt parity gate — one manifest, every target, enforced at build time.\n *\n * A product with an embedded tool program (a stdio MCP the sandbox spawns)\n * has two representations of its tool surface: the manifest it authors and\n * the program that actually answers `tools/list`. Every hour of pain in the\n * fleet's toolbelt history was those two lists disagreeing — a verb present\n * in one target and absent from the other shipped green and failed in\n * production (hardware-agent #10155 class). This module turns that drift\n * class into a red test: spawn the program, read its real surface, diff it\n * against the manifest, and name every disagreement.\n *\n * Substrate-free by design: Node builtins only, no test-framework\n * dependency, no MCP SDK. `probeStdioToolProgram` speaks just enough\n * JSON-RPC (initialize → initialized → tools/list, replies matched by id,\n * notifications ignored) for a zero-dependency embedded program; the diff\n * and the assert are pure functions any runner (vitest, node:test, a tsx\n * script) can call.\n *\n * Canonical consumer shape:\n *\n * ```ts\n * import { assertToolbeltParity, probeStdioToolProgram } from '@tangle-network/agent-app/toolbelt'\n *\n * const probed = await probeStdioToolProgram({ program: programPath, env })\n * assertToolbeltParity(TOOLBELT, probed.tools) // throws with the named diff\n * ```\n */\nimport { spawn } from 'node:child_process'\n\n/** One authored tool in the product's manifest — the ONE source of truth the\n * generated program and every derived surface (allowlists, prompt tool\n * tables, dashboards) must agree with. */\nexport interface ToolbeltManifestTool {\n readonly name: string\n /** AAA-standard description (what / example / when NOT). Parity requires the\n * program to serve it byte-identical — truncation at a bundle boundary is\n * drift, not formatting. */\n readonly description: string\n /** JSON Schema for the tool's input. Compared structurally (key order\n * insensitive) when either side declares one. */\n readonly inputSchema?: unknown\n /** MCP tool annotations (readOnlyHint, …). Compared structurally when the\n * manifest declares them. */\n readonly annotations?: unknown\n /** Product-defined transport tag (`pure` | `http` | …). Not part of the\n * wire surface; carried so derived surfaces can key off the manifest. */\n readonly transport?: string\n}\n\n/** A tool as the spawned program actually listed it. */\nexport interface ProbedTool {\n readonly name: string\n readonly description?: string\n readonly inputSchema?: unknown\n readonly annotations?: unknown\n}\n\n/** What `probeStdioToolProgram` saw. `serverInfo`/`raw` are included so a\n * failed probe can name the layer (the diagnosability rule: never swallow). */\nexport interface ToolProgramProbe {\n readonly tools: readonly ProbedTool[]\n readonly initializeReply: Record<string, unknown> | null\n}\n\nexport interface ProbeStdioToolProgramOptions {\n /** Path to the program to spawn. Spawned with the current Node executable. */\n readonly program: string\n /** Extra argv after the program path. */\n readonly args?: readonly string[]\n /** Environment for the child. Defaults to `process.env`. */\n readonly env?: NodeJS.ProcessEnv\n /** Working directory for the child. */\n readonly cwd?: string\n /** Wall-clock ceiling for the whole probe. Default 15s. */\n readonly timeoutMs?: number\n}\n\n/** Spawn the embedded tool program and read its REAL tool surface. */\nexport function probeStdioToolProgram(options: ProbeStdioToolProgramOptions): Promise<ToolProgramProbe> {\n const timeoutMs = options.timeoutMs ?? 15_000\n return new Promise<ToolProgramProbe>((resolve, reject) => {\n const child = spawn(process.execPath, [options.program, ...(options.args ?? [])], {\n env: options.env ?? process.env,\n cwd: options.cwd,\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n let stdout = ''\n let stderr = ''\n let settled = false\n let initializeReply: Record<string, unknown> | null = null\n const lines: string[] = []\n\n const finish = (run: () => void) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n try { child.kill() } catch { /* already gone */ }\n run()\n }\n\n const timer = setTimeout(\n () => finish(() => reject(new Error(\n `tool program probe timed out after ${timeoutMs}ms waiting for tools/list. ` +\n `stderr so far: ${stderr.trim().slice(0, 2000) || '(empty)'}; ` +\n `stdout so far: ${stdout.trim().slice(0, 2000) || '(empty)'}`,\n ))),\n timeoutMs,\n )\n\n child.stdout.setEncoding('utf8')\n child.stdout.on('data', (chunk: string) => {\n stdout += chunk\n let index: number\n while ((index = stdout.indexOf('\\n')) >= 0) {\n const line = stdout.slice(0, index).trim()\n stdout = stdout.slice(index + 1)\n if (!line) continue\n lines.push(line)\n let message: Record<string, unknown>\n try {\n message = JSON.parse(line) as Record<string, unknown>\n } catch {\n continue // a banner line, not JSON-RPC\n }\n if (message.method !== undefined) continue // notification from server\n if (message.id === 1) initializeReply = message.result as Record<string, unknown> ?? null\n if (message.id === 2 && message.result !== undefined && message.error === undefined) {\n const rawTools = (message.result as { tools?: unknown }).tools\n const tools: ProbedTool[] = Array.isArray(rawTools)\n ? rawTools.filter((t): t is Record<string, unknown> => !!t && typeof t === 'object' && typeof (t as { name?: unknown }).name === 'string')\n .map((t) => {\n const tool = t as unknown as { name: string; description?: string; inputSchema?: unknown; annotations?: unknown }\n return {\n name: tool.name,\n ...(tool.description !== undefined ? { description: tool.description } : {}),\n ...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),\n ...(tool.annotations !== undefined ? { annotations: tool.annotations } : {}),\n }\n })\n : []\n finish(() => resolve({ tools, initializeReply }))\n } else if (message.id === 2 && message.error !== undefined) {\n finish(() => reject(new Error(\n `tool program refused tools/list: ${JSON.stringify(message.error)}`,\n )))\n }\n }\n })\n child.stderr.setEncoding('utf8')\n child.stderr.on('data', (chunk: string) => { stderr += chunk })\n child.on('error', (error) => finish(() => reject(new Error(\n `tool program probe failed to spawn ${options.program}: ${error.message}`,\n ))))\n child.on('exit', (code, signal) => finish(() => reject(new Error(\n `tool program exited before answering tools/list (code ${code}${signal ? `, signal ${signal}` : ''}). ` +\n `stderr: ${stderr.trim().slice(0, 2000) || '(empty)'}`,\n ))))\n\n // Minimal MCP handshake: initialize → initialized → tools/list. Replies\n // are matched by id; a program that never replies to initialize still\n // resolves the probe when its tools/list reply arrives.\n const send = (payload: unknown) => { try { child.stdin.write(JSON.stringify(payload) + '\\n') } catch { /* closed; exit handler reports */ } }\n send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'toolbelt-parity', version: '0.0.0' } } })\n send({ jsonrpc: '2.0', method: 'notifications/initialized' })\n send({ jsonrpc: '2.0', id: 2, method: 'tools/list' })\n })\n}\n\n/** Structural equality with sorted keys — two JSON schemas are the same\n * contract regardless of key order. */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n\n/** Field-level drift between the manifest and the program's real surface. */\nexport interface ToolbeltFieldDrift {\n readonly name: string\n readonly manifest: unknown\n readonly program: unknown\n}\n\n/** The named diff. Every array is sorted; empty arrays mean agreement. */\nexport interface ToolbeltParityDiff {\n readonly ok: boolean\n /** Manifest tools the program did not list (the #10155 class: the verb\n * exists in the manifest, absent from the running surface). */\n readonly missingFromProgram: readonly string[]\n /** Tools the program listed that no manifest entry owns. */\n readonly unknownToManifest: readonly string[]\n /** Tools whose served description is not byte-identical to the manifest. */\n readonly descriptionDrift: readonly ToolbeltFieldDrift[]\n /** Tools whose served input schema differs structurally from the manifest. */\n readonly schemaDrift: readonly ToolbeltFieldDrift[]\n /** Tools whose served annotations differ structurally from the manifest. */\n readonly annotationDrift: readonly ToolbeltFieldDrift[]\n}\n\n/** Diff a spawned program's real surface against the authored manifest. */\nexport function toolbeltParityDiff(\n manifest: readonly ToolbeltManifestTool[],\n listed: readonly ProbedTool[],\n): ToolbeltParityDiff {\n const byName = new Map(manifest.map((tool) => [tool.name, tool]))\n const listedByName = new Map(listed.map((tool) => [tool.name, tool]))\n const missingFromProgram = manifest\n .filter((tool) => !listedByName.has(tool.name))\n .map((tool) => tool.name)\n .sort()\n const unknownToManifest = listed\n .filter((tool) => !byName.has(tool.name))\n .map((tool) => tool.name)\n .sort()\n const descriptionDrift: ToolbeltFieldDrift[] = []\n const schemaDrift: ToolbeltFieldDrift[] = []\n const annotationDrift: ToolbeltFieldDrift[] = []\n for (const tool of manifest) {\n const served = listedByName.get(tool.name)\n if (!served) continue\n if (served.description !== tool.description) {\n descriptionDrift.push({ name: tool.name, manifest: tool.description, program: served.description ?? null })\n }\n const manifestSchema = tool.inputSchema\n if (manifestSchema !== undefined || served.inputSchema !== undefined) {\n if (stableStringify(manifestSchema) !== stableStringify(served.inputSchema)) {\n schemaDrift.push({ name: tool.name, manifest: manifestSchema ?? null, program: served.inputSchema ?? null })\n }\n }\n const manifestAnnotations = tool.annotations\n if (manifestAnnotations !== undefined || served.annotations !== undefined) {\n if (stableStringify(manifestAnnotations) !== stableStringify(served.annotations)) {\n annotationDrift.push({ name: tool.name, manifest: manifestAnnotations ?? null, program: served.annotations ?? null })\n }\n }\n }\n const ok = missingFromProgram.length === 0\n && unknownToManifest.length === 0\n && descriptionDrift.length === 0\n && schemaDrift.length === 0\n && annotationDrift.length === 0\n return {\n ok,\n missingFromProgram,\n unknownToManifest,\n descriptionDrift,\n schemaDrift,\n annotationDrift,\n }\n}\n\n/** Render a diff as one actionable report — every drift named, never a bare count. */\nexport function formatToolbeltParityDiff(diff: ToolbeltParityDiff): string {\n if (diff.ok) return 'toolbelt parity: the program is the manifest'\n const lines = ['toolbelt parity FAILED — the program and the manifest disagree:']\n if (diff.missingFromProgram.length > 0) {\n lines.push(` missing from the program (in the manifest, NOT served): ${diff.missingFromProgram.join(', ')}`)\n }\n if (diff.unknownToManifest.length > 0) {\n lines.push(` unknown to the manifest (served, NOT authored): ${diff.unknownToManifest.join(', ')}`)\n }\n for (const drift of diff.descriptionDrift) {\n lines.push(` description drift on \"${drift.name}\":`)\n lines.push(` manifest: ${JSON.stringify(drift.manifest)}`)\n lines.push(` program: ${JSON.stringify(drift.program)}`)\n }\n for (const drift of diff.schemaDrift) {\n lines.push(` input-schema drift on \"${drift.name}\":`)\n lines.push(` manifest: ${stableStringify(drift.manifest)}`)\n lines.push(` program: ${stableStringify(drift.program)}`)\n }\n for (const drift of diff.annotationDrift) {\n lines.push(` annotation drift on \"${drift.name}\":`)\n lines.push(` manifest: ${stableStringify(drift.manifest)}`)\n lines.push(` program: ${stableStringify(drift.program)}`)\n }\n lines.push(' Fix the ONE manifest (or the generator that derives the program from it) — never patch a second list.')\n return lines.join('\\n')\n}\n\n/** Thrown by {@link assertToolbeltParity} with the full formatted diff. */\nexport class ToolbeltParityError extends Error {\n readonly diff: ToolbeltParityDiff\n constructor(diff: ToolbeltParityDiff) {\n super(formatToolbeltParityDiff(diff))\n this.name = 'ToolbeltParityError'\n this.diff = diff\n }\n}\n\n/** Assert parity: same names, byte-identical descriptions, structurally equal\n * schemas and annotations. Throws {@link ToolbeltParityError} with every\n * disagreement named — a red build, not a production silence. */\nexport function assertToolbeltParity(\n manifest: readonly ToolbeltManifestTool[],\n listed: readonly ProbedTool[],\n): void {\n const diff = toolbeltParityDiff(manifest, listed)\n if (!diff.ok) throw new ToolbeltParityError(diff)\n}\n"],"mappings":";AA4BA,SAAS,aAAa;AAmDf,SAAS,sBAAsB,SAAkE;AACtG,QAAM,YAAY,QAAQ,aAAa;AACvC,SAAO,IAAI,QAA0B,CAAC,SAAS,WAAW;AACxD,UAAM,QAAQ,MAAM,QAAQ,UAAU,CAAC,QAAQ,SAAS,GAAI,QAAQ,QAAQ,CAAC,CAAE,GAAG;AAAA,MAChF,KAAK,QAAQ,OAAO,QAAQ;AAAA,MAC5B,KAAK,QAAQ;AAAA,MACb,OAAO,CAAC,QAAQ,QAAQ,MAAM;AAAA,IAChC,CAAC;AACD,QAAI,SAAS;AACb,QAAI,SAAS;AACb,QAAI,UAAU;AACd,QAAI,kBAAkD;AACtD,UAAM,QAAkB,CAAC;AAEzB,UAAM,SAAS,CAAC,QAAoB;AAClC,UAAI,QAAS;AACb,gBAAU;AACV,mBAAa,KAAK;AAClB,UAAI;AAAE,cAAM,KAAK;AAAA,MAAE,QAAQ;AAAA,MAAqB;AAChD,U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AAM,KAAK,iBAAiB,KAAK,UAAU,MAAM,QAAQ,CAAC,EAAE;AAC5D,UAAM,KAAK,iBAAiB,KAAK,UAAU,MAAM,OAAO,CAAC,EAAE;AAAA,EAC7D;AACA,aAAW,SAAS,KAAK,aAAa;AACpC,UAAM,KAAK,4BAA4B,MAAM,IAAI,IAAI;AACrD,UAAM,KAAK,iBAAiB,gBAAgB,MAAM,QAAQ,CAAC,EAAE;AAC7D,UAAM,KAAK,iBAAiB,gBAAgB,MAAM,OAAO,CAAC,EAAE;AAAA,EAC9D;AACA,aAAW,SAAS,KAAK,iBAAiB;AACxC,UAAM,KAAK,0BAA0B,MAAM,IAAI,IAAI;AACnD,UAAM,KAAK,iBAAiB,gBAAgB,MAAM,QAAQ,CAAC,EAAE;AAC7D,UAAM,KAAK,iBAAiB,gBAAgB,MAAM,OAAO,CAAC,EAAE;AAAA,EAC9D;AACA,QAAM,KAAK,8GAAyG;AACpH,SAAO,MAAM,KAAK,IAAI;AACxB;AAGO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EACpC;AAAA,EACT,YAAY,MAA0B;AACpC,UAAM,yBAAyB,IAAI,CAAC;AACpC,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAKO,SAAS,qBACd,UACA,QACM;AACN,QAAM,OAAO,mBAAmB,UAAU,MAAM;AAChD,MAAI,CAAC,KAAK,GAAI,OAAM,IAAI,oBAAoB,IAAI;AAClD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/toolbelt/index.ts"],"sourcesContent":["/**\n * The toolbelt parity gate — one manifest, every target, enforced at build time.\n *\n * A product with an embedded tool program (a stdio MCP the sandbox spawns)\n * has two representations of its tool surface: the manifest it authors and\n * the program that actually answers `tools/list`. Every hour of pain in the\n * fleet's toolbelt history was those two lists disagreeing — a verb present\n * in one target and absent from the other shipped green and failed in\n * production (hardware-agent #10155 class). This module turns that drift\n * class into a red test: spawn the program, read its real surface, diff it\n * against the manifest, and name every disagreement.\n *\n * Substrate-free by design: Node builtins only, no test-framework\n * dependency, no MCP SDK. `probeStdioToolProgram` speaks just enough\n * JSON-RPC (initialize → initialized → tools/list, replies matched by id,\n * notifications ignored) for a zero-dependency embedded program; the diff\n * and the assert are pure functions any runner (vitest, node:test, a tsx\n * script) can call.\n *\n * Canonical consumer shape:\n *\n * ```ts\n * import { assertToolbeltParity, probeStdioToolProgram } from '@tangle-network/agent-app/toolbelt'\n *\n * const probed = await probeStdioToolProgram({ program: programPath, env })\n * assertToolbeltParity(TOOLBELT, probed.tools) // throws with the named diff\n * ```\n */\nimport { spawn } from 'node:child_process'\nimport { createInterface } from 'node:readline'\n\n/** One authored tool in the product's manifest — the ONE source of truth the\n * generated program and every derived surface (allowlists, prompt tool\n * tables, dashboards) must agree with. */\nexport interface ToolbeltManifestTool {\n readonly name: string\n /** AAA-standard description (what / example / when NOT). Parity requires the\n * program to serve it byte-identical — truncation at a bundle boundary is\n * drift, not formatting. */\n readonly description: string\n /** JSON Schema for the tool's input. Compared structurally (key order\n * insensitive) when either side declares one. */\n readonly inputSchema?: unknown\n /** MCP tool annotations (readOnlyHint, …). Compared structurally when the\n * manifest declares them. */\n readonly annotations?: unknown\n /** Product-defined transport tag (`pure` | `http` | …). Not part of the\n * wire surface; carried so derived surfaces can key off the manifest. */\n readonly transport?: string\n}\n\n/** A tool as the spawned program actually listed it. */\nexport interface ProbedTool {\n readonly name: string\n readonly description?: string\n readonly inputSchema?: unknown\n readonly annotations?: unknown\n}\n\n/** What `probeStdioToolProgram` saw. `serverInfo`/`raw` are included so a\n * failed probe can name the layer (the diagnosability rule: never swallow). */\nexport interface ToolProgramProbe {\n readonly tools: readonly ProbedTool[]\n readonly initializeReply: Record<string, unknown> | null\n}\n\nexport interface ProbeStdioToolProgramOptions {\n /** Path to the program to spawn. Spawned with the current Node executable. */\n readonly program: string\n /** Extra argv after the program path. */\n readonly args?: readonly string[]\n /** Environment for the child. Defaults to `process.env`. */\n readonly env?: NodeJS.ProcessEnv\n /** Working directory for the child. */\n readonly cwd?: string\n /** Wall-clock ceiling for the whole probe. Default 15s. */\n readonly timeoutMs?: number\n}\n\n/** Spawn the embedded tool program and read its REAL tool surface. */\nexport function probeStdioToolProgram(options: ProbeStdioToolProgramOptions): Promise<ToolProgramProbe> {\n const timeoutMs = options.timeoutMs ?? 15_000\n return new Promise<ToolProgramProbe>((resolve, reject) => {\n const child = spawn(process.execPath, [options.program, ...(options.args ?? [])], {\n env: options.env ?? process.env,\n cwd: options.cwd,\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n // Diagnostics only: the last 2 KB each side ever emitted, so a failed\n // probe names the layer instead of an unprocessed tail.\n const recent = (text: string) => text.slice(-2000).trim() || '(empty)'\n let stderr = ''\n let stdoutSeen = ''\n let settled = false\n let initializeReply: Record<string, unknown> | null = null\n\n const finish = (run: () => void) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n rl.close()\n try { child.kill() } catch { /* already gone */ }\n run()\n }\n\n const timer = setTimeout(\n () => finish(() => reject(new Error(\n `tool program probe timed out after ${timeoutMs}ms waiting for tools/list. ` +\n `stderr so far: ${recent(stderr)}; stdout so far: ${recent(stdoutSeen)}`,\n ))),\n timeoutMs,\n )\n\n // Line-delimited JSON-RPC over stdio: readline owns the buffering (no\n // manual byte scanning), and every line seen is also diagnostics.\n const rl = createInterface({ input: child.stdout })\n rl.on('line', (line: string) => {\n const trimmed = line.trim()\n if (!trimmed) return\n stdoutSeen = (stdoutSeen + trimmed + '\\n').slice(-2000)\n let message: Record<string, unknown>\n try {\n message = JSON.parse(trimmed) as Record<string, unknown>\n } catch {\n return // a banner line, not JSON-RPC\n }\n if (message.method !== undefined) return // notification from server\n if (message.id === 1) initializeReply = message.result as Record<string, unknown> ?? null\n if (message.id === 2 && message.result !== undefined && message.error === undefined) {\n const rawTools = (message.result as { tools?: unknown }).tools\n const tools: ProbedTool[] = Array.isArray(rawTools)\n ? rawTools.filter((t): t is Record<string, unknown> => !!t && typeof t === 'object' && typeof (t as { name?: unknown }).name === 'string')\n .map((t) => {\n const tool = t as unknown as { name: string; description?: string; inputSchema?: unknown; annotations?: unknown }\n return {\n name: tool.name,\n ...(tool.description !== undefined ? { description: tool.description } : {}),\n ...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),\n ...(tool.annotations !== undefined ? { annotations: tool.annotations } : {}),\n }\n })\n : []\n finish(() => resolve({ tools, initializeReply }))\n } else if (message.id === 2 && message.error !== undefined) {\n finish(() => reject(new Error(\n `tool program refused tools/list: ${JSON.stringify(message.error)}`,\n )))\n }\n })\n child.stdout.setEncoding('utf8')\n child.stderr.setEncoding('utf8')\n child.stderr.on('data', (chunk: string) => { stderr = (stderr + chunk).slice(-2000) })\n child.on('error', (error) => finish(() => reject(new Error(\n `tool program probe failed to spawn ${options.program}: ${error.message}`,\n ))))\n child.on('exit', (code, signal) => finish(() => reject(new Error(\n `tool program exited before answering tools/list (code ${code}${signal ? `, signal ${signal}` : ''}). ` +\n `stderr: ${recent(stderr)}`,\n ))))\n\n // Minimal MCP handshake: initialize → initialized → tools/list. Replies\n // are matched by id; a program that never replies to initialize still\n // resolves the probe when its tools/list reply arrives.\n const send = (payload: unknown) => { try { child.stdin.write(JSON.stringify(payload) + '\\n') } catch { /* closed; exit handler reports */ } }\n send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'toolbelt-parity', version: '0.0.0' } } })\n send({ jsonrpc: '2.0', method: 'notifications/initialized' })\n send({ jsonrpc: '2.0', id: 2, method: 'tools/list' })\n })\n}\n\n/** Structural equality with sorted keys — two JSON schemas are the same\n * contract regardless of key order. */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n\n/** Field-level drift between the manifest and the program's real surface. */\nexport interface ToolbeltFieldDrift {\n readonly name: string\n readonly manifest: unknown\n readonly program: unknown\n}\n\n/** The named diff. Every array is sorted; empty arrays mean agreement. */\nexport interface ToolbeltParityDiff {\n readonly ok: boolean\n /** Manifest tools the program did not list (the #10155 class: the verb\n * exists in the manifest, absent from the running surface). */\n readonly missingFromProgram: readonly string[]\n /** Tools the program listed that no manifest entry owns. */\n readonly unknownToManifest: readonly string[]\n /** Tools whose served description is not byte-identical to the manifest. */\n readonly descriptionDrift: readonly ToolbeltFieldDrift[]\n /** Tools whose served input schema differs structurally from the manifest. */\n readonly schemaDrift: readonly ToolbeltFieldDrift[]\n /** Tools whose served annotations differ structurally from the manifest. */\n readonly annotationDrift: readonly ToolbeltFieldDrift[]\n}\n\n/** Diff a spawned program's real surface against the authored manifest. */\nexport function toolbeltParityDiff(\n manifest: readonly ToolbeltManifestTool[],\n listed: readonly ProbedTool[],\n): ToolbeltParityDiff {\n const byName = new Map(manifest.map((tool) => [tool.name, tool]))\n const listedByName = new Map(listed.map((tool) => [tool.name, tool]))\n const missingFromProgram = manifest\n .filter((tool) => !listedByName.has(tool.name))\n .map((tool) => tool.name)\n .sort()\n const unknownToManifest = listed\n .filter((tool) => !byName.has(tool.name))\n .map((tool) => tool.name)\n .sort()\n const descriptionDrift: ToolbeltFieldDrift[] = []\n const schemaDrift: ToolbeltFieldDrift[] = []\n const annotationDrift: ToolbeltFieldDrift[] = []\n for (const tool of manifest) {\n const served = listedByName.get(tool.name)\n if (!served) continue\n if (served.description !== tool.description) {\n descriptionDrift.push({ name: tool.name, manifest: tool.description, program: served.description ?? null })\n }\n const manifestSchema = tool.inputSchema\n if (manifestSchema !== undefined || served.inputSchema !== undefined) {\n if (stableStringify(manifestSchema) !== stableStringify(served.inputSchema)) {\n schemaDrift.push({ name: tool.name, manifest: manifestSchema ?? null, program: served.inputSchema ?? null })\n }\n }\n const manifestAnnotations = tool.annotations\n if (manifestAnnotations !== undefined || served.annotations !== undefined) {\n if (stableStringify(manifestAnnotations) !== stableStringify(served.annotations)) {\n annotationDrift.push({ name: tool.name, manifest: manifestAnnotations ?? null, program: served.annotations ?? null })\n }\n }\n }\n const ok = missingFromProgram.length === 0\n && unknownToManifest.length === 0\n && descriptionDrift.length === 0\n && schemaDrift.length === 0\n && annotationDrift.length === 0\n return {\n ok,\n missingFromProgram,\n unknownToManifest,\n descriptionDrift,\n schemaDrift,\n annotationDrift,\n }\n}\n\n/** Render a diff as one actionable report — every drift named, never a bare count. */\nexport function formatToolbeltParityDiff(diff: ToolbeltParityDiff): string {\n if (diff.ok) return 'toolbelt parity: the program is the manifest'\n const lines = ['toolbelt parity FAILED — the program and the manifest disagree:']\n if (diff.missingFromProgram.length > 0) {\n lines.push(` missing from the program (in the manifest, NOT served): ${diff.missingFromProgram.join(', ')}`)\n }\n if (diff.unknownToManifest.length > 0) {\n lines.push(` unknown to the manifest (served, NOT authored): ${diff.unknownToManifest.join(', ')}`)\n }\n for (const drift of diff.descriptionDrift) {\n lines.push(` description drift on \"${drift.name}\":`)\n lines.push(` manifest: ${JSON.stringify(drift.manifest)}`)\n lines.push(` program: ${JSON.stringify(drift.program)}`)\n }\n for (const drift of diff.schemaDrift) {\n lines.push(` input-schema drift on \"${drift.name}\":`)\n lines.push(` manifest: ${stableStringify(drift.manifest)}`)\n lines.push(` program: ${stableStringify(drift.program)}`)\n }\n for (const drift of diff.annotationDrift) {\n lines.push(` annotation drift on \"${drift.name}\":`)\n lines.push(` manifest: ${stableStringify(drift.manifest)}`)\n lines.push(` program: ${stableStringify(drift.program)}`)\n }\n lines.push(' Fix the ONE manifest (or the generator that derives the program from it) — never patch a second list.')\n return lines.join('\\n')\n}\n\n/** Thrown by {@link assertToolbeltParity} with the full formatted diff. */\nexport class ToolbeltParityError extends Error {\n readonly diff: ToolbeltParityDiff\n constructor(diff: ToolbeltParityDiff) {\n super(formatToolbeltParityDiff(diff))\n this.name = 'ToolbeltParityError'\n this.diff = diff\n }\n}\n\n/** Assert parity: same names, byte-identical descriptions, structurally equal\n * schemas and annotations. Throws {@link ToolbeltParityError} with every\n * disagreement named — a red build, not a production silence. */\nexport function assertToolbeltParity(\n manifest: readonly ToolbeltManifestTool[],\n listed: readonly ProbedTool[],\n): void {\n const diff = toolbeltParityDiff(manifest, listed)\n if (!diff.ok) throw new ToolbeltParityError(diff)\n}\n"],"mappings":";AA4BA,SAAS,aAAa;AACtB,SAAS,uBAAuB;AAmDzB,SAAS,sBAAsB,SAAkE;AACtG,QAAM,YAAY,QAAQ,aAAa;AACvC,SAAO,IAAI,QAA0B,CAAC,SAAS,WAAW;AACxD,UAAM,QAAQ,MAAM,QAAQ,UAAU,CAAC,QAAQ,SAAS,GAAI,QAAQ,QAAQ,CAAC,CAAE,GAAG;AAAA,MAChF,KAAK,QAAQ,OAAO,QAAQ;AAAA,MAC5B,KAAK,QAAQ;AAAA,MACb,OAAO,CAAC,QAAQ,QAAQ,MAAM;AAAA,IAChC,CAAC;AAGD,UAAM,SAAS,CAAC,SAAiB,KAAK,MAAM,IAAK,EAAE,KAAK,KAAK;AAC7D,QAAI,SAAS;AACb,QAAI,aAAa;AACjB,QAAI,UAAU;AACd,QAAI,kBAAkD;AAEtD,UAAM,SAAS,CAAC,QAAoB;AAClC,UAAI,QAAS;AACb,gBAAU;AACV,mBAAa,KAAK;AAClB,SAAG,MAAM;AACT,UAAI;AAAE,cAAM,KAAK;AAAA,MAAE,QAAQ;AAAA,MAAqB;AAChD,UAAI;AAAA,IACN;AAEA,UAAM,QAAQ;AAAA,MACZ,MAAM,OAAO,MAAM,OAAO,IAAI;AAAA,QAC5B,sCAAsC,SAAS,6CAC7B,OAAO,MAAM,CAAC,oBAAoB,OAAO,UAAU,CAAC;AAAA,MACxE,CAAC,CAAC;AAAA,MACF;AAAA,IACF;AAIA,UAAM,KAAK,gBAAgB,EAAE,OAAO,MAAM,O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MAAM,IAAI,IAAI;AACnD,UAAM,KAAK,iBAAiB,gBAAgB,MAAM,QAAQ,CAAC,EAAE;AAC7D,UAAM,KAAK,iBAAiB,gBAAgB,MAAM,OAAO,CAAC,EAAE;AAAA,EAC9D;AACA,QAAM,KAAK,8GAAyG;AACpH,SAAO,MAAM,KAAK,IAAI;AACxB;AAGO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EACpC;AAAA,EACT,YAAY,MAA0B;AACpC,UAAM,yBAAyB,IAAI,CAAC;AACpC,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAKO,SAAS,qBACd,UACA,QACM;AACN,QAAM,OAAO,mBAAmB,UAAU,MAAM;AAChD,MAAI,CAAC,KAAK,GAAI,OAAM,IAAI,oBAAoB,IAAI;AAClD;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-app",
|
|
3
|
-
"version": "0.60.
|
|
3
|
+
"version": "0.60.190",
|
|
4
4
|
"packageManager": "pnpm@11.24.0",
|
|
5
5
|
"description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
|
|
6
6
|
"keywords": [
|
|
@@ -709,7 +709,7 @@
|
|
|
709
709
|
"@tangle-network/agent-gateway": "0.11.4",
|
|
710
710
|
"@tangle-network/agent-integrations": "0.75.0",
|
|
711
711
|
"@tangle-network/agent-interface": "5.2.1",
|
|
712
|
-
"@tangle-network/agent-knowledge": "22.0.
|
|
712
|
+
"@tangle-network/agent-knowledge": "22.0.3",
|
|
713
713
|
"@tangle-network/agent-profile-materialize": "0.25.2",
|
|
714
714
|
"@tangle-network/agent-runtime": "0.325.0",
|
|
715
715
|
"@tangle-network/brand": "1.26.0",
|