stitchkit 0.136.5 → 0.136.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -15,6 +15,13 @@ additive**; the first breaking change landed in 0.10.0. Grep the file for
15
15
 
16
16
  ## [Unreleased]
17
17
 
18
+ ## [0.136.6] - 2026-12-03
19
+
20
+ ### Fixed
21
+
22
+ - `stitchkit/spend` — `reconcilePendingSpend` accepts `maxPendingAgeMs` (`ReconcilePendingSpendOptions`, a positive safe integer validated upfront with `TypeError`): when a gateway's reconciler still returns `undefined` ("not yet", such as OpenRouter's `404` or absent `total_cost`) and at least `maxPendingAgeMs` has elapsed since `record.receipt.at` (or `record.attempt.startedAt` when no receipt exists), `reconcilePendingSpend` settles a rank-3 receipt with `costStatus: 'unknown'` and `failureCode: 'price-never-reported'` so permanently unpriced rows leave `pendingCosts` instead of accumulating forever. Before `maxPendingAgeMs` (or when omitted), `undefined` still leaves the row `pending`; reconciler throws (`failed` / `onError`), gateways without a configured reconciler, and answers that return a price (including cancelled generations with `total_cost`, even past `maxPendingAgeMs`) keep their existing behaviour; invalid record timestamps route to `failed` / `onError`, while a broken `now()` clock or `store.settle` failure still rejects without calling `onError`. `mergeSpendReceipt` also resolves equal-rank exact-timestamp ties in favour of a factual cost (`reported` or `free`) and symmetrically prevents a non-factual rank-3 reconciler receipt from adding or leaving behind `failureCode` / `failureMessage` on a factual receipt, while preserving rank 1–2 transport failure codes.
23
+ **Affects:** `stitchkit/spend` reconcilePendingSpend, ReconcilePendingSpendOptions, mergeSpendReceipt
24
+
18
25
  ## [0.136.5] - 2026-12-03
19
26
 
20
27
  ### Added
@@ -11,8 +11,10 @@ export declare function openRouterSpendProvider(options: {
11
11
  }): SpendProvider;
12
12
  /**
13
13
  * Ask OpenRouter what an attempt cost (`GET /api/v1/generation?id=`), by the
14
- * generation id the gateway read from the response. A 404 is "not yet" — the
15
- * attempt stays pending; an attempt with no generation id can never be priced.
14
+ * generation id the gateway read from the response. A 404 or missing `total_cost`
15
+ * returns `undefined` ("not yet", settled as `unknown` once `maxPendingAgeMs`
16
+ * passes in `reconcilePendingSpend`); an attempt with no generation id can never
17
+ * be priced.
16
18
  */
