@noetic-tools/core 5.17.0 → 5.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/openrouter.d.ts +7 -0
- package/dist/adapters/openrouter.js +23 -0
- package/dist/conditions/conditions.js +3 -0
- package/dist/harness/agent-harness.d.ts +63 -9
- package/dist/harness/agent-harness.js +222 -22
- package/dist/harness/call-spend.d.ts +34 -0
- package/dist/harness/call-spend.js +125 -0
- package/dist/harness/decide-call.d.ts +3 -0
- package/dist/harness/decide-call.js +51 -12
- package/dist/harness/deps/adapters.d.ts +1 -1
- package/dist/harness/deps/adapters.js +1 -1
- package/dist/harness/deps/runtime.d.ts +3 -1
- package/dist/harness/deps/runtime.js +3 -1
- package/dist/harness/deps/types.d.ts +1 -1
- package/dist/harness/model-call.d.ts +3 -0
- package/dist/harness/model-call.js +123 -66
- package/dist/harness/model-price.d.ts +51 -0
- package/dist/harness/model-price.js +158 -0
- package/dist/harness/model-rounds.d.ts +13 -0
- package/dist/harness/model-rounds.js +42 -2
- package/dist/harness/spend.d.ts +144 -0
- package/dist/harness/spend.js +534 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -0
- package/dist/interpreter/execute-action.js +2 -0
- package/dist/interpreter/execute-control.js +1 -0
- package/dist/interpreter/execute-decide.js +43 -1
- package/dist/interpreter/execute.js +9 -0
- package/dist/runtime/context-impl.d.ts +1 -0
- package/dist/runtime/context-impl.js +1 -0
- package/dist/runtime/drain.d.ts +68 -0
- package/dist/runtime/drain.js +280 -0
- package/dist/runtime/durable/spend-log.d.ts +58 -0
- package/dist/runtime/durable/spend-log.js +133 -0
- package/dist/runtime/durable/step-ledger.d.ts +9 -2
- package/dist/runtime/durable/step-ledger.js +9 -6
- package/dist/runtime/session-runner.d.ts +5 -3
- package/dist/runtime/session-runner.js +9 -4
- package/dist/until/predicates.d.ts +5 -1
- package/dist/until/predicates.js +12 -7
- package/dist/util/spent.d.ts +14 -0
- package/dist/util/spent.js +67 -0
- package/dist/util/status-code.d.ts +5 -0
- package/dist/util/status-code.js +8 -0
- package/package.json +2 -2
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paid dispatches: a record before every paid provider call, and the bill settled
|
|
3
|
+
* afterwards even when the call was cut off (spec 23 § Paid dispatches).
|
|
4
|
+
*
|
|
5
|
+
* A call's record is written before it is sent, gains the provider's generation id
|
|
6
|
+
* when its response headers arrive, and is deleted when its bill reaches the run.
|
|
7
|
+
* A call that ends any other way — cancelled, steered, timed out, its host killed —
|
|
8
|
+
* leaves the record behind. It is then *pending*: held at its ceiling, and priced
|
|
9
|
+
* through the provider's generation lookup once the provider has billed it.
|
|
10
|
+
*/
|
|
11
|
+
import { recordUsage, SpendKind } from '@noetic-tools/types';
|
|
12
|
+
import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
|
|
13
|
+
import { isUnreadable } from '../runtime/durable/spend-log.js';
|
|
14
|
+
import { hashText } from '../runtime/durable/step-ledger.js';
|
|
15
|
+
import { statusOf } from '../util/status-code.js';
|
|
16
|
+
import { ContextImpl, laneBase } from './deps/runtime.js';
|
|
17
|
+
import { ceilingOf, createPriceBook, LOOKUP_TIMEOUT_MS, measureRequest } from './model-price.js';
|
|
18
|
+
import { roundPath } from './model-rounds.js';
|
|
19
|
+
//#region Types
|
|
20
|
+
/** @internal Request header that ties a response back to its dispatch. */
|
|
21
|
+
export const DISPATCH_HEADER = 'x-noetic-dispatch';
|
|
22
|
+
/** @internal Response header carrying OpenRouter's id for the call. */
|
|
23
|
+
export const GENERATION_HEADER = 'x-generation-id';
|
|
24
|
+
const DEFAULT_PATIENCE_MS = 60e3;
|
|
25
|
+
const FIRST_POLL_MS = 1e3;
|
|
26
|
+
const MAX_POLL_MS = 10e3;
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region Spend
|
|
29
|
+
/**
|
|
30
|
+
* @internal
|
|
31
|
+
* One harness's paid dispatches: the live ones it is sending and the pending ones it
|
|
32
|
+
* holds. Pending records come from storage, so any harness over the same storage can
|
|
33
|
+
* settle a call another harness made.
|
|
34
|
+
*/
|
|
35
|
+
export class Spend {
|
|
36
|
+
host;
|
|
37
|
+
live = new Map();
|
|
38
|
+
holds = new Map();
|
|
39
|
+
/**
|
|
40
|
+
* Generation lookups in flight, so two callers never settle one dispatch twice and
|
|
41
|
+
* a reconcile waits for the ones already running.
|
|
42
|
+
*/
|
|
43
|
+
lookups = new Map();
|
|
44
|
+
price;
|
|
45
|
+
constructor(host) {
|
|
46
|
+
this.host = host;
|
|
47
|
+
this.price = createPriceBook(() => host.client());
|
|
48
|
+
}
|
|
49
|
+
/** Write the record for a call about to be sent. A failed write never blocks the call. */
|
|
50
|
+
async open(params) {
|
|
51
|
+
const root = rootOf(params.ctx);
|
|
52
|
+
const path = pathOf(params.ctx);
|
|
53
|
+
const { json, inputTokens } = measureRequest(params.body);
|
|
54
|
+
const record = {
|
|
55
|
+
id: crypto.randomUUID(),
|
|
56
|
+
kind: params.kind,
|
|
57
|
+
model: params.model,
|
|
58
|
+
requestHash: hashText(json),
|
|
59
|
+
inputTokens,
|
|
60
|
+
...(params.maxOutputTokens !== undefined
|
|
61
|
+
? {
|
|
62
|
+
maxOutputTokens: params.maxOutputTokens,
|
|
63
|
+
}
|
|
64
|
+
: {}),
|
|
65
|
+
...(root
|
|
66
|
+
? {
|
|
67
|
+
executionId: root.id,
|
|
68
|
+
threadId: root.threadId,
|
|
69
|
+
}
|
|
70
|
+
: {}),
|
|
71
|
+
...(path !== undefined
|
|
72
|
+
? {
|
|
73
|
+
path: params.round === undefined ? path : roundPath(path, params.round),
|
|
74
|
+
}
|
|
75
|
+
: {}),
|
|
76
|
+
sentAt: new Date().toISOString(),
|
|
77
|
+
};
|
|
78
|
+
const dispatch = new Dispatch(this, this.host.log, record, root);
|
|
79
|
+
this.live.set(record.id, dispatch);
|
|
80
|
+
await quietly('write', () => this.host.log.put(record));
|
|
81
|
+
return dispatch;
|
|
82
|
+
}
|
|
83
|
+
/** Save a live dispatch's generation id. The client's response hook awaits it. */
|
|
84
|
+
noteGeneration(dispatchId, generationId) {
|
|
85
|
+
return this.live.get(dispatchId)?.noteGeneration(generationId) ?? Promise.resolve();
|
|
86
|
+
}
|
|
87
|
+
/** Unsettled dispatches, each with its ceiling. Unreadable ones have none. */
|
|
88
|
+
async pending(executionId) {
|
|
89
|
+
const records = await this.unsettled(executionId);
|
|
90
|
+
return Promise.all(records.map(async (record) => {
|
|
91
|
+
if (isUnreadable(record)) {
|
|
92
|
+
return unreadablePending(record);
|
|
93
|
+
}
|
|
94
|
+
const ceiling = await this.ceilingOf(record);
|
|
95
|
+
return ceiling === undefined
|
|
96
|
+
? record
|
|
97
|
+
: {
|
|
98
|
+
...record,
|
|
99
|
+
ceiling,
|
|
100
|
+
};
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Hold the restored root context's pending dispatches on it, then reconcile them in
|
|
105
|
+
* the background. `ctx.heldCost` is set when this resolves.
|
|
106
|
+
*/
|
|
107
|
+
async adopt(ctx) {
|
|
108
|
+
const root = rootOf(ctx);
|
|
109
|
+
const records = await this.unsettled(ctx.id);
|
|
110
|
+
await Promise.all(records.map((record) => this.hold(record, root)));
|
|
111
|
+
void this.reconcile({
|
|
112
|
+
executionId: ctx.id,
|
|
113
|
+
}).catch((error) => warn('reconcile', error));
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Price every pending dispatch that has a generation id, polling until the provider
|
|
117
|
+
* has, and wait for lookups already running for the same dispatches.
|
|
118
|
+
*/
|
|
119
|
+
async reconcile(opts = {}) {
|
|
120
|
+
const { executionId } = opts;
|
|
121
|
+
const running = [
|
|
122
|
+
...this.lookups.values(),
|
|
123
|
+
]
|
|
124
|
+
.filter((lookup) => executionId === undefined || lookup.executionId === executionId)
|
|
125
|
+
.map((lookup) => lookup.settled);
|
|
126
|
+
const records = await this.unsettled(executionId);
|
|
127
|
+
await Promise.all(records.map((record) => this.hold(record)));
|
|
128
|
+
const patienceMs = opts.patienceMs ?? DEFAULT_PATIENCE_MS;
|
|
129
|
+
const settled = await Promise.all([
|
|
130
|
+
...running,
|
|
131
|
+
...records.map((record) => this.lookup(record, patienceMs)),
|
|
132
|
+
]);
|
|
133
|
+
const unique = new Map();
|
|
134
|
+
for (const settlement of settled) {
|
|
135
|
+
if (settlement) {
|
|
136
|
+
unique.set(settlement.id, settlement);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return [
|
|
140
|
+
...unique.values(),
|
|
141
|
+
];
|
|
142
|
+
}
|
|
143
|
+
/** Settle one pending dispatch at an amount the host asserts. */
|
|
144
|
+
async writeOff(id, opts) {
|
|
145
|
+
if (this.live.has(id)) {
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
const record = this.holds.get(id)?.record ?? (await this.host.log.get(id));
|
|
149
|
+
if (!record) {
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
await this.hold(record);
|
|
153
|
+
return this.settle(id, {
|
|
154
|
+
cost: opts.assumedCost,
|
|
155
|
+
inputTokens: 0,
|
|
156
|
+
outputTokens: 0,
|
|
157
|
+
}, true);
|
|
158
|
+
}
|
|
159
|
+
/** USD held for a thread's pending dispatches. */
|
|
160
|
+
heldFor(threadId) {
|
|
161
|
+
let held = 0;
|
|
162
|
+
for (const hold of this.holds.values()) {
|
|
163
|
+
if (hold.record.threadId === threadId) {
|
|
164
|
+
held += hold.ceiling ?? 0;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return held;
|
|
168
|
+
}
|
|
169
|
+
/** A live dispatch ended. Called by `Dispatch` only. */
|
|
170
|
+
release(id) {
|
|
171
|
+
this.live.delete(id);
|
|
172
|
+
}
|
|
173
|
+
/** A dispatch ended without a bill: hold it and start looking for one. Called by `Dispatch` only. */
|
|
174
|
+
leave(record, root) {
|
|
175
|
+
void this.hold(record, root)
|
|
176
|
+
.then(() => this.lookup(record, DEFAULT_PATIENCE_MS))
|
|
177
|
+
.catch((error) => warn('reconcile', error));
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Stored dispatches not in flight here, all or one execution's. An unreadable record
|
|
181
|
+
* that names no execution may be any execution's, so it is listed with each of them.
|
|
182
|
+
*/
|
|
183
|
+
async unsettled(executionId) {
|
|
184
|
+
const records = await this.host.log.list();
|
|
185
|
+
return records.filter((record) => !this.live.has(record.id) &&
|
|
186
|
+
(executionId === undefined ||
|
|
187
|
+
record.executionId === executionId ||
|
|
188
|
+
(isUnreadable(record) && record.executionId === undefined)));
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Hold `record` at its ceiling, on `ctx` when given. A dispatch already held moves to
|
|
192
|
+
* `ctx`, so an execution restored in this process takes over its cut-off calls.
|
|
193
|
+
*/
|
|
194
|
+
hold(record, ctx) {
|
|
195
|
+
const known = this.holds.get(record.id);
|
|
196
|
+
// A record read mid-write by a store whose writes are not atomic reads whole later:
|
|
197
|
+
// hold it again, now at its ceiling. An unreadable hold holds nothing to release.
|
|
198
|
+
if (known && isUnreadable(known.record) && !isUnreadable(record) && !known.settling) {
|
|
199
|
+
this.holds.delete(record.id);
|
|
200
|
+
return this.hold(record, ctx ?? known.ctx);
|
|
201
|
+
}
|
|
202
|
+
if (known) {
|
|
203
|
+
if (ctx && known.ctx !== ctx) {
|
|
204
|
+
if (known.ctx && known.ceiling !== undefined) {
|
|
205
|
+
known.ctx.heldCost = Math.max(0, known.ctx.heldCost - known.ceiling);
|
|
206
|
+
}
|
|
207
|
+
known.ctx = ctx;
|
|
208
|
+
ctx.heldCost += known.ceiling ?? 0;
|
|
209
|
+
}
|
|
210
|
+
return known.ready;
|
|
211
|
+
}
|
|
212
|
+
const hold = {
|
|
213
|
+
record,
|
|
214
|
+
ctx,
|
|
215
|
+
ready: Promise.resolve(),
|
|
216
|
+
};
|
|
217
|
+
this.holds.set(record.id, hold);
|
|
218
|
+
hold.ready = this.ceilingOf(record).then((ceiling) => {
|
|
219
|
+
if (this.holds.get(record.id) !== hold) {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
hold.ceiling = ceiling;
|
|
223
|
+
if (hold.ctx && ceiling !== undefined) {
|
|
224
|
+
hold.ctx.heldCost += ceiling;
|
|
225
|
+
}
|
|
226
|
+
this.emit(hold, 'spend_pending', isUnreadable(record)
|
|
227
|
+
? {
|
|
228
|
+
id: record.id,
|
|
229
|
+
unreadable: true,
|
|
230
|
+
unbounded: true,
|
|
231
|
+
}
|
|
232
|
+
: {
|
|
233
|
+
id: record.id,
|
|
234
|
+
kind: record.kind,
|
|
235
|
+
model: record.model,
|
|
236
|
+
generationId: record.generationId,
|
|
237
|
+
ceiling,
|
|
238
|
+
...(ceiling === undefined
|
|
239
|
+
? {
|
|
240
|
+
unbounded: true,
|
|
241
|
+
}
|
|
242
|
+
: {}),
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
return hold.ready;
|
|
246
|
+
}
|
|
247
|
+
async ceilingOf(record) {
|
|
248
|
+
if (isUnreadable(record)) {
|
|
249
|
+
return undefined;
|
|
250
|
+
}
|
|
251
|
+
const price = await this.price(record.model);
|
|
252
|
+
return price ? ceilingOf(record, price) : undefined;
|
|
253
|
+
}
|
|
254
|
+
/** Unreadable records carry no generation id, so they are never priced. */
|
|
255
|
+
lookup(record, patienceMs) {
|
|
256
|
+
const generationId = isUnreadable(record) ? undefined : record.generationId;
|
|
257
|
+
if (!generationId) {
|
|
258
|
+
return Promise.resolve(undefined);
|
|
259
|
+
}
|
|
260
|
+
const running = this.lookups.get(record.id);
|
|
261
|
+
if (running) {
|
|
262
|
+
return running.settled;
|
|
263
|
+
}
|
|
264
|
+
const settled = this.poll(record.id, generationId, patienceMs).finally(() => {
|
|
265
|
+
this.lookups.delete(record.id);
|
|
266
|
+
});
|
|
267
|
+
this.lookups.set(record.id, {
|
|
268
|
+
executionId: record.executionId,
|
|
269
|
+
settled,
|
|
270
|
+
});
|
|
271
|
+
return settled;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Ask the provider for the call's bill until it has one. The provider prices a call
|
|
275
|
+
* some seconds after it ends — 7 to 32 s observed — so a lookup that gave up after a
|
|
276
|
+
* few seconds would leave ordinary calls unknown.
|
|
277
|
+
*/
|
|
278
|
+
async poll(id, generationId, patienceMs) {
|
|
279
|
+
const client = this.host.client();
|
|
280
|
+
if (!client) {
|
|
281
|
+
return undefined;
|
|
282
|
+
}
|
|
283
|
+
const deadline = Date.now() + patienceMs;
|
|
284
|
+
for (let wait = FIRST_POLL_MS; this.holds.has(id); wait = Math.min(wait * 2, MAX_POLL_MS)) {
|
|
285
|
+
const bill = await fetchBill(client, generationId);
|
|
286
|
+
if (bill === 'stop') {
|
|
287
|
+
return undefined;
|
|
288
|
+
}
|
|
289
|
+
if (bill) {
|
|
290
|
+
return this.settle(id, bill);
|
|
291
|
+
}
|
|
292
|
+
if (Date.now() + wait > deadline) {
|
|
293
|
+
return undefined;
|
|
294
|
+
}
|
|
295
|
+
await sleep(wait);
|
|
296
|
+
}
|
|
297
|
+
return undefined;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Settle a held dispatch: drop its record, release its hold, and charge its bill
|
|
301
|
+
* once. The record goes first, so a crash part-way loses a settlement rather than
|
|
302
|
+
* counting one twice. A record already gone was settled by another harness over the
|
|
303
|
+
* same storage, which charged it; one that could not be deleted stays held, to be
|
|
304
|
+
* settled by a later reconcile.
|
|
305
|
+
*/
|
|
306
|
+
async settle(id, bill, writtenOff = false) {
|
|
307
|
+
const hold = this.holds.get(id);
|
|
308
|
+
if (!hold || hold.settling) {
|
|
309
|
+
return undefined;
|
|
310
|
+
}
|
|
311
|
+
// The hold stays in place until the record is gone, so a reconcile listing storage
|
|
312
|
+
// meanwhile joins this settlement instead of holding the dispatch again.
|
|
313
|
+
hold.settling = true;
|
|
314
|
+
const taken = await this.take(id);
|
|
315
|
+
if (taken === 'failed') {
|
|
316
|
+
hold.settling = false;
|
|
317
|
+
return undefined;
|
|
318
|
+
}
|
|
319
|
+
this.holds.delete(id);
|
|
320
|
+
if (hold.ctx && hold.ceiling !== undefined) {
|
|
321
|
+
hold.ctx.heldCost = Math.max(0, hold.ctx.heldCost - hold.ceiling);
|
|
322
|
+
}
|
|
323
|
+
if (taken === 'gone') {
|
|
324
|
+
return undefined;
|
|
325
|
+
}
|
|
326
|
+
await this.charge(hold, bill);
|
|
327
|
+
const { executionId, threadId } = hold.record;
|
|
328
|
+
this.emit(hold, 'spend_settled', {
|
|
329
|
+
id,
|
|
330
|
+
cost: bill.cost,
|
|
331
|
+
...(writtenOff
|
|
332
|
+
? {
|
|
333
|
+
writtenOff,
|
|
334
|
+
}
|
|
335
|
+
: {}),
|
|
336
|
+
});
|
|
337
|
+
return {
|
|
338
|
+
id,
|
|
339
|
+
...(executionId !== undefined
|
|
340
|
+
? {
|
|
341
|
+
executionId,
|
|
342
|
+
}
|
|
343
|
+
: {}),
|
|
344
|
+
...(threadId !== undefined
|
|
345
|
+
? {
|
|
346
|
+
threadId,
|
|
347
|
+
}
|
|
348
|
+
: {}),
|
|
349
|
+
...bill,
|
|
350
|
+
...(writtenOff
|
|
351
|
+
? {
|
|
352
|
+
writtenOff: true,
|
|
353
|
+
}
|
|
354
|
+
: {}),
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Charge a bill to one place: the run in flight on its execution, else its thread's
|
|
359
|
+
* session, else the context this harness held it on. A run in flight passes the
|
|
360
|
+
* charge on to its turn's usage, so charging the session too would count it twice.
|
|
361
|
+
*/
|
|
362
|
+
async charge(hold, bill) {
|
|
363
|
+
const charge = {
|
|
364
|
+
inputTokens: bill.inputTokens,
|
|
365
|
+
outputTokens: bill.outputTokens,
|
|
366
|
+
cost: bill.cost,
|
|
367
|
+
billedCost: bill.cost,
|
|
368
|
+
};
|
|
369
|
+
const { executionId, threadId } = hold.record;
|
|
370
|
+
const live = executionId !== undefined ? this.host.liveRoot(executionId) : undefined;
|
|
371
|
+
if (live) {
|
|
372
|
+
recordUsage(live, charge);
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
if (threadId !== undefined && (await this.host.chargeSession(threadId, charge))) {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (hold.ctx) {
|
|
379
|
+
recordUsage(hold.ctx, charge);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/** Delete a held dispatch's record, unless it is already gone. */
|
|
383
|
+
async take(id) {
|
|
384
|
+
try {
|
|
385
|
+
if (!(await this.host.log.get(id))) {
|
|
386
|
+
return 'gone';
|
|
387
|
+
}
|
|
388
|
+
await this.host.log.remove(id);
|
|
389
|
+
return 'taken';
|
|
390
|
+
}
|
|
391
|
+
catch (error) {
|
|
392
|
+
warn('delete', error);
|
|
393
|
+
return 'failed';
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
emit(hold, eventType, data) {
|
|
397
|
+
const threadId = hold.record.threadId;
|
|
398
|
+
emitFrameworkEvent({
|
|
399
|
+
broadcaster: getBroadcaster(hold.ctx) ??
|
|
400
|
+
(threadId !== undefined ? this.host.sessionBroadcaster(threadId) : undefined),
|
|
401
|
+
agentName: this.host.agentName,
|
|
402
|
+
eventType,
|
|
403
|
+
data,
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
//#endregion
|
|
408
|
+
//#region Dispatch
|
|
409
|
+
/**
|
|
410
|
+
* @internal
|
|
411
|
+
* One paid call in flight. Record writes run one at a time, so a generation id saved
|
|
412
|
+
* late never brings back a record that was already deleted.
|
|
413
|
+
*/
|
|
414
|
+
export class Dispatch {
|
|
415
|
+
spend;
|
|
416
|
+
log;
|
|
417
|
+
record;
|
|
418
|
+
root;
|
|
419
|
+
writes = Promise.resolve();
|
|
420
|
+
ended = false;
|
|
421
|
+
constructor(spend, log, record, root) {
|
|
422
|
+
this.spend = spend;
|
|
423
|
+
this.log = log;
|
|
424
|
+
this.record = record;
|
|
425
|
+
this.root = root;
|
|
426
|
+
}
|
|
427
|
+
/** Request headers that tie the response back to this dispatch. */
|
|
428
|
+
get headers() {
|
|
429
|
+
return {
|
|
430
|
+
[DISPATCH_HEADER]: this.record.id,
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
noteGeneration(generationId) {
|
|
434
|
+
if (this.ended || this.record.generationId) {
|
|
435
|
+
return this.writes;
|
|
436
|
+
}
|
|
437
|
+
this.record.generationId = generationId;
|
|
438
|
+
return this.queue('write', () => this.log.put(this.record));
|
|
439
|
+
}
|
|
440
|
+
/** The call's bill reached the run, or the provider refused it: drop the record. */
|
|
441
|
+
settle() {
|
|
442
|
+
if (this.ended) {
|
|
443
|
+
return this.writes;
|
|
444
|
+
}
|
|
445
|
+
this.ended = true;
|
|
446
|
+
this.spend.release(this.record.id);
|
|
447
|
+
return this.queue('delete', () => this.log.remove(this.record.id));
|
|
448
|
+
}
|
|
449
|
+
/** The call is over. Without a settled bill its record stays, pending. */
|
|
450
|
+
end() {
|
|
451
|
+
if (this.ended) {
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
this.ended = true;
|
|
455
|
+
this.spend.release(this.record.id);
|
|
456
|
+
void this.writes.then(() => this.spend.leave(this.record, this.root));
|
|
457
|
+
}
|
|
458
|
+
queue(what, write) {
|
|
459
|
+
this.writes = this.writes.then(() => quietly(what, write));
|
|
460
|
+
return this.writes;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
//#endregion
|
|
464
|
+
//#region Helpers
|
|
465
|
+
/**
|
|
466
|
+
* An unreadable record as `PendingSpend` lists it: `PendingSpend` requires the fields
|
|
467
|
+
* the record lost, so they hold the placeholders its doc names.
|
|
468
|
+
*/
|
|
469
|
+
function unreadablePending(record) {
|
|
470
|
+
return {
|
|
471
|
+
...record,
|
|
472
|
+
kind: SpendKind.Model,
|
|
473
|
+
model: 'unknown',
|
|
474
|
+
requestHash: '',
|
|
475
|
+
inputTokens: 0,
|
|
476
|
+
sentAt: new Date(0).toISOString(),
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
function rootOf(ctx) {
|
|
480
|
+
let node = ctx;
|
|
481
|
+
while (node?.parent) {
|
|
482
|
+
node = node.parent;
|
|
483
|
+
}
|
|
484
|
+
const root = node ? laneBase(node) : undefined;
|
|
485
|
+
return root instanceof ContextImpl ? root : undefined;
|
|
486
|
+
}
|
|
487
|
+
function pathOf(ctx) {
|
|
488
|
+
return ctx instanceof ContextImpl ? ctx.currentDispatch()?.path : undefined;
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* The provider's bill for a call: undefined while it has not priced it yet, 'stop'
|
|
492
|
+
* when asking again cannot help.
|
|
493
|
+
*/
|
|
494
|
+
async function fetchBill(client, generationId) {
|
|
495
|
+
try {
|
|
496
|
+
const { data } = await client.generations.getGeneration({
|
|
497
|
+
id: generationId,
|
|
498
|
+
}, {
|
|
499
|
+
timeoutMs: LOOKUP_TIMEOUT_MS,
|
|
500
|
+
});
|
|
501
|
+
return {
|
|
502
|
+
cost: data.totalCost,
|
|
503
|
+
inputTokens: data.tokensPrompt ?? 0,
|
|
504
|
+
outputTokens: data.tokensCompletion ?? 0,
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
catch (e) {
|
|
508
|
+
const status = statusOf(e);
|
|
509
|
+
const transient = status === undefined || status === 404 || status === 429 || status >= 500;
|
|
510
|
+
return transient ? undefined : 'stop';
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/** Storage is best-effort here, as for checkpoints: a failed write never fails the call. */
|
|
514
|
+
async function quietly(what, write) {
|
|
515
|
+
try {
|
|
516
|
+
await write();
|
|
517
|
+
}
|
|
518
|
+
catch (error) {
|
|
519
|
+
warn(what, error);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
function warn(what, error) {
|
|
523
|
+
console.warn(`Spend: dispatch ${what} failed:`, error instanceof Error ? error.message : String(error));
|
|
524
|
+
}
|
|
525
|
+
/** A wait that does not keep the host process alive. */
|
|
526
|
+
function sleep(ms) {
|
|
527
|
+
return new Promise((resolve) => {
|
|
528
|
+
const timer = setTimeout(resolve, ms);
|
|
529
|
+
if (typeof timer === 'object' && 'unref' in timer) {
|
|
530
|
+
timer.unref();
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
//#endregion
|
package/dist/index.d.ts
CHANGED
|
@@ -164,7 +164,11 @@ export type { LayerTraceSpan, Span, TraceExporter } from '@noetic-tools/types';
|
|
|
164
164
|
/** @public */
|
|
165
165
|
export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent, StreamingItem, } from '@noetic-tools/types';
|
|
166
166
|
/** @public */
|
|
167
|
-
export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, ExecuteOptions, HarnessJudgmentContract, HarnessStatus, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, SessionScope, SessionUsage, } from '@noetic-tools/types';
|
|
167
|
+
export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, DrainCall, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, HarnessJudgmentContract, HarnessStatus, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, SessionScope, SessionUsage, } from '@noetic-tools/types';
|
|
168
|
+
/** @public */
|
|
169
|
+
export type { PendingSpend, ReconcileSpendOptions, SpendSettlement, WriteOffSpendOptions, } from '@noetic-tools/types';
|
|
170
|
+
/** @public */
|
|
171
|
+
export { SpendKind } from '@noetic-tools/types';
|
|
168
172
|
/** @public */
|
|
169
173
|
export type { AfterModelCallParams, AfterModelCallResult, ApproveToolCallParams, BeforeToolCallParams, BeforeToolCallResult, LedgerEntry, OnSteerParams, OnSteerResult, Steer, SteeringConfig, SteeringDecision, SteeringRule, SteeringState, SteerVerdict, ToolApprover, } from '@noetic-tools/types';
|
|
170
174
|
/** @public */
|
package/dist/index.js
CHANGED
|
@@ -107,6 +107,8 @@ export { ChannelSnapshotSchema, CheckpointSchemaVersion, CheckpointSnapshotSchem
|
|
|
107
107
|
/** @public */
|
|
108
108
|
export { Slot } from '@noetic-tools/context';
|
|
109
109
|
/** @public */
|
|
110
|
+
export { SpendKind } from '@noetic-tools/types';
|
|
111
|
+
/** @public */
|
|
110
112
|
export { LedgerEntryKind, SteerAction, SteeringAction, SteerPoint } from '@noetic-tools/types';
|
|
111
113
|
/** @public */
|
|
112
114
|
export { BooleanQuestionSchema, ChoiceQuestionSchema, choiceValues, DECIDE_LIMITS, DecideOutputError, DecideQuestionSchema, DecideQuestionsSchema, routeOutcomes, ScoreQuestionSchema, scoreLevels, } from '@noetic-tools/types';
|
|
@@ -5,6 +5,7 @@ import { createMessage, estimateTokens, extractAssistantText, frameworkCast, isN
|
|
|
5
5
|
import { ToolAttr } from '../observability/genai-attributes.js';
|
|
6
6
|
import { askApproval } from '../runtime/tool-approval.js';
|
|
7
7
|
import { emitToolUi } from '../runtime/tool-ui.js';
|
|
8
|
+
import { chargeSpent } from '../util/spent.js';
|
|
8
9
|
import { allocateBudgets, assembleView, buildToolExecutionContext, ContextImpl, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DEFAULT_PROJECTION, defaultItemSchemaRegistry, disposeLayers, emitFrameworkEvent, getBroadcaster, INTERRUPT_REASON, initLayers, lineageKey, noteCacheOutcome, resolveCacheConfig, resolveLayerTools, returnLayers, shouldEmit, snapshotCwdState, spawnLayers, unpinLayers, } from './action-deps.js';
|
|
9
10
|
import { isServerToolSpec, SteeringAction } from './action-types.js';
|
|
10
11
|
import { openChildSpan, traceChild } from './child-span.js';
|
|
@@ -636,6 +637,7 @@ async function callOnFreshView(scope, recallQuery, rerenderRequests) {
|
|
|
636
637
|
});
|
|
637
638
|
spanAttributes = undefined;
|
|
638
639
|
const response = await baseCtx.harness.callModel(request).catch((e) => {
|
|
640
|
+
chargeSpent(baseCtx, e);
|
|
639
641
|
throw wrapModelError(e, step.id, baseCtx);
|
|
640
642
|
});
|
|
641
643
|
// Track tokens/cost for EVERY model call, including responses steering
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { choiceValues, DecideOutputError, frameworkCast, hashString, NoeticConfigError, NoeticErrorImpl, scoreLevels, } from '@noetic-tools/types';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { GenAI, NoeticAttr } from '../observability/genai-attributes.js';
|
|
4
|
+
import { drainsOf } from '../runtime/drain.js';
|
|
5
|
+
import { chargeSpent } from '../util/spent.js';
|
|
4
6
|
import { allocateBudgets, assembleView, DECISION_PROJECTION, exportSpans, laneBase, } from './action-deps.js';
|
|
5
7
|
import { resolveLazy } from './execute-action.js';
|
|
6
8
|
import { trackUsage } from './message-helpers.js';
|
|
@@ -42,6 +44,7 @@ export async function executeDecide(step, input, ctx, layers) {
|
|
|
42
44
|
samples: step.samples,
|
|
43
45
|
signal: isContextImpl(baseCtx) ? baseCtx.abortSignal : undefined,
|
|
44
46
|
parentSpan: span,
|
|
47
|
+
_billTo: baseCtx,
|
|
45
48
|
});
|
|
46
49
|
trackUsage(baseCtx, {
|
|
47
50
|
items: [],
|
|
@@ -158,12 +161,48 @@ async function resolveModel(step, ctx) {
|
|
|
158
161
|
}
|
|
159
162
|
/** Provider errors arrive raw; give them the step's id and a Noetic kind. */
|
|
160
163
|
async function askHarness(step, ctx, request) {
|
|
164
|
+
const drains = drainsOf(ctx);
|
|
165
|
+
// A graceful stop that began while the step prepared its request sends nothing.
|
|
166
|
+
await drains?.hold(ctx);
|
|
167
|
+
if (ctx.aborted) {
|
|
168
|
+
throw new NoeticErrorImpl({
|
|
169
|
+
kind: 'cancelled',
|
|
170
|
+
reason: ctx.abortReason ?? 'context aborted',
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
const finished = drains?.track(ctx, {
|
|
174
|
+
kind: 'decide',
|
|
175
|
+
model: request.model,
|
|
176
|
+
});
|
|
177
|
+
let bill;
|
|
161
178
|
try {
|
|
162
|
-
|
|
179
|
+
const response = await ctx.harness.decide(request);
|
|
180
|
+
bill = {
|
|
181
|
+
cost: response.cost ?? 0,
|
|
182
|
+
usage: response.usage,
|
|
183
|
+
};
|
|
184
|
+
return response;
|
|
163
185
|
}
|
|
164
186
|
catch (e) {
|
|
187
|
+
// A drain lists the call with what it charged here: an estimate's rounds that
|
|
188
|
+
// failed, or the tokens a failed parse still cost.
|
|
189
|
+
const spent = chargeSpent(ctx, e);
|
|
190
|
+
if (spent) {
|
|
191
|
+
bill = {
|
|
192
|
+
cost: spent.cost ?? 0,
|
|
193
|
+
usage: {
|
|
194
|
+
inputTokens: spent.inputTokens,
|
|
195
|
+
outputTokens: spent.outputTokens,
|
|
196
|
+
cachedTokens: spent.cachedTokens,
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|
|
165
200
|
if (e instanceof DecideOutputError && !ctx.aborted) {
|
|
166
201
|
if (e.usage) {
|
|
202
|
+
bill = {
|
|
203
|
+
cost: e.cost ?? 0,
|
|
204
|
+
usage: e.usage,
|
|
205
|
+
};
|
|
167
206
|
trackUsage(ctx, {
|
|
168
207
|
items: [],
|
|
169
208
|
usage: e.usage,
|
|
@@ -180,6 +219,9 @@ async function askHarness(step, ctx, request) {
|
|
|
180
219
|
}
|
|
181
220
|
throw wrapModelError(e, step.id, ctx);
|
|
182
221
|
}
|
|
222
|
+
finally {
|
|
223
|
+
finished?.(bill);
|
|
224
|
+
}
|
|
183
225
|
}
|
|
184
226
|
//#endregion
|
|
185
227
|
//#region State
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { frameworkCast, NoeticErrorImpl } from '@noetic-tools/types';
|
|
2
2
|
import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
|
|
3
3
|
import { ContextImpl } from '../runtime/context-impl.js';
|
|
4
|
+
import { drainsOf } from '../runtime/drain.js';
|
|
4
5
|
import { REPLAY_KEY_PREFIX } from '../runtime/durable/step-ledger.js';
|
|
5
6
|
import { DetachedHandleImpl } from '../util/detached-handle.js';
|
|
6
7
|
import { allowCustomItems, appendReplayed, beginEmitItems, emitStepItems } from './emit-items.js';
|
|
@@ -252,6 +253,9 @@ async function recordToLedger(opts) {
|
|
|
252
253
|
*/
|
|
253
254
|
export async function execute(step, input, ctx) {
|
|
254
255
|
const baseCtx = frameworkCast(ctx);
|
|
256
|
+
// Under a graceful stop no new step starts: it waits here until the tree is cancelled.
|
|
257
|
+
const drains = drainsOf(baseCtx);
|
|
258
|
+
await drains?.hold(baseCtx);
|
|
255
259
|
// Depth guard — classified as step_failed (not budget_exceeded) because depth
|
|
256
260
|
// is a structural safety limit, not a user-configurable budget field.
|
|
257
261
|
if (ctx.depth >= MAX_DEPTH) {
|
|
@@ -393,6 +397,7 @@ export async function execute(step, input, ctx) {
|
|
|
393
397
|
}
|
|
394
398
|
catch (error) {
|
|
395
399
|
lane?.releaseDispatch();
|
|
400
|
+
drains?.release(frameworkCast(stepCtx));
|
|
396
401
|
throw error;
|
|
397
402
|
}
|
|
398
403
|
finally {
|
|
@@ -427,5 +432,9 @@ export async function execute(step, input, ctx) {
|
|
|
427
432
|
* step produced. A no-op unless the harness has a CheckpointStore, and a failing
|
|
428
433
|
* save is logged rather than thrown — durability must never fail a good step. */
|
|
429
434
|
await baseCtx.checkpoint();
|
|
435
|
+
// The model calls the step made stop counting as in flight only now, once
|
|
436
|
+
// they are charged and the step recorded. A call a failed record leaves
|
|
437
|
+
// behind is released when an enclosing step ends.
|
|
438
|
+
drains?.release(frameworkCast(stepCtx));
|
|
430
439
|
return result;
|
|
431
440
|
}
|