stitchkit 0.136.5 → 0.136.7
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 +13 -0
- package/dist/agent-runtime/providers/openrouter-spend.d.ts +4 -2
- package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -1
- package/dist/entrypoints/postgres.d.ts +6 -0
- package/dist/entrypoints/postgres.d.ts.map +1 -0
- package/dist/entrypoints/postgres.js +134 -0
- package/dist/entrypoints/spend.js +84 -14
- package/dist/postgres/serialize-prisma.d.ts +40 -0
- package/dist/postgres/serialize-prisma.d.ts.map +1 -0
- package/dist/spend/receipt-merge.d.ts +8 -4
- package/dist/spend/receipt-merge.d.ts.map +1 -1
- package/dist/spend/reconcile.d.ts +15 -2
- package/dist/spend/reconcile.d.ts.map +1 -1
- package/dist/spend/schemas.d.ts +1 -0
- package/dist/spend/schemas.d.ts.map +1 -1
- package/llms/agent-runtime-openrouter.txt +1 -1
- package/llms/postgres.txt +37 -0
- package/llms/spend.txt +11 -5
- package/llms/stitchkit.txt +2 -0
- package/llms-full.txt +41 -6
- package/llms.txt +4 -3
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -15,6 +15,19 @@ additive**; the first breaking change landed in 0.10.0. Grep the file for
|
|
|
15
15
|
|
|
16
16
|
## [Unreleased]
|
|
17
17
|
|
|
18
|
+
## [0.136.7] - 2026-12-03
|
|
19
|
+
|
|
20
|
+
### Added
|
|
21
|
+
|
|
22
|
+
- `stitchkit/postgres` — new peer-free `evolving` server entrypoint exporting `withSerializedPrismaTransactions` (plus structural interfaces `PrismaDriverAdapterFactory`, `PrismaDriverAdapter`, `PrismaDriverTransaction`) to serialize statements inside each Prisma interactive transaction (`queryRaw`, `executeRaw`, `commit`, `rollback`, `createSavepoint`, `rollbackToSavepoint`, `releaseSavepoint`) in strict FIFO order without overlapping on one `pg.Client`, while keeping non-transactional pool queries and concurrent transactions parallel, preserving `connectToShadowDb`, `userDefinedTypeParser` re-entrancy, `#private` fields, `Symbol` properties, and `$disconnect()` → reconnect lifecycle without adding `@prisma/adapter-pg` or `pg` as peers. → ADR 0344
|
|
23
|
+
|
|
24
|
+
## [0.136.6] - 2026-12-03
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
|
|
28
|
+
- `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.
|
|
29
|
+
**Affects:** `stitchkit/spend` reconcilePendingSpend, ReconcilePendingSpendOptions, mergeSpendReceipt
|
|
30
|
+
|
|
18
31
|
## [0.136.5] - 2026-12-03
|
|
19
32
|
|
|
20
33
|
### 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
|
|
15
|
-
*
|
|
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
|
|
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"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `stitchkit/postgres` — peer-free helpers for PostgreSQL applications,
|
|
3
|
+
* including per-transaction serialization for Prisma SQL driver adapters.
|
|
4
|
+
*/
|
|
5
|
+
export { type PrismaDriverAdapter, type PrismaDriverAdapterFactory, type PrismaDriverTransaction, withSerializedPrismaTransactions, } from '../postgres/serialize-prisma.js';
|
|
6
|
+
//# sourceMappingURL=postgres.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../../src/entrypoints/postgres.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,0BAA0B,EAC/B,KAAK,uBAAuB,EAC5B,gCAAgC,GACjC,MAAM,8BAA8B,CAAC"}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// src/postgres/serialize-prisma.ts
|
|
2
|
+
var CONNECT_FACTORY_METHODS = new Set([
|
|
3
|
+
"connect",
|
|
4
|
+
"connectToShadowDb"
|
|
5
|
+
]);
|
|
6
|
+
var SERIALIZED_TRANSACTION_METHODS = new Set([
|
|
7
|
+
"queryRaw",
|
|
8
|
+
"executeRaw",
|
|
9
|
+
"commit",
|
|
10
|
+
"rollback",
|
|
11
|
+
"createSavepoint",
|
|
12
|
+
"rollbackToSavepoint",
|
|
13
|
+
"releaseSavepoint"
|
|
14
|
+
]);
|
|
15
|
+
var wrappedFactories = new WeakSet;
|
|
16
|
+
var wrappedAdapters = new WeakSet;
|
|
17
|
+
var wrappedTransactions = new WeakSet;
|
|
18
|
+
function isObject(value) {
|
|
19
|
+
return typeof value === "object" && value !== null;
|
|
20
|
+
}
|
|
21
|
+
function assertWrappableMethods(target, keys, kind) {
|
|
22
|
+
for (const key of keys) {
|
|
23
|
+
const descriptor = Object.getOwnPropertyDescriptor(target, key);
|
|
24
|
+
if (descriptor !== undefined && !descriptor.configurable && !descriptor.writable && "value" in descriptor && typeof descriptor.value === "function") {
|
|
25
|
+
throw new TypeError(`withSerializedPrismaTransactions cannot wrap non-configurable, non-writable ${kind} method "${String(key)}"`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function readOwnProperty(target, key) {
|
|
30
|
+
const descriptor = Object.getOwnPropertyDescriptor(target, key);
|
|
31
|
+
if (descriptor !== undefined && !descriptor.configurable && !descriptor.writable && "value" in descriptor) {
|
|
32
|
+
return descriptor.value;
|
|
33
|
+
}
|
|
34
|
+
const value = Reflect.get(target, key, target);
|
|
35
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
36
|
+
}
|
|
37
|
+
function wrapTransaction(transaction) {
|
|
38
|
+
if (wrappedTransactions.has(transaction))
|
|
39
|
+
return transaction;
|
|
40
|
+
assertWrappableMethods(transaction, SERIALIZED_TRANSACTION_METHODS, "transaction");
|
|
41
|
+
let previous = Promise.resolve();
|
|
42
|
+
const proxy = new Proxy(transaction, {
|
|
43
|
+
get(target, key) {
|
|
44
|
+
if (SERIALIZED_TRANSACTION_METHODS.has(key)) {
|
|
45
|
+
const raw = Reflect.get(target, key, target);
|
|
46
|
+
if (typeof raw !== "function")
|
|
47
|
+
return raw;
|
|
48
|
+
return (...args) => {
|
|
49
|
+
let release = () => {
|
|
50
|
+
return;
|
|
51
|
+
};
|
|
52
|
+
const gate = new Promise((resolve) => {
|
|
53
|
+
release = resolve;
|
|
54
|
+
});
|
|
55
|
+
const wait = previous;
|
|
56
|
+
previous = gate;
|
|
57
|
+
return wait.then(async () => {
|
|
58
|
+
try {
|
|
59
|
+
return await Reflect.apply(raw, target, args);
|
|
60
|
+
} finally {
|
|
61
|
+
release();
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
return readOwnProperty(target, key);
|
|
67
|
+
},
|
|
68
|
+
set(target, key, value) {
|
|
69
|
+
return Reflect.set(target, key, value, target);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
wrappedTransactions.add(proxy);
|
|
73
|
+
return proxy;
|
|
74
|
+
}
|
|
75
|
+
function wrapAdapter(adapter) {
|
|
76
|
+
if (wrappedAdapters.has(adapter))
|
|
77
|
+
return adapter;
|
|
78
|
+
assertWrappableMethods(adapter, ["startTransaction"], "adapter");
|
|
79
|
+
const proxy = new Proxy(adapter, {
|
|
80
|
+
get(target, key) {
|
|
81
|
+
if (key === "startTransaction") {
|
|
82
|
+
const raw = Reflect.get(target, key, target);
|
|
83
|
+
if (typeof raw !== "function")
|
|
84
|
+
return raw;
|
|
85
|
+
return async (...args) => {
|
|
86
|
+
const transaction = await Reflect.apply(raw, target, args);
|
|
87
|
+
return isObject(transaction) ? wrapTransaction(transaction) : transaction;
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
return readOwnProperty(target, key);
|
|
91
|
+
},
|
|
92
|
+
set(target, key, value) {
|
|
93
|
+
return Reflect.set(target, key, value, target);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
wrappedAdapters.add(proxy);
|
|
97
|
+
return proxy;
|
|
98
|
+
}
|
|
99
|
+
function withSerializedPrismaTransactions(adapter) {
|
|
100
|
+
if (!isObject(adapter)) {
|
|
101
|
+
throw new TypeError("withSerializedPrismaTransactions expects a Prisma driver adapter factory object");
|
|
102
|
+
}
|
|
103
|
+
if (wrappedFactories.has(adapter))
|
|
104
|
+
return adapter;
|
|
105
|
+
const provider = Reflect.get(adapter, "provider", adapter);
|
|
106
|
+
const adapterName = Reflect.get(adapter, "adapterName", adapter);
|
|
107
|
+
const connect = Reflect.get(adapter, "connect", adapter);
|
|
108
|
+
if (typeof provider !== "string" || typeof adapterName !== "string" || typeof connect !== "function") {
|
|
109
|
+
throw new TypeError("withSerializedPrismaTransactions expects a Prisma driver adapter factory with string provider, string adapterName and a connect() method");
|
|
110
|
+
}
|
|
111
|
+
assertWrappableMethods(adapter, CONNECT_FACTORY_METHODS, "adapter factory");
|
|
112
|
+
const proxy = new Proxy(adapter, {
|
|
113
|
+
get(target, key) {
|
|
114
|
+
if (CONNECT_FACTORY_METHODS.has(key)) {
|
|
115
|
+
const raw = Reflect.get(target, key, target);
|
|
116
|
+
if (typeof raw !== "function")
|
|
117
|
+
return raw;
|
|
118
|
+
return async (...args) => {
|
|
119
|
+
const connected = await Reflect.apply(raw, target, args);
|
|
120
|
+
return isObject(connected) ? wrapAdapter(connected) : connected;
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
return readOwnProperty(target, key);
|
|
124
|
+
},
|
|
125
|
+
set(target, key, value) {
|
|
126
|
+
return Reflect.set(target, key, value, target);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
wrappedFactories.add(proxy);
|
|
130
|
+
return proxy;
|
|
131
|
+
}
|
|
132
|
+
export {
|
|
133
|
+
withSerializedPrismaTransactions
|
|
134
|
+
};
|
|
@@ -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
|
|
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:
|
|
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:
|
|
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
|
|
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
|
|
459
|
-
const
|
|
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
|
|
533
|
-
if (
|
|
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:
|
|
613
|
+
at: checkedAt.iso,
|
|
544
614
|
outcome: record.receipt?.outcome ?? "pending",
|
|
545
|
-
facts: SpendFactsSchema.parse({ costStatus: "unknown", ...withoutUndefined(
|
|
615
|
+
facts: SpendFactsSchema.parse({ costStatus: "unknown", ...withoutUndefined(facts) })
|
|
546
616
|
});
|
|
547
617
|
} catch (error) {
|
|
548
618
|
result.failed += 1;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serializes interactive transaction statements on a Prisma SQL driver adapter
|
|
3
|
+
* without importing `@prisma/adapter-pg` or `pg`.
|
|
4
|
+
*
|
|
5
|
+
* Prisma 7 can dispatch independent query-plan nodes (such as included
|
|
6
|
+
* relations) concurrently with `Promise.all` onto a single interactive
|
|
7
|
+
* transaction handle. On PostgreSQL (`pg`), all statements of an interactive
|
|
8
|
+
* transaction share one `pg.Client`: `pg@8` queues overlapping calls with a
|
|
9
|
+
* deprecation warning and `pg@9` refuses them.
|
|
10
|
+
*
|
|
11
|
+
* Wrapping the factory keeps queries outside a transaction parallel across the
|
|
12
|
+
* pool, keeps `commit`/`rollback` (which release the `pg.PoolClient`) in the
|
|
13
|
+
* same FIFO queue as `queryRaw`/`executeRaw` and savepoint statements, and
|
|
14
|
+
* preserves the adapter's own connection lifecycle across `$disconnect()` and
|
|
15
|
+
* reconnect.
|
|
16
|
+
*/
|
|
17
|
+
/** Minimal structural handle for a Prisma interactive transaction whose statements run serially on one connection. */
|
|
18
|
+
export interface PrismaDriverTransaction {
|
|
19
|
+
queryRaw(query: never): Promise<unknown>;
|
|
20
|
+
executeRaw(query: never): Promise<unknown>;
|
|
21
|
+
commit(): Promise<unknown>;
|
|
22
|
+
rollback(): Promise<unknown>;
|
|
23
|
+
readonly createSavepoint?: ((name: never) => Promise<unknown>) | undefined;
|
|
24
|
+
readonly rollbackToSavepoint?: ((name: never) => Promise<unknown>) | undefined;
|
|
25
|
+
readonly releaseSavepoint?: ((name: never) => Promise<unknown>) | undefined;
|
|
26
|
+
}
|
|
27
|
+
/** Minimal structural handle for a connected Prisma SQL driver adapter whose interactive transactions are serialized. */
|
|
28
|
+
export interface PrismaDriverAdapter {
|
|
29
|
+
startTransaction(isolationLevel: never): Promise<PrismaDriverTransaction>;
|
|
30
|
+
}
|
|
31
|
+
/** Minimal structural handle for a Prisma SQL driver adapter factory accepted by `withSerializedPrismaTransactions`. */
|
|
32
|
+
export interface PrismaDriverAdapterFactory {
|
|
33
|
+
readonly provider: string;
|
|
34
|
+
readonly adapterName: string;
|
|
35
|
+
connect(): Promise<PrismaDriverAdapter>;
|
|
36
|
+
readonly connectToShadowDb?: (() => Promise<PrismaDriverAdapter>) | undefined;
|
|
37
|
+
}
|
|
38
|
+
/** Wrap a Prisma SQL driver adapter factory so statements inside each interactive transaction run one at a time. */
|
|
39
|
+
export declare function withSerializedPrismaTransactions<F extends PrismaDriverAdapterFactory>(adapter: F): F;
|
|
40
|
+
//# sourceMappingURL=serialize-prisma.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serialize-prisma.d.ts","sourceRoot":"","sources":["../../src/postgres/serialize-prisma.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,sHAAsH;AACtH,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACzC,UAAU,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAC3B,QAAQ,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7B,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC;IAC3E,QAAQ,CAAC,mBAAmB,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC;IAC/E,QAAQ,CAAC,gBAAgB,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC;CAC7E;AAED,yHAAyH;AACzH,MAAM,WAAW,mBAAmB;IAClC,gBAAgB,CAAC,cAAc,EAAE,KAAK,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAC;CAC3E;AAED,wHAAwH;AACxH,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,OAAO,IAAI,OAAO,CAAC,mBAAmB,CAAC,CAAC;IACxC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,CAAC,MAAM,OAAO,CAAC,mBAAmB,CAAC,CAAC,GAAG,SAAS,CAAC;CAC/E;AA6HD,oHAAoH;AACpH,wBAAgB,gCAAgC,CAAC,CAAC,SAAS,0BAA0B,EACnF,OAAO,EAAE,CAAC,GACT,CAAC,CAwCH"}
|
|
@@ -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
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
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;
|
|
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.
|
|
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<SpendReconcileResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reconcile.d.ts","sourceRoot":"","sources":["../../src/spend/reconcile.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"reconcile.d.ts","sourceRoot":"","sources":["../../src/spend/reconcile.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,UAAU,EAEf,KAAK,gBAAgB,EAErB,KAAK,WAAW,EAEjB,MAAM,WAAW,CAAC;AAEnB;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG,CAC5B,MAAM,EAAE,WAAW,KAChB,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,SAAS,CAAC,CAAC;AAE9C,6EAA6E;AAC7E,MAAM,WAAW,4BAA4B;IAC3C,KAAK,EAAE,gBAAgB,CAAC;IACxB,oFAAoF;IACpF,WAAW,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC,CAAC;IACvD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;IACjB,qLAAqL;IACrL,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE;QAAE,MAAM,EAAE,WAAW,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,CAAC;CACtE;AAED,oFAAoF;AACpF,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;CAChB;AAgDD;;;;;;;;;;GAUG;AACH,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,4BAA4B,GACpC,OAAO,CAAC,oBAAoB,CAAC,CA+D/B;AAED;;;GAGG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,EAAE;IAChD,KAAK,EAAE,gBAAgB,CAAC;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;CAClB,GAAG,OAAO,CAAC,MAAM,CAAC,CAkBlB"}
|
package/dist/spend/schemas.d.ts
CHANGED
|
@@ -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;
|
|
1
|
+
{"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/spend/schemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAKxB,eAAO,MAAM,oBAAoB,kBAAmC,CAAC;AAErE;;;;;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,MAAM,sBAAsB,0EAAsD,CAAC;AAC1F,mFAAmF;AACnF,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAEtE,iGAAiG;AACjG,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAM7B,CAAC;AACH,0DAA0D;AAC1D,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAE9D,sEAAsE;AACtE,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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
|
|
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 |
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# stitchkit/postgres — stitchkit docs slice
|
|
2
|
+
|
|
3
|
+
> Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
|
|
4
|
+
> `llms.txt` in this package.
|
|
5
|
+
|
|
6
|
+
Contains: API reference: `stitchkit/postgres` (docs/api/reference.md)
|
|
7
|
+
|
|
8
|
+
==============================================================================
|
|
9
|
+
# API reference: `stitchkit/postgres` (docs/api/reference.md)
|
|
10
|
+
==============================================================================
|
|
11
|
+
|
|
12
|
+
## `stitchkit/postgres`
|
|
13
|
+
|
|
14
|
+
Server-only, peer-free PostgreSQL application helpers. Wraps any Prisma SQL driver adapter factory
|
|
15
|
+
(such as `new PrismaPg(...)`) without importing `@prisma/adapter-pg` or `pg`, so statements inside
|
|
16
|
+
each interactive transaction reach its single PostgreSQL connection one at a time while queries
|
|
17
|
+
outside transactions and separate transactions stay parallel across the pool. See
|
|
18
|
+
[ADR 0344](../decisions/0344-peer-free-prisma-transaction-serialization.md).
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { PrismaPg } from '@prisma/adapter-pg';
|
|
22
|
+
import { withSerializedPrismaTransactions } from 'stitchkit/postgres';
|
|
23
|
+
|
|
24
|
+
const adapter = withSerializedPrismaTransactions(
|
|
25
|
+
new PrismaPg({ connectionString: env.DATABASE_URL }),
|
|
26
|
+
);
|
|
27
|
+
const prisma = new PrismaClient({ adapter });
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
| Export | Kind | Summary |
|
|
31
|
+
|--------|------|---------|
|
|
32
|
+
| `withSerializedPrismaTransactions` | function | wraps a Prisma SQL driver adapter factory (`connect` and optional `connectToShadowDb`) so `queryRaw`, `executeRaw`, `commit`, `rollback` and savepoints inside each interactive transaction execute in strict FIFO order without overlapping on one connection; idempotent and fails fast with `TypeError` on non-factory inputs (such as a raw `pg.Pool`) |
|
|
33
|
+
| `PrismaDriverAdapterFactory` | _type_ | minimal structural Prisma SQL driver adapter factory (`provider`, `adapterName`, `connect`, optional `connectToShadowDb`) accepted by `withSerializedPrismaTransactions` |
|
|
34
|
+
| `PrismaDriverAdapter` | _type_ | minimal structural connected Prisma SQL driver adapter (`startTransaction`) |
|
|
35
|
+
| `PrismaDriverTransaction` | _type_ | minimal structural interactive transaction handle (`queryRaw`, `executeRaw`, `commit`, `rollback` and optional savepoints) |
|
|
36
|
+
|
|
37
|
+
---
|
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
|
|
125
|
-
attempts still `pending` (OpenRouter: `GET /api/v1/generation?id=`) and
|
|
126
|
-
rank-3 receipts.
|
|
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
|
|
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
|
|
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/stitchkit.txt
CHANGED
|
@@ -98,6 +98,7 @@ own, recorded as an ADR.
|
|
|
98
98
|
| `stitchkit/voice` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the mechanics of a live voice reply — `SentenceCutter`, `speakableText`, a `SpeechQueue` that synthesises ahead and stops on interruption, the conversation phases |
|
|
99
99
|
| `stitchkit/sync` | browser **and** server | evolving<br>_redefined in 1 of the 10 minors since 0.127.0, most recently 0.132.0_ | the client half of an offline-first sync — which outbox rows leave next, pending edits on top of remote rows, deletes that win until acknowledged, the cursor session, the push and page wire with an open outcome vocabulary; no driver, runs in Hermes |
|
|
100
100
|
| `stitchkit/sync/postgres` | server (Bun or Node) | evolving<br>_redefined in 0 of the 10 minors since 0.127.0_ | the server half — versions that commit in order, a ledger that runs each change once, a feed of what changed, inside the app's own transaction; a memory store and `checkSyncStore` |
|
|
101
|
+
| `stitchkit/postgres` | server (Bun or Node) | evolving<br>_redefined in 0 of the 1 minor since 0.136.7_ | peer-free PostgreSQL helpers — `withSerializedPrismaTransactions` queues interactive transaction statements one at a time on a Prisma SQL driver adapter (`PrismaPg`) while keeping pool queries parallel |
|
|
101
102
|
| `stitchkit/geo` | server (Bun or Node) | evolving<br>_redefined in 2 of the 43 minors since 0.94.0, most recently 0.127.0_ | managed GeoIP reader generations, last-known-good reload and the optional MaxMind adapter |
|
|
102
103
|
| `stitchkit/geo/contract` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the place snapshot schema, for a shared contract that stores or sends `GeoAttribution`; brings `zod` |
|
|
103
104
|
| `stitchkit/xlsx` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | a workbook from rows and typed columns, with no dependency; text never runs as a formula |
|
|
@@ -259,6 +260,7 @@ map — feature → packages:
|
|
|
259
260
|
| Anthropic native provider (`stitchkit/agent-runtime/anthropic`) | — (peer-free) |
|
|
260
261
|
| AI SDK runtime adapter (`stitchkit/agent-runtime/ai-sdk`) | `ai` |
|
|
261
262
|
| Postgres agent store (`stitchkit/agent-runtime/postgres`) | — (the application's own Postgres client) |
|
|
263
|
+
| Postgres Prisma transaction serializer (`stitchkit/postgres`) | — (peer-free; wraps the application's own Prisma SQL driver adapter) |
|
|
262
264
|
| SQLite agent store (`stitchkit/agent-runtime/sqlite/bun` or `/node`) | — (runtime built-in) |
|
|
263
265
|
| Agent executor — Claude Agent SDK leaf (`stitchkit/agent-executor/claude-sdk`) | `@anthropic-ai/claude-agent-sdk` |
|
|
264
266
|
| Agent executor — consumer testing kit (`stitchkit/agent-executor/testing`) | — |
|
package/llms-full.txt
CHANGED
|
@@ -89,6 +89,7 @@ own, recorded as an ADR.
|
|
|
89
89
|
| `stitchkit/voice` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the mechanics of a live voice reply — `SentenceCutter`, `speakableText`, a `SpeechQueue` that synthesises ahead and stops on interruption, the conversation phases |
|
|
90
90
|
| `stitchkit/sync` | browser **and** server | evolving<br>_redefined in 1 of the 10 minors since 0.127.0, most recently 0.132.0_ | the client half of an offline-first sync — which outbox rows leave next, pending edits on top of remote rows, deletes that win until acknowledged, the cursor session, the push and page wire with an open outcome vocabulary; no driver, runs in Hermes |
|
|
91
91
|
| `stitchkit/sync/postgres` | server (Bun or Node) | evolving<br>_redefined in 0 of the 10 minors since 0.127.0_ | the server half — versions that commit in order, a ledger that runs each change once, a feed of what changed, inside the app's own transaction; a memory store and `checkSyncStore` |
|
|
92
|
+
| `stitchkit/postgres` | server (Bun or Node) | evolving<br>_redefined in 0 of the 1 minor since 0.136.7_ | peer-free PostgreSQL helpers — `withSerializedPrismaTransactions` queues interactive transaction statements one at a time on a Prisma SQL driver adapter (`PrismaPg`) while keeping pool queries parallel |
|
|
92
93
|
| `stitchkit/geo` | server (Bun or Node) | evolving<br>_redefined in 2 of the 43 minors since 0.94.0, most recently 0.127.0_ | managed GeoIP reader generations, last-known-good reload and the optional MaxMind adapter |
|
|
93
94
|
| `stitchkit/geo/contract` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the place snapshot schema, for a shared contract that stores or sends `GeoAttribution`; brings `zod` |
|
|
94
95
|
| `stitchkit/xlsx` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | a workbook from rows and typed columns, with no dependency; text never runs as a formula |
|
|
@@ -250,6 +251,7 @@ map — feature → packages:
|
|
|
250
251
|
| Anthropic native provider (`stitchkit/agent-runtime/anthropic`) | — (peer-free) |
|
|
251
252
|
| AI SDK runtime adapter (`stitchkit/agent-runtime/ai-sdk`) | `ai` |
|
|
252
253
|
| Postgres agent store (`stitchkit/agent-runtime/postgres`) | — (the application's own Postgres client) |
|
|
254
|
+
| Postgres Prisma transaction serializer (`stitchkit/postgres`) | — (peer-free; wraps the application's own Prisma SQL driver adapter) |
|
|
253
255
|
| SQLite agent store (`stitchkit/agent-runtime/sqlite/bun` or `/node`) | — (runtime built-in) |
|
|
254
256
|
| Agent executor — Claude Agent SDK leaf (`stitchkit/agent-executor/claude-sdk`) | `@anthropic-ai/claude-agent-sdk` |
|
|
255
257
|
| Agent executor — consumer testing kit (`stitchkit/agent-executor/testing`) | — |
|
|
@@ -17992,9 +17994,15 @@ nor stored refuses the call.
|
|
|
17992
17994
|
|
|
17993
17995
|
## Afterwards
|
|
17994
17996
|
|
|
17995
|
-
- `reconcilePendingSpend({ store, reconcilers })` asks each provider for
|
|
17996
|
-
attempts still `pending` (OpenRouter: `GET /api/v1/generation?id=`) and
|
|
17997
|
-
rank-3 receipts.
|
|
17997
|
+
- `reconcilePendingSpend({ store, reconcilers, maxPendingAgeMs })` asks each provider for
|
|
17998
|
+
the cost of attempts still `pending` (OpenRouter: `GET /api/v1/generation?id=`) and
|
|
17999
|
+
settles rank-3 receipts. Pass `maxPendingAgeMs` so an attempt whose reconciler still
|
|
18000
|
+
returns `undefined` (for example a 404 or missing `total_cost`) after that age — measured
|
|
18001
|
+
from `record.receipt.at`, or `record.attempt.startedAt` when no receipt exists — settles
|
|
18002
|
+
as `costStatus: 'unknown'` with `failureCode: 'price-never-reported'` instead of staying
|
|
18003
|
+
`pending` forever and filling `pendingCosts`; before `maxPendingAgeMs`, or when omitted,
|
|
18004
|
+
`undefined` keeps the row `pending`, and reconciler failures stay `pending` for the next
|
|
18005
|
+
pass. The store needs `pendingCosts`.
|
|
17998
18006
|
- `closeOrphanedSpend({ store, olderThanMs })` closes attempts whose process never
|
|
17999
18007
|
came back to them as `orphaned`, cost `unknown`. The store needs `openAttempts`.
|
|
18000
18008
|
|
|
@@ -30371,7 +30379,7 @@ Server-only, peer-free native OpenRouter provider over Web `fetch` and Chat Comp
|
|
|
30371
30379
|
| `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
30380
|
| `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
30381
|
| `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
|
|
30382
|
+
| `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
30383
|
| `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
30384
|
| `OpenRouterModelCatalogOptions` | _type_ | optional static/dynamic credential, `baseUrl` override, timeout, clock and injected `OpenRouterFetch` for catalog loading |
|
|
30377
30385
|
| `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 +31385,8 @@ Peer-free, server-only spend accounting for paid model APIs (→ [guide](../guid
|
|
|
31377
31385
|
| `runWithSpendAttribution` / `getSpendAttribution` | function | the attribution of every gateway call in a call chain (AsyncLocalStorage); nested calls refine, `labels` merge |
|
|
31378
31386
|
| `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
31387
|
| `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
|
|
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
|
|
31388
|
+
| `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) |
|
|
31389
|
+
| `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
31390
|
| `closeOrphanedSpend` | function | closes attempts left open longer than `olderThanMs` as `orphaned` with an `unknown` cost |
|
|
31383
31391
|
| `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
31392
|
|
|
@@ -31843,6 +31851,33 @@ The server half, inside the application's own transaction. See the [sync guide](
|
|
|
31843
31851
|
|
|
31844
31852
|
---
|
|
31845
31853
|
|
|
31854
|
+
## `stitchkit/postgres`
|
|
31855
|
+
|
|
31856
|
+
Server-only, peer-free PostgreSQL application helpers. Wraps any Prisma SQL driver adapter factory
|
|
31857
|
+
(such as `new PrismaPg(...)`) without importing `@prisma/adapter-pg` or `pg`, so statements inside
|
|
31858
|
+
each interactive transaction reach its single PostgreSQL connection one at a time while queries
|
|
31859
|
+
outside transactions and separate transactions stay parallel across the pool. See
|
|
31860
|
+
[ADR 0344](../decisions/0344-peer-free-prisma-transaction-serialization.md).
|
|
31861
|
+
|
|
31862
|
+
```ts
|
|
31863
|
+
import { PrismaPg } from '@prisma/adapter-pg';
|
|
31864
|
+
import { withSerializedPrismaTransactions } from 'stitchkit/postgres';
|
|
31865
|
+
|
|
31866
|
+
const adapter = withSerializedPrismaTransactions(
|
|
31867
|
+
new PrismaPg({ connectionString: env.DATABASE_URL }),
|
|
31868
|
+
);
|
|
31869
|
+
const prisma = new PrismaClient({ adapter });
|
|
31870
|
+
```
|
|
31871
|
+
|
|
31872
|
+
| Export | Kind | Summary |
|
|
31873
|
+
|--------|------|---------|
|
|
31874
|
+
| `withSerializedPrismaTransactions` | function | wraps a Prisma SQL driver adapter factory (`connect` and optional `connectToShadowDb`) so `queryRaw`, `executeRaw`, `commit`, `rollback` and savepoints inside each interactive transaction execute in strict FIFO order without overlapping on one connection; idempotent and fails fast with `TypeError` on non-factory inputs (such as a raw `pg.Pool`) |
|
|
31875
|
+
| `PrismaDriverAdapterFactory` | _type_ | minimal structural Prisma SQL driver adapter factory (`provider`, `adapterName`, `connect`, optional `connectToShadowDb`) accepted by `withSerializedPrismaTransactions` |
|
|
31876
|
+
| `PrismaDriverAdapter` | _type_ | minimal structural connected Prisma SQL driver adapter (`startTransaction`) |
|
|
31877
|
+
| `PrismaDriverTransaction` | _type_ | minimal structural interactive transaction handle (`queryRaw`, `executeRaw`, `commit`, `rollback` and optional savepoints) |
|
|
31878
|
+
|
|
31879
|
+
---
|
|
31880
|
+
|
|
31846
31881
|
## `stitchkit/geo`
|
|
31847
31882
|
|
|
31848
31883
|
Server-only managed GeoIP generations. Applications own database acquisition,
|
package/llms.txt
CHANGED
|
@@ -9,7 +9,7 @@ Build with stitchkit: define a contract once, then `implement` it and serve it (
|
|
|
9
9
|
Load the slice for each entrypoint your code imports — `import … from 'stitchkit/server'` → `llms/server.txt`; the root `stitchkit` import → `llms/stitchkit.txt`. A slice holds that entrypoint's API reference section and the guide pages whose home it is; every guide lives in exactly one slice, and a slice that needs another's guide names it under "Also read". Each file is at most 50.0 KB; a longer one continues in numbered parts, each naming the next at its top. Moving across versions: load `llms/upgrading.txt` and the range slices it lists between your version and the target. `llms-full.txt` inlines everything; it is far larger than a context window, so do not read it whole.
|
|
10
10
|
|
|
11
11
|
## Entrypoint slices
|
|
12
|
-
- **stitchkit**: [llms/stitchkit.txt](llms/stitchkit.txt)
|
|
12
|
+
- **stitchkit**: [llms/stitchkit.txt](llms/stitchkit.txt) 45.0 KB → [llms/stitchkit.2.txt](llms/stitchkit.2.txt) 47.2 KB → [llms/stitchkit.3.txt](llms/stitchkit.3.txt) 29.4 KB
|
|
13
13
|
- **stitchkit/live**: [llms/live.txt](llms/live.txt) 22.9 KB
|
|
14
14
|
- **stitchkit/react**: [llms/react.txt](llms/react.txt) 8.7 KB
|
|
15
15
|
- **stitchkit/react/keyboard**: [llms/react-keyboard.txt](llms/react-keyboard.txt) 22.7 KB
|
|
@@ -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)
|
|
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)
|
|
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
|
|
@@ -76,6 +76,7 @@ Load the slice for each entrypoint your code imports — `import … from 'stitc
|
|
|
76
76
|
- **stitchkit/voice**: [llms/voice.txt](llms/voice.txt) 5.2 KB
|
|
77
77
|
- **stitchkit/sync**: [llms/sync.txt](llms/sync.txt) 25.3 KB
|
|
78
78
|
- **stitchkit/sync/postgres**: [llms/sync-postgres.txt](llms/sync-postgres.txt) 2.3 KB
|
|
79
|
+
- **stitchkit/postgres**: [llms/postgres.txt](llms/postgres.txt) 2.1 KB
|
|
79
80
|
- **stitchkit/oauth**: [llms/oauth.txt](llms/oauth.txt) 6.7 KB
|
|
80
81
|
- **stitchkit/google**: [llms/google.txt](llms/google.txt) 1.4 KB
|
|
81
82
|
- **stitchkit/declaration**: [llms/declaration.txt](llms/declaration.txt) 15.9 KB
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stitchkit",
|
|
3
|
-
"version": "0.136.
|
|
3
|
+
"version": "0.136.7",
|
|
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",
|
|
@@ -325,6 +325,10 @@
|
|
|
325
325
|
"types": "./dist/entrypoints/sync/postgres.d.ts",
|
|
326
326
|
"import": "./dist/entrypoints/sync/postgres.js"
|
|
327
327
|
},
|
|
328
|
+
"./postgres": {
|
|
329
|
+
"types": "./dist/entrypoints/postgres.d.ts",
|
|
330
|
+
"import": "./dist/entrypoints/postgres.js"
|
|
331
|
+
},
|
|
328
332
|
"./oauth": {
|
|
329
333
|
"types": "./dist/entrypoints/oauth.d.ts",
|
|
330
334
|
"import": "./dist/entrypoints/oauth.js"
|