17
19
  export declare function createOpenRouterSpendReconciler(options: {
18
20
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"openrouter-spend.d.ts","sourceRoot":"","sources":["../../../src/agent-runtime/providers/openrouter-spend.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,EAAc,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,KAAK,eAAe,EAAyB,MAAM,mBAAmB,CAAC;AAyDhF,gHAAgH;AAChH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE;IAC/C,wDAAwD;IACxD,MAAM,EAAE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACvC,4GAA4G;IAC5G,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,GAAG,aAAa,CAQhB;AAeD;;;;GAIG;AACH,wBAAgB,+BAA+B,CAAC,OAAO,EAAE;IACvD;;;OAGG;IACH,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,WAAW,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IACrE,qFAAqF;IACrF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,eAAe,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,eAAe,CAyClB"}
1
+ {"version":3,"file":"openrouter-spend.d.ts","sourceRoot":"","sources":["../../../src/agent-runtime/providers/openrouter-spend.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,EAAc,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,KAAK,eAAe,EAAyB,MAAM,mBAAmB,CAAC;AAyDhF,gHAAgH;AAChH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE;IAC/C,wDAAwD;IACxD,MAAM,EAAE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACvC,4GAA4G;IAC5G,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,GAAG,aAAa,CAQhB;AAeD;;;;;;GAMG;AACH,wBAAgB,+BAA+B,CAAC,OAAO,EAAE;IACvD;;;OAGG;IACH,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,WAAW,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IACrE,qFAAqF;IACrF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,eAAe,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,eAAe,CAyClB"}
@@ -5,6 +5,9 @@ import {
5
5
  SpoolUnspooledError,
6
6
  createSpoolCore
7
7
  } from "../index-xqppqn97.js";
8
+ import {
9
+ assertPositiveSafeInteger
10
+ } from "../index-gr0kxymw.js";
8
11
  import {
9
12
  isRecord,
10
13
  withoutUndefined
@@ -18,7 +21,7 @@ import { z } from "zod";
18
21
  var Id = z.string().min(1).max(256);
19
22
  var Label = z.string().min(1).max(512);
20
23
  var Count = z.int().nonnegative();
21
- var Timestamp = z.iso.datetime({ offset: true });
24
+ var SpendTimestampSchema = z.iso.datetime({ offset: true });
22
25
  var SpendAttributionSchema = z.strictObject({
23
26
  scope: Label.optional(),
24
27
  purpose: Label,
@@ -71,7 +74,7 @@ var SpendFactsSchema = z.strictObject({
71
74
  var SpendAttemptSchema = z.strictObject({
72
75
  attemptId: Id,
73
76
  gateway: Label,
74
- startedAt: Timestamp,
77
+ startedAt: SpendTimestampSchema,
75
78
  attribution: SpendAttributionSchema,
76
79
  request: z.strictObject({
77
80
  method: z.string().min(1).max(16),
@@ -83,7 +86,7 @@ var SpendReceiptRankSchema = z.union([z.literal(1), z.literal(2), z.literal(3)])
83
86
  var SpendReceiptSchema = z.strictObject({
84
87
  attemptId: Id,
85
88
  rank: SpendReceiptRankSchema,
86
- at: Timestamp,
89
+ at: SpendTimestampSchema,
87
90
  outcome: SpendOutcomeSchema,
88
91
  facts: SpendFactsSchema
89
92
  });
@@ -431,6 +434,10 @@ function createSpendGateway(config) {
431
434
  }
432
435
  // src/spend/receipt-merge.ts
433
436
  var isFactual = (status) => status === "reported" || status === "free";
437
+ var RECONCILER_FAILURE_FIELDS = new Set(["failureCode", "failureMessage"]);
438
+ function pickFacts(facts, options) {
439
+ return Object.fromEntries(Object.entries(facts).filter(([key, value]) => value !== undefined && (!options.dropReconcilerFailure || !RECONCILER_FAILURE_FIELDS.has(key))));
440
+ }
434
441
  function costOf(facts) {
435
442
  return {
436
443
  costStatus: facts.costStatus,
@@ -453,10 +460,23 @@ function mergeSpendReceipt(previous, next) {
453
460
  return known;
454
461
  if (known.outcome === "orphaned")
455
462
  return incoming;
456
- const newerWins = incoming.rank > known.rank || incoming.rank === known.rank && Date.parse(incoming.at) >= Date.parse(known.at);
463
+ const incomingAt = Date.parse(incoming.at);
464
+ const knownAt = Date.parse(known.at);
465
+ const newerWins = incoming.rank > known.rank || incoming.rank === known.rank && (incomingAt > knownAt || incomingAt === knownAt && (!isFactual(known.facts.costStatus) || isFactual(incoming.facts.costStatus)));
457
466
  const [older, newer] = newerWins ? [known, incoming] : [incoming, known];
458
- const defined = Object.fromEntries(Object.entries(newer.facts).filter(([, value]) => value !== undefined));
459
- const facts = { ...older.facts, ...defined };
467
+ const olderFactual = isFactual(older.facts.costStatus);
468
+ const newerFactual = isFactual(newer.facts.costStatus);
469
+ const baseFacts = pickFacts(older.facts, {
470
+ dropReconcilerFailure: older.rank === 3 && !olderFactual && newerFactual
471
+ });
472
+ const newerFacts = pickFacts(newer.facts, {
473
+ dropReconcilerFailure: newer.rank === 3 && olderFactual && !newerFactual
474
+ });
475
+ const facts = {
476
+ ...baseFacts,
477
+ ...newerFacts,
478
+ costStatus: newer.facts.costStatus
479
+ };
460
480
  const outcome = newer.outcome === "pending" && older.outcome !== "pending" ? older.outcome : newer.outcome;
461
481
  const cost = mergedCost(older.facts, newer.facts);
462
482
  const { costUsd: _dropped, ...withoutCost } = facts;
@@ -509,10 +529,47 @@ function createSpooledSpendStore(config) {
509
529
  };
510
530
  }
511
531
  // src/spend/reconcile.ts
532
+ function readCheckedAt(now) {
533
+ const value = now();
534
+ if (!isRecord(value)) {
535
+ throw new TypeError(`reconcilePendingSpend now() must return a Date, received ${String(value)}`);
536
+ }
537
+ const getTime = Reflect.get(value, "getTime");
538
+ const toISOString = Reflect.get(value, "toISOString");
539
+ if (typeof getTime !== "function" || typeof toISOString !== "function") {
540
+ throw new TypeError(`reconcilePendingSpend now() must return a Date, received ${String(value)}`);
541
+ }
542
+ const epoch = Reflect.apply(getTime, value, []);
543
+ if (typeof epoch !== "number" || !Number.isFinite(epoch)) {
544
+ throw new RangeError("reconcilePendingSpend now() returned an invalid Date");
545
+ }
546
+ const iso = Reflect.apply(toISOString, value, []);
547
+ if (typeof iso !== "string") {
548
+ throw new TypeError("reconcilePendingSpend now() must return a Date");
549
+ }
550
+ const parsedIso = SpendTimestampSchema.safeParse(iso);
551
+ if (!parsedIso.success || Date.parse(parsedIso.data) !== epoch) {
552
+ throw new RangeError("reconcilePendingSpend now() returned an invalid Date");
553
+ }
554
+ return { epoch, iso: parsedIso.data };
555
+ }
556
+ function parsePendingSinceEpoch(record) {
557
+ const since = record.receipt?.at ?? record.attempt.startedAt;
558
+ const parsed = SpendTimestampSchema.safeParse(since);
559
+ if (!parsed.success) {
560
+ throw new TypeError(`Spend record "${record.attempt.attemptId}" has an invalid timestamp: ${String(since)}`);
561
+ }
562
+ const sinceEpoch = Date.parse(parsed.data);
563
+ if (!Number.isFinite(sinceEpoch)) {
564
+ throw new TypeError(`Spend record "${record.attempt.attemptId}" has an unparseable timestamp: ${parsed.data}`);
565
+ }
566
+ return sinceEpoch;
567
+ }
512
568
  async function reconcilePendingSpend(options) {
513
- const { store } = options;
569
+ const { store, maxPendingAgeMs } = options;
514
570
  if (!store.pendingCosts)
515
571
  throw new TypeError("reconcilePendingSpend needs a store with pendingCosts");
572
+ assertPositiveSafeInteger("maxPendingAgeMs", maxPendingAgeMs);
516
573
  const now = options.now ?? (() => new Date);
517
574
  const result = {
518
575
  checked: 0,
@@ -527,22 +584,35 @@ async function reconcilePendingSpend(options) {
527
584
  result.stillPending += 1;
528
585
  continue;
529
586
  }
587
+ let learned;
588
+ try {
589
+ learned = await reconcile(record);
590
+ if (learned !== undefined && !isRecord(learned)) {
591
+ throw new TypeError("Spend reconciler must return a facts object or undefined");
592
+ }
593
+ } catch (error) {
594
+ result.failed += 1;
595
+ options.onError?.({ record, error });
596
+ continue;
597
+ }
598
+ if (learned === undefined && maxPendingAgeMs === undefined) {
599
+ result.stillPending += 1;
600
+ continue;
601
+ }
602
+ const checkedAt = readCheckedAt(now);
530
603
  let receipt;
531
604
  try {
532
- const learned = await reconcile(record);
533
- if (learned === undefined) {
605
+ const facts = learned ?? (maxPendingAgeMs !== undefined && checkedAt.epoch - parsePendingSinceEpoch(record) >= maxPendingAgeMs ? { costStatus: "unknown", failureCode: "price-never-reported" } : undefined);
606
+ if (facts === undefined) {
534
607
  result.stillPending += 1;
535
608
  continue;
536
609
  }
537
- if (!isRecord(learned)) {
538
- throw new TypeError("Spend reconciler must return a facts object or undefined");
539
- }
540
610
  receipt = mergeSpendReceipt(record.receipt, {
541
611
  attemptId: record.attempt.attemptId,
542
612
  rank: 3,
543
- at: now().toISOString(),
613
+ at: checkedAt.iso,
544
614
  outcome: record.receipt?.outcome ?? "pending",
545
- facts: SpendFactsSchema.parse({ costStatus: "unknown", ...withoutUndefined(learned) })
615
+ facts: SpendFactsSchema.parse({ costStatus: "unknown", ...withoutUndefined(facts) })
546
616
  });
547
617
  } catch (error) {
548
618
  result.failed += 1;
@@ -4,10 +4,14 @@ import { type SpendReceipt } from './schemas.js';
4
4
  * out-of-order delivery converge: a field the higher-ranked receipt knows wins, a
5
5
  * field it does not know keeps the other's value, a closed outcome never returns
6
6
  * to `pending`, and a provider-reported cost is never erased by a later guess.
7
- * Equal ranks: the receipt with the later `at` wins, whatever order they arrive in.
8
- * An `orphaned` close (a sweep found nothing) never replaces a real one. Fields are
9
- * ranked by receipt, not each: it assumes one transport-side receipt per attempt
10
- * (the gateway writes exactly one), followed by reconciler receipts.
7
+ * Equal ranks: the receipt with the later `at` wins, whatever order they arrive in
8
+ * (and a factual cost breaks an exact-timestamp tie). A non-factual rank-3
9
+ * reconciler receipt never overwrites or leaves behind a reconciler `failureCode` /
10
+ * `failureMessage` alongside a factual (`reported` or `free`) cost, while transport
11
+ * failure codes from ranks 1–2 stay intact. An `orphaned` close (a sweep found
12
+ * nothing) never replaces a real one. Fields are ranked by receipt, not each: it
13
+ * assumes one transport-side receipt per attempt (the gateway writes exactly one),
14
+ * followed by reconciler receipts.
11
15
  */
12
16
  export declare function mergeSpendReceipt(previous: SpendReceipt | undefined, next: SpendReceipt): SpendReceipt;
13
17
  //# sourceMappingURL=receipt-merge.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"receipt-merge.d.ts","sourceRoot":"","sources":["../../src/spend/receipt-merge.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,YAAY,EAElB,MAAM,WAAW,CAAC;AAsBnB;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,YAAY,GAAG,SAAS,EAClC,IAAI,EAAE,YAAY,GACjB,YAAY,CA6Bd"}
1
+ {"version":3,"file":"receipt-merge.d.ts","sourceRoot":"","sources":["../../src/spend/receipt-merge.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,YAAY,EAElB,MAAM,WAAW,CAAC;AAqCnB;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,YAAY,GAAG,SAAS,EAClC,IAAI,EAAE,YAAY,GACjB,YAAY,CA2Cd"}
@@ -11,8 +11,16 @@ export interface ReconcilePendingSpendOptions {
11
11
  /** By gateway name; a pending attempt of a gateway without one is left as it is. */
12
12
  reconcilers: Readonly<Record<string, SpendReconciler>>;
13
13
  limit?: number;
14
+ /**
15
+ * Once a pending attempt has waited at least this many milliseconds since its
16
+ * latest receipt (`record.receipt.at`, or `record.attempt.startedAt` when no
17
+ * receipt exists) and its reconciler still returns `undefined`, settle it as
18
+ * `costStatus: 'unknown'` with `failureCode: 'price-never-reported'` instead
19
+ * of leaving it `pending` forever.
20
+ */
21
+ maxPendingAgeMs?: number;
14
22
  now?: () => Date;
15
- /** A reconciler that threw or returned invalid facts: the attempt stays pending, and here is why (for `reconcileError`). */
23
+ /** A reconciler that threw or returned invalid facts, an invalid record timestamp, or a receipt-merge failure: the attempt stays pending, and here is why (for `reconcileError`). */
16
24
  onError?: (failure: {
17
25
  record: SpendRecord;
18
26
  error: unknown;
@@ -28,7 +36,12 @@ export interface SpendReconcileResult {
28
36
  /**
29
37
  * One pass over the attempts whose cost is still `pending`: each reconciler's
30
38
  * answer is settled as a rank-3 receipt, merged so it only ever adds what the
31
- * provider now knows. A reconciler that throws or returns invalid facts is
39
+ * provider now knows. When `maxPendingAgeMs` is set and a reconciler still
40
+ * returns `undefined` once at least that many milliseconds have passed since
41
+ * `record.receipt.at` (or `record.attempt.startedAt` when no receipt exists),
42
+ * the attempt is settled as `costStatus: 'unknown'` with
43
+ * `failureCode: 'price-never-reported'`. A reconciler that throws or returns
44
+ * invalid facts, an invalid record timestamp, or a receipt-merge failure is
32
45
  * counted and its attempt stays pending for the next pass.
33
46
  */
34
47
  export declare function reconcilePendingSpend(options: ReconcilePendingSpendOptions): Promise<Sp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AClB,GAAG,OAAO,CAAC,MAAM,CAAC,CAkBlB"}
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ export declare const SpendTimestampSchema: z.ZodISODateTime;
2
3
  /**
3
4
  * Who and what a model call is for. Free strings, no domain vocabulary (ADR 0002):
4
5
  * `scope` is the application's own boundary (a space, a tenant), `purpose` the job
@@ -1 +1 @@
1
- {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/spend/schemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAOxB;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;kBAcjC,CAAC;AACH,8EAA8E;AAC9E,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAEtE;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB;;;;;;EAMhC,CAAC;AACH,6EAA6E;AAC7E,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB;;;;;;;EAO7B,CAAC;AACH,0DAA0D;AAC1D,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAE9D,wGAAwG;AACxG,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;kBAqB3B,CAAC;AACH,8FAA8F;AAC9F,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAE1D,+EAA+E;AAC/E,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;kBAU7B,CAAC;AACH,gDAAgD;AAChD,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAE9D;;;;GAIG;AACH,eAAO,MA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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAG5B,CAAC;AACH,+DAA+D;AAC/D,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAE5D;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5C,MAAM,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7C,gFAAgF;IAChF,YAAY,CAAC,CAAC,KAAK,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,SAAS,WAAW,EAAE,CAAC,CAAC;IACzE,2FAA2F;IAC3F,YAAY,CAAC,CAAC,KAAK,EAAE;QACnB,aAAa,EAAE,MAAM,CAAC;QACtB,KAAK,EAAE,MAAM,CAAC;KACf,GAAG,OAAO,CAAC,SAAS,YAAY,EAAE,CAAC,CAAC;CACtC"}
@@ -32,7 +32,7 @@ Server-only, peer-free native OpenRouter provider over Web `fetch` and Chat Comp
32
32
  | `findOpenRouterModel` / `listOpenRouterModels` / `OpenRouterModelFilter` | functions / _type_ | query an `OpenRouterCatalogSnapshot` by exact `id` or `canonicalSlug`, or filter models by `tools`, `reasoning` (`reasoning`, `include_reasoning`, or declared efforts), `inputModalities`, `outputModalities`, `minContextLength` (via effective context `min(contextLength, topProviderContextLength)`), `maxPromptUsdPerMillion`, `maxCompletionUsdPerMillion`, `maxCacheWriteUsdPerMillion` (using the same ceiling semantics as `evaluateOpenRouterModelAdmission`), `freeOnly`, and `author` |
33
33
  | `createOpenRouterCatalogCache` / `OpenRouterCatalogCache` / `OpenRouterCatalogCacheOptions` / `OpenRouterCatalogCacheReadResult` / `OpenRouterCatalogStore` | function / _types_ | Web Fetch-clean cached OpenRouter catalog reader with single-flight coalescing, per-caller `AbortSignal` isolation, `freshMs` TTL, `retryBackoffMs` stale fallback, optional pluggable persistence (`store`), and `read`/`refresh`/`getModel`/`listModels`; `OpenRouterCatalogCacheReadResult` is a discriminated union on `status` (`'current' \| 'stale' \| 'unavailable'`) narrowing `snapshot`, `observedAt`, `models`, and `lastError` without casts (use `read()` for admission/billing decisions; `getModel`/`listModels` map `'unavailable'` to `undefined`/`[]`) |
34
34
  | `evaluateOpenRouterModelAdmission` / `OpenRouterAdmissionPolicySchema` / `OpenRouterAdmissionPolicy` / `OpenRouterModelAdmissionSchema` / `OpenRouterModelAdmission` / `OpenRouterAdmissionReasonSchema` / `OpenRouterAdmissionReason` | function / schemas / _types_ | decide one model from a stored snapshot: `admitted`, `unverified` (stale or future-dated snapshot, `'context-unknown'`, `'price-unknown'`, `'endpoints-unknown'`) or `rejected` with a reason (`requiredParameters`, `requiredInputModalities`, effective context `min(contextLength, topProviderContextLength)`, separated worst-case pricing ceilings `maxPromptUsdPerMillion` / `maxCompletionUsdPerMillion` / `maxCacheWriteUsdPerMillion` via `resolveOpenRouterModelCeiling`, live endpoint); `~`, `-latest`, `:batch`, `stealth/`, `openrouter/auto`, `aliasOf`, and `aliasTarget` models are always refused as `'floating-alias'`; the result is a schema, so a stored decision reads back |
35
- | `openRouterSpendProvider` / `createOpenRouterSpendReconciler` | functions | OpenRouter for `stitchkit/spend`: the gateway provider (origin derived from optional `baseUrl` override, key read per call, chat + non-chat usage facts including `x-generation-id`, `input_tokens`/`output_tokens`, `generation_id`, and `usage.seconds` as `workUnit: 'seconds'`) and the reconciler that prices an attempt by its generation id (`GET /api/v1/generation`, optional `baseUrl` override; a 404 is "not yet"; `apiKey` may be a function of the record, since OpenRouter prices a generation only for the key that made it) |
35
+ | `openRouterSpendProvider` / `createOpenRouterSpendReconciler` | functions | OpenRouter for `stitchkit/spend`: the gateway provider (origin derived from optional `baseUrl` override, key read per call, chat + non-chat usage facts including `x-generation-id`, `input_tokens`/`output_tokens`, `generation_id`, and `usage.seconds` as `workUnit: 'seconds'`) and the reconciler that prices an attempt by its generation id (`GET /api/v1/generation`, optional `baseUrl` override; a 404 or absent `total_cost` returns `undefined` ("not yet", closed as `unknown` once `maxPendingAgeMs` passes in `reconcilePendingSpend`); `apiKey` may be a function of the record, since OpenRouter prices a generation only for the key that made it) |
36
36
  | `openRouterModelCatalog` | function | complete tool-capable text catalog (`sort=top-weekly`) plus independent weekly popularity and available benchmark observations (optional static or async `apiKey` and `baseUrl` override); a `timeoutMs` that is not an integer from 1 to 2147483647 ms (the timer range) is refused when the catalog is created (`RangeError`) |
37
37
  | `OpenRouterModelCatalogOptions` | _type_ | optional static/dynamic credential, `baseUrl` override, timeout, clock and injected `OpenRouterFetch` for catalog loading |
38
38
  | `OPENROUTER_API_BASE_URL` / `OpenRouterFetch` | const / _type_ | canonical default OpenRouter API v1 base URL (`https://openrouter.ai/api/v1`) and the one Web Fetch-compatible transport type (it receives the resolved `URL`) shared by `openRouterProvider`, catalog, spend and non-chat endpoint helpers |
package/llms/spend.txt CHANGED
@@ -121,9 +121,15 @@ nor stored refuses the call.
121
121
 
122
122
  ## Afterwards
123
123
 
124
- - `reconcilePendingSpend({ store, reconcilers })` asks each provider for the cost of
125
- attempts still `pending` (OpenRouter: `GET /api/v1/generation?id=`) and settles
126
- rank-3 receipts. The store needs `pendingCosts`.
124
+ - `reconcilePendingSpend({ store, reconcilers, maxPendingAgeMs })` asks each provider for
125
+ the cost of attempts still `pending` (OpenRouter: `GET /api/v1/generation?id=`) and
126
+ settles rank-3 receipts. Pass `maxPendingAgeMs` so an attempt whose reconciler still
127
+ returns `undefined` (for example a 404 or missing `total_cost`) after that age — measured
128
+ from `record.receipt.at`, or `record.attempt.startedAt` when no receipt exists — settles
129
+ as `costStatus: 'unknown'` with `failureCode: 'price-never-reported'` instead of staying
130
+ `pending` forever and filling `pendingCosts`; before `maxPendingAgeMs`, or when omitted,
131
+ `undefined` keeps the row `pending`, and reconciler failures stay `pending` for the next
132
+ pass. The store needs `pendingCosts`.
127
133
  - `closeOrphanedSpend({ store, olderThanMs })` closes attempts whose process never
128
134
  came back to them as `orphaned`, cost `unknown`. The store needs `openAttempts`.
129
135
 
@@ -189,7 +195,7 @@ Peer-free, server-only spend accounting for paid model APIs (→ [guide](../guid
189
195
  | `runWithSpendAttribution` / `getSpendAttribution` | function | the attribution of every gateway call in a call chain (AsyncLocalStorage); nested calls refine, `labels` merge |
190
196
  | `openAiCompatibleUsage` / `SpendFactsReader` | const / _type_ | reads `id`, `model` and `usage` (tokens, reasoning, cache, OpenRouter's `cost`) from a JSON body or the stream's events |
191
197
  | `createSpooledSpendStore` / `SpooledSpendStore` / `SpooledSpendStoreConfig` | function / _types_ | a ledger that survives its database: on disk first (`0o600`, bounded), delivered after; `recover()` replays in order, an attempt before its receipts — a receipt whose attempt is undelivered waits on disk with it, in the live path too; a record neither spooled nor stored refuses the call; `pendingCosts` and `openAttempts` pass through |
192
- | `mergeSpendReceipt` | function | the monotone merge a ledger applies: a higher rank adds what it knows, equal ranks resolve by `at`, a closed outcome never returns to `pending`, a reported cost is never erased, and an `orphaned` close never replaces a real one (a real one replaces it) |
193
- | `reconcilePendingSpend` / `SpendReconciler` / `ReconcilePendingSpendOptions` / `SpendReconcileResult` | function / _types_ | one pass over attempts whose cost is `pending`: each gateway's reconciler answers, rank-3 receipts are settled; `onError` sees a reconciler that threw, returned invalid facts, or failed receipt merging (while `store.settle` failures still reject) |
198
+ | `mergeSpendReceipt` | function | the monotone merge a ledger applies: a higher rank adds what it knows, equal ranks resolve by `at` (a factual cost breaks exact-timestamp ties), a closed outcome never returns to `pending`, a reported cost is never erased, a non-factual rank-3 reconciler receipt neither pollutes a factual cost with `failureCode`/`failureMessage` nor leaves those fields behind once a factual price arrives (while rank 1–2 transport failure codes stay intact), and an `orphaned` close never replaces a real one (a real one replaces it) |
199
+ | `reconcilePendingSpend` / `SpendReconciler` / `ReconcilePendingSpendOptions` / `SpendReconcileResult` | function / _types_ | one pass over attempts whose cost is `pending`: each gateway's reconciler answers, rank-3 receipts are settled; optional `maxPendingAgeMs` (positive safe integer validated upfront) settles attempts whose reconciler still returns `undefined` at or past that age since `record.receipt.at` (or `record.attempt.startedAt`) as `costStatus: 'unknown'` with `failureCode: 'price-never-reported'` (while reconciler throws and gateways without a reconciler stay `pending`); `onError` sees a reconciler that threw or returned invalid facts, an invalid record timestamp, or a receipt-merge failure (while broken `now()` clocks and `store.settle` failures still reject) |
194
200
  | `closeOrphanedSpend` | function | closes attempts left open longer than `olderThanMs` as `orphaned` with an `unknown` cost |
195
201
  | `SpendAttributionSchema` / `SpendAttribution` / `SpendAttemptSchema` / `SpendAttempt` / `SpendReceiptSchema` / `SpendReceipt` / `SpendRecordSchema` / `SpendRecord` / `SpendFactsSchema` / `SpendFacts` / `SpendOutcomeSchema` / `SpendOutcome` / `SpendCostStatusSchema` / `SpendCostStatus` / `SpendLedgerStore` / `SpendReceiptRank` | schemas / _types_ | the records: attribution (free strings: `scope`, `purpose`, `operation`, `labels`, run/invocation/step links), the attempt, the receipt (`rank`, `outcome`, `facts`), and the ledger the application implements |
package/llms-full.txt CHANGED
@@ -17992,9 +17992,15 @@ nor stored refuses the call.
17992
17992
 
17993
17993
  ## Afterwards
17994
17994
 
17995
- - `reconcilePendingSpend({ store, reconcilers })` asks each provider for the cost of
17996
- attempts still `pending` (OpenRouter: `GET /api/v1/generation?id=`) and settles
17997
- rank-3 receipts. The store needs `pendingCosts`.
17995
+ - `reconcilePendingSpend({ store, reconcilers, maxPendingAgeMs })` asks each provider for
17996
+ the cost of attempts still `pending` (OpenRouter: `GET /api/v1/generation?id=`) and
17997
+ settles rank-3 receipts. Pass `maxPendingAgeMs` so an attempt whose reconciler still
17998
+ returns `undefined` (for example a 404 or missing `total_cost`) after that age — measured
17999
+ from `record.receipt.at`, or `record.attempt.startedAt` when no receipt exists — settles
18000
+ as `costStatus: 'unknown'` with `failureCode: 'price-never-reported'` instead of staying
18001
+ `pending` forever and filling `pendingCosts`; before `maxPendingAgeMs`, or when omitted,
18002
+ `undefined` keeps the row `pending`, and reconciler failures stay `pending` for the next
18003
+ pass. The store needs `pendingCosts`.
17998
18004
  - `closeOrphanedSpend({ store, olderThanMs })` closes attempts whose process never
17999
18005
  came back to them as `orphaned`, cost `unknown`. The store needs `openAttempts`.
18000
18006
 
@@ -30371,7 +30377,7 @@ Server-only, peer-free native OpenRouter provider over Web `fetch` and Chat Comp
30371
30377
  | `findOpenRouterModel` / `listOpenRouterModels` / `OpenRouterModelFilter` | functions / _type_ | query an `OpenRouterCatalogSnapshot` by exact `id` or `canonicalSlug`, or filter models by `tools`, `reasoning` (`reasoning`, `include_reasoning`, or declared efforts), `inputModalities`, `outputModalities`, `minContextLength` (via effective context `min(contextLength, topProviderContextLength)`), `maxPromptUsdPerMillion`, `maxCompletionUsdPerMillion`, `maxCacheWriteUsdPerMillion` (using the same ceiling semantics as `evaluateOpenRouterModelAdmission`), `freeOnly`, and `author` |
30372
30378
  | `createOpenRouterCatalogCache` / `OpenRouterCatalogCache` / `OpenRouterCatalogCacheOptions` / `OpenRouterCatalogCacheReadResult` / `OpenRouterCatalogStore` | function / _types_ | Web Fetch-clean cached OpenRouter catalog reader with single-flight coalescing, per-caller `AbortSignal` isolation, `freshMs` TTL, `retryBackoffMs` stale fallback, optional pluggable persistence (`store`), and `read`/`refresh`/`getModel`/`listModels`; `OpenRouterCatalogCacheReadResult` is a discriminated union on `status` (`'current' \| 'stale' \| 'unavailable'`) narrowing `snapshot`, `observedAt`, `models`, and `lastError` without casts (use `read()` for admission/billing decisions; `getModel`/`listModels` map `'unavailable'` to `undefined`/`[]`) |
30373
30379
  | `evaluateOpenRouterModelAdmission` / `OpenRouterAdmissionPolicySchema` / `OpenRouterAdmissionPolicy` / `OpenRouterModelAdmissionSchema` / `OpenRouterModelAdmission` / `OpenRouterAdmissionReasonSchema` / `OpenRouterAdmissionReason` | function / schemas / _types_ | decide one model from a stored snapshot: `admitted`, `unverified` (stale or future-dated snapshot, `'context-unknown'`, `'price-unknown'`, `'endpoints-unknown'`) or `rejected` with a reason (`requiredParameters`, `requiredInputModalities`, effective context `min(contextLength, topProviderContextLength)`, separated worst-case pricing ceilings `maxPromptUsdPerMillion` / `maxCompletionUsdPerMillion` / `maxCacheWriteUsdPerMillion` via `resolveOpenRouterModelCeiling`, live endpoint); `~`, `-latest`, `:batch`, `stealth/`, `openrouter/auto`, `aliasOf`, and `aliasTarget` models are always refused as `'floating-alias'`; the result is a schema, so a stored decision reads back |
30374
- | `openRouterSpendProvider` / `createOpenRouterSpendReconciler` | functions | OpenRouter for `stitchkit/spend`: the gateway provider (origin derived from optional `baseUrl` override, key read per call, chat + non-chat usage facts including `x-generation-id`, `input_tokens`/`output_tokens`, `generation_id`, and `usage.seconds` as `workUnit: 'seconds'`) and the reconciler that prices an attempt by its generation id (`GET /api/v1/generation`, optional `baseUrl` override; a 404 is "not yet"; `apiKey` may be a function of the record, since OpenRouter prices a generation only for the key that made it) |
30380
+ | `openRouterSpendProvider` / `createOpenRouterSpendReconciler` | functions | OpenRouter for `stitchkit/spend`: the gateway provider (origin derived from optional `baseUrl` override, key read per call, chat + non-chat usage facts including `x-generation-id`, `input_tokens`/`output_tokens`, `generation_id`, and `usage.seconds` as `workUnit: 'seconds'`) and the reconciler that prices an attempt by its generation id (`GET /api/v1/generation`, optional `baseUrl` override; a 404 or absent `total_cost` returns `undefined` ("not yet", closed as `unknown` once `maxPendingAgeMs` passes in `reconcilePendingSpend`); `apiKey` may be a function of the record, since OpenRouter prices a generation only for the key that made it) |
30375
30381
  | `openRouterModelCatalog` | function | complete tool-capable text catalog (`sort=top-weekly`) plus independent weekly popularity and available benchmark observations (optional static or async `apiKey` and `baseUrl` override); a `timeoutMs` that is not an integer from 1 to 2147483647 ms (the timer range) is refused when the catalog is created (`RangeError`) |
30376
30382
  | `OpenRouterModelCatalogOptions` | _type_ | optional static/dynamic credential, `baseUrl` override, timeout, clock and injected `OpenRouterFetch` for catalog loading |
30377
30383
  | `OPENROUTER_API_BASE_URL` / `OpenRouterFetch` | const / _type_ | canonical default OpenRouter API v1 base URL (`https://openrouter.ai/api/v1`) and the one Web Fetch-compatible transport type (it receives the resolved `URL`) shared by `openRouterProvider`, catalog, spend and non-chat endpoint helpers |
@@ -31377,8 +31383,8 @@ Peer-free, server-only spend accounting for paid model APIs (→ [guide](../guid
31377
31383
  | `runWithSpendAttribution` / `getSpendAttribution` | function | the attribution of every gateway call in a call chain (AsyncLocalStorage); nested calls refine, `labels` merge |
31378
31384
  | `openAiCompatibleUsage` / `SpendFactsReader` | const / _type_ | reads `id`, `model` and `usage` (tokens, reasoning, cache, OpenRouter's `cost`) from a JSON body or the stream's events |
31379
31385
  | `createSpooledSpendStore` / `SpooledSpendStore` / `SpooledSpendStoreConfig` | function / _types_ | a ledger that survives its database: on disk first (`0o600`, bounded), delivered after; `recover()` replays in order, an attempt before its receipts — a receipt whose attempt is undelivered waits on disk with it, in the live path too; a record neither spooled nor stored refuses the call; `pendingCosts` and `openAttempts` pass through |
31380
- | `mergeSpendReceipt` | function | the monotone merge a ledger applies: a higher rank adds what it knows, equal ranks resolve by `at`, a closed outcome never returns to `pending`, a reported cost is never erased, and an `orphaned` close never replaces a real one (a real one replaces it) |
31381
- | `reconcilePendingSpend` / `SpendReconciler` / `ReconcilePendingSpendOptions` / `SpendReconcileResult` | function / _types_ | one pass over attempts whose cost is `pending`: each gateway's reconciler answers, rank-3 receipts are settled; `onError` sees a reconciler that threw, returned invalid facts, or failed receipt merging (while `store.settle` failures still reject) |
31386
+ | `mergeSpendReceipt` | function | the monotone merge a ledger applies: a higher rank adds what it knows, equal ranks resolve by `at` (a factual cost breaks exact-timestamp ties), a closed outcome never returns to `pending`, a reported cost is never erased, a non-factual rank-3 reconciler receipt neither pollutes a factual cost with `failureCode`/`failureMessage` nor leaves those fields behind once a factual price arrives (while rank 1–2 transport failure codes stay intact), and an `orphaned` close never replaces a real one (a real one replaces it) |
31387
+ | `reconcilePendingSpend` / `SpendReconciler` / `ReconcilePendingSpendOptions` / `SpendReconcileResult` | function / _types_ | one pass over attempts whose cost is `pending`: each gateway's reconciler answers, rank-3 receipts are settled; optional `maxPendingAgeMs` (positive safe integer validated upfront) settles attempts whose reconciler still returns `undefined` at or past that age since `record.receipt.at` (or `record.attempt.startedAt`) as `costStatus: 'unknown'` with `failureCode: 'price-never-reported'` (while reconciler throws and gateways without a reconciler stay `pending`); `onError` sees a reconciler that threw or returned invalid facts, an invalid record timestamp, or a receipt-merge failure (while broken `now()` clocks and `store.settle` failures still reject) |
31382
31388
  | `closeOrphanedSpend` | function | closes attempts left open longer than `olderThanMs` as `orphaned` with an `unknown` cost |
31383
31389
  | `SpendAttributionSchema` / `SpendAttribution` / `SpendAttemptSchema` / `SpendAttempt` / `SpendReceiptSchema` / `SpendReceipt` / `SpendRecordSchema` / `SpendRecord` / `SpendFactsSchema` / `SpendFacts` / `SpendOutcomeSchema` / `SpendOutcome` / `SpendCostStatusSchema` / `SpendCostStatus` / `SpendLedgerStore` / `SpendReceiptRank` | schemas / _types_ | the records: attribution (free strings: `scope`, `purpose`, `operation`, `labels`, run/invocation/step links), the attempt, the receipt (`rank`, `outcome`, `facts`), and the ledger the application implements |
31384
31390
 
package/llms.txt CHANGED
@@ -34,7 +34,7 @@ Load the slice for each entrypoint your code imports — `import … from 'stitc
34
34
  - **stitchkit/agent-runtime/harness**: [llms/agent-runtime-harness.txt](llms/agent-runtime-harness.txt) 13.7 KB
35
35
  - **stitchkit/agent-runtime/coding-tools**: [llms/agent-runtime-coding-tools.txt](llms/agent-runtime-coding-tools.txt) 5.0 KB
36
36
  - **stitchkit/agent-runtime/browser**: [llms/agent-runtime-browser.txt](llms/agent-runtime-browser.txt) 5.4 KB
37
- - **stitchkit/agent-runtime/openrouter**: [llms/agent-runtime-openrouter.txt](llms/agent-runtime-openrouter.txt) 14.9 KB
37
+ - **stitchkit/agent-runtime/openrouter**: [llms/agent-runtime-openrouter.txt](llms/agent-runtime-openrouter.txt) 15.0 KB
38
38
  - **stitchkit/agent-runtime/openai**: [llms/agent-runtime-openai.txt](llms/agent-runtime-openai.txt) 2.3 KB
39
39
  - **stitchkit/agent-runtime/anthropic**: [llms/agent-runtime-anthropic.txt](llms/agent-runtime-anthropic.txt) 2.9 KB
40
40
  - **stitchkit/agent-executor**: [llms/agent-executor.txt](llms/agent-executor.txt) 13.5 KB
@@ -54,7 +54,7 @@ Load the slice for each entrypoint your code imports — `import … from 'stitc
54
54
  - **stitchkit/application/diagnostic-journal**: [llms/application-diagnostic-journal.txt](llms/application-diagnostic-journal.txt) 1.8 KB
55
55
  - **stitchkit/testing**: [llms/testing.txt](llms/testing.txt) 34.1 KB
56
56
  - **stitchkit/agent-runtime/sandbox**: [llms/agent-runtime-sandbox.txt](llms/agent-runtime-sandbox.txt) 17.1 KB
57
- - **stitchkit/spend**: [llms/spend.txt](llms/spend.txt) 11.0 KB
57
+ - **stitchkit/spend**: [llms/spend.txt](llms/spend.txt) 12.2 KB
58
58
  - **stitchkit/spend/testing**: [llms/spend-testing.txt](llms/spend-testing.txt) 1.2 KB
59
59
  - **stitchkit/files**: [llms/files.txt](llms/files.txt) 11.7 KB
60
60
  - **stitchkit/service-host**: [llms/service-host.txt](llms/service-host.txt) 10.3 KB
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stitchkit",
3
- "version": "0.136.5",
3
+ "version": "0.136.6",
4
4
  "description": "Contract-first backend framework — one defineContract() into an HTTP API, MCP tools, AI-agent tools and a typed client. Bun and Node.",
5
5
  "keywords": [
6
6
  "bun",