@noetic-tools/core 5.17.0 → 5.18.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/conditions/conditions.js +1 -0
- package/dist/harness/agent-harness.d.ts +54 -9
- package/dist/harness/agent-harness.js +179 -22
- package/dist/harness/decide-call.d.ts +3 -0
- package/dist/harness/decide-call.js +45 -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 +87 -17
- package/dist/harness/model-price.d.ts +35 -0
- package/dist/harness/model-price.js +81 -0
- package/dist/harness/model-rounds.d.ts +2 -0
- package/dist/harness/model-rounds.js +5 -1
- package/dist/harness/spend.d.ts +138 -0
- package/dist/harness/spend.js +494 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -0
- package/dist/interpreter/execute-control.js +1 -0
- package/dist/interpreter/execute-decide.js +18 -0
- 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 +77 -0
- package/dist/runtime/drain.js +268 -0
- package/dist/runtime/durable/spend-log.d.ts +38 -0
- package/dist/runtime/durable/spend-log.js +65 -0
- package/dist/runtime/durable/step-ledger.d.ts +6 -0
- package/dist/runtime/durable/step-ledger.js +3 -2
- 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/status-code.d.ts +5 -0
- package/dist/util/status-code.js +8 -0
- package/package.json +2 -2
|
@@ -0,0 +1,494 @@
|
|
|
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 { estimateTokens, recordUsage } from '@noetic-tools/types';
|
|
12
|
+
import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
|
|
13
|
+
import { hashText } from '../runtime/durable/step-ledger.js';
|
|
14
|
+
import { statusOf } from '../util/status-code.js';
|
|
15
|
+
import { ContextImpl, laneBase } from './deps/runtime.js';
|
|
16
|
+
import { ceilingOf, createPriceBook, LOOKUP_TIMEOUT_MS } from './model-price.js';
|
|
17
|
+
import { roundPath } from './model-rounds.js';
|
|
18
|
+
//#region Types
|
|
19
|
+
/** @internal Request header that ties a response back to its dispatch. */
|
|
20
|
+
export const DISPATCH_HEADER = 'x-noetic-dispatch';
|
|
21
|
+
/** @internal Response header carrying OpenRouter's id for the call. */
|
|
22
|
+
export const GENERATION_HEADER = 'x-generation-id';
|
|
23
|
+
const DEFAULT_PATIENCE_MS = 60e3;
|
|
24
|
+
const FIRST_POLL_MS = 1e3;
|
|
25
|
+
const MAX_POLL_MS = 10e3;
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region Spend
|
|
28
|
+
/**
|
|
29
|
+
* @internal
|
|
30
|
+
* One harness's paid dispatches: the live ones it is sending and the pending ones it
|
|
31
|
+
* holds. Pending records come from storage, so any harness over the same storage can
|
|
32
|
+
* settle a call another harness made.
|
|
33
|
+
*/
|
|
34
|
+
export class Spend {
|
|
35
|
+
host;
|
|
36
|
+
live = new Map();
|
|
37
|
+
holds = new Map();
|
|
38
|
+
/**
|
|
39
|
+
* Generation lookups in flight, so two callers never settle one dispatch twice and
|
|
40
|
+
* a reconcile waits for the ones already running.
|
|
41
|
+
*/
|
|
42
|
+
lookups = new Map();
|
|
43
|
+
price;
|
|
44
|
+
constructor(host) {
|
|
45
|
+
this.host = host;
|
|
46
|
+
this.price = createPriceBook(() => host.client());
|
|
47
|
+
}
|
|
48
|
+
/** Write the record for a call about to be sent. A failed write never blocks the call. */
|
|
49
|
+
async open(params) {
|
|
50
|
+
const root = rootOf(params.ctx);
|
|
51
|
+
const path = pathOf(params.ctx);
|
|
52
|
+
const json = JSON.stringify(params.body) ?? '';
|
|
53
|
+
const record = {
|
|
54
|
+
id: crypto.randomUUID(),
|
|
55
|
+
kind: params.kind,
|
|
56
|
+
model: params.model,
|
|
57
|
+
requestHash: hashText(json),
|
|
58
|
+
inputTokens: estimateTokens(json),
|
|
59
|
+
...(params.maxOutputTokens !== undefined
|
|
60
|
+
? {
|
|
61
|
+
maxOutputTokens: params.maxOutputTokens,
|
|
62
|
+
}
|
|
63
|
+
: {}),
|
|
64
|
+
...(root
|
|
65
|
+
? {
|
|
66
|
+
executionId: root.id,
|
|
67
|
+
threadId: root.threadId,
|
|
68
|
+
}
|
|
69
|
+
: {}),
|
|
70
|
+
...(path !== undefined
|
|
71
|
+
? {
|
|
72
|
+
path: params.round === undefined ? path : roundPath(path, params.round),
|
|
73
|
+
}
|
|
74
|
+
: {}),
|
|
75
|
+
sentAt: new Date().toISOString(),
|
|
76
|
+
};
|
|
77
|
+
const dispatch = new Dispatch(this, this.host.log, record, root);
|
|
78
|
+
this.live.set(record.id, dispatch);
|
|
79
|
+
await quietly('write', () => this.host.log.put(record));
|
|
80
|
+
return dispatch;
|
|
81
|
+
}
|
|
82
|
+
/** Save a live dispatch's generation id. The client's response hook awaits it. */
|
|
83
|
+
noteGeneration(dispatchId, generationId) {
|
|
84
|
+
return this.live.get(dispatchId)?.noteGeneration(generationId) ?? Promise.resolve();
|
|
85
|
+
}
|
|
86
|
+
/** Unsettled dispatches, each with its ceiling. */
|
|
87
|
+
async pending(executionId) {
|
|
88
|
+
const records = await this.unsettled(executionId);
|
|
89
|
+
return Promise.all(records.map(async (record) => {
|
|
90
|
+
const ceiling = await this.ceilingOf(record);
|
|
91
|
+
return ceiling === undefined
|
|
92
|
+
? record
|
|
93
|
+
: {
|
|
94
|
+
...record,
|
|
95
|
+
ceiling,
|
|
96
|
+
};
|
|
97
|
+
}));
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Hold the restored root context's pending dispatches on it, then reconcile them in
|
|
101
|
+
* the background. `ctx.heldCost` is set when this resolves.
|
|
102
|
+
*/
|
|
103
|
+
async adopt(ctx) {
|
|
104
|
+
const root = rootOf(ctx);
|
|
105
|
+
const records = await this.unsettled(ctx.id);
|
|
106
|
+
await Promise.all(records.map((record) => this.hold(record, root)));
|
|
107
|
+
void this.reconcile({
|
|
108
|
+
executionId: ctx.id,
|
|
109
|
+
}).catch((error) => warn('reconcile', error));
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Price every pending dispatch that has a generation id, polling until the provider
|
|
113
|
+
* has, and wait for lookups already running for the same dispatches.
|
|
114
|
+
*/
|
|
115
|
+
async reconcile(opts = {}) {
|
|
116
|
+
const { executionId } = opts;
|
|
117
|
+
const running = [
|
|
118
|
+
...this.lookups.values(),
|
|
119
|
+
]
|
|
120
|
+
.filter((lookup) => executionId === undefined || lookup.executionId === executionId)
|
|
121
|
+
.map((lookup) => lookup.settled);
|
|
122
|
+
const records = await this.unsettled(executionId);
|
|
123
|
+
await Promise.all(records.map((record) => this.hold(record)));
|
|
124
|
+
const patienceMs = opts.patienceMs ?? DEFAULT_PATIENCE_MS;
|
|
125
|
+
const settled = await Promise.all([
|
|
126
|
+
...running,
|
|
127
|
+
...records.map((record) => this.lookup(record, patienceMs)),
|
|
128
|
+
]);
|
|
129
|
+
const unique = new Map();
|
|
130
|
+
for (const settlement of settled) {
|
|
131
|
+
if (settlement) {
|
|
132
|
+
unique.set(settlement.id, settlement);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return [
|
|
136
|
+
...unique.values(),
|
|
137
|
+
];
|
|
138
|
+
}
|
|
139
|
+
/** Settle one pending dispatch at an amount the host asserts. */
|
|
140
|
+
async writeOff(id, opts) {
|
|
141
|
+
if (this.live.has(id)) {
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
const record = this.holds.get(id)?.record ?? (await this.host.log.get(id));
|
|
145
|
+
if (!record) {
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
await this.hold(record);
|
|
149
|
+
return this.settle(id, {
|
|
150
|
+
cost: opts.assumedCost,
|
|
151
|
+
inputTokens: 0,
|
|
152
|
+
outputTokens: 0,
|
|
153
|
+
}, true);
|
|
154
|
+
}
|
|
155
|
+
/** USD held for a thread's pending dispatches. */
|
|
156
|
+
heldFor(threadId) {
|
|
157
|
+
let held = 0;
|
|
158
|
+
for (const hold of this.holds.values()) {
|
|
159
|
+
if (hold.record.threadId === threadId) {
|
|
160
|
+
held += hold.ceiling ?? 0;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return held;
|
|
164
|
+
}
|
|
165
|
+
/** A live dispatch ended. Called by `Dispatch` only. */
|
|
166
|
+
release(id) {
|
|
167
|
+
this.live.delete(id);
|
|
168
|
+
}
|
|
169
|
+
/** A dispatch ended without a bill: hold it and start looking for one. Called by `Dispatch` only. */
|
|
170
|
+
leave(record, root) {
|
|
171
|
+
void this.hold(record, root)
|
|
172
|
+
.then(() => this.lookup(record, DEFAULT_PATIENCE_MS))
|
|
173
|
+
.catch((error) => warn('reconcile', error));
|
|
174
|
+
}
|
|
175
|
+
async unsettled(executionId) {
|
|
176
|
+
const records = await this.host.log.list();
|
|
177
|
+
return records.filter((record) => !this.live.has(record.id) &&
|
|
178
|
+
(executionId === undefined || record.executionId === executionId));
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Hold `record` at its ceiling, on `ctx` when given. A dispatch already held moves to
|
|
182
|
+
* `ctx`, so an execution restored in this process takes over its cut-off calls.
|
|
183
|
+
*/
|
|
184
|
+
hold(record, ctx) {
|
|
185
|
+
const known = this.holds.get(record.id);
|
|
186
|
+
if (known) {
|
|
187
|
+
if (ctx && known.ctx !== ctx) {
|
|
188
|
+
if (known.ctx && known.ceiling !== undefined) {
|
|
189
|
+
known.ctx.heldCost = Math.max(0, known.ctx.heldCost - known.ceiling);
|
|
190
|
+
}
|
|
191
|
+
known.ctx = ctx;
|
|
192
|
+
ctx.heldCost += known.ceiling ?? 0;
|
|
193
|
+
}
|
|
194
|
+
return known.ready;
|
|
195
|
+
}
|
|
196
|
+
const hold = {
|
|
197
|
+
record,
|
|
198
|
+
ctx,
|
|
199
|
+
ready: Promise.resolve(),
|
|
200
|
+
};
|
|
201
|
+
this.holds.set(record.id, hold);
|
|
202
|
+
hold.ready = this.ceilingOf(record).then((ceiling) => {
|
|
203
|
+
if (this.holds.get(record.id) !== hold) {
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
hold.ceiling = ceiling;
|
|
207
|
+
if (hold.ctx && ceiling !== undefined) {
|
|
208
|
+
hold.ctx.heldCost += ceiling;
|
|
209
|
+
}
|
|
210
|
+
this.emit(hold, 'spend_pending', {
|
|
211
|
+
id: record.id,
|
|
212
|
+
kind: record.kind,
|
|
213
|
+
model: record.model,
|
|
214
|
+
generationId: record.generationId,
|
|
215
|
+
ceiling,
|
|
216
|
+
...(ceiling === undefined
|
|
217
|
+
? {
|
|
218
|
+
unbounded: true,
|
|
219
|
+
}
|
|
220
|
+
: {}),
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
return hold.ready;
|
|
224
|
+
}
|
|
225
|
+
async ceilingOf(record) {
|
|
226
|
+
const price = await this.price(record.model);
|
|
227
|
+
return price ? ceilingOf(record, price) : undefined;
|
|
228
|
+
}
|
|
229
|
+
lookup(record, patienceMs) {
|
|
230
|
+
const generationId = record.generationId;
|
|
231
|
+
if (!generationId) {
|
|
232
|
+
return Promise.resolve(undefined);
|
|
233
|
+
}
|
|
234
|
+
const running = this.lookups.get(record.id);
|
|
235
|
+
if (running) {
|
|
236
|
+
return running.settled;
|
|
237
|
+
}
|
|
238
|
+
const settled = this.poll(record.id, generationId, patienceMs).finally(() => {
|
|
239
|
+
this.lookups.delete(record.id);
|
|
240
|
+
});
|
|
241
|
+
this.lookups.set(record.id, {
|
|
242
|
+
executionId: record.executionId,
|
|
243
|
+
settled,
|
|
244
|
+
});
|
|
245
|
+
return settled;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Ask the provider for the call's bill until it has one. The provider prices a call
|
|
249
|
+
* some seconds after it ends — 7 to 32 s observed — so a lookup that gave up after a
|
|
250
|
+
* few seconds would leave ordinary calls unknown.
|
|
251
|
+
*/
|
|
252
|
+
async poll(id, generationId, patienceMs) {
|
|
253
|
+
const client = this.host.client();
|
|
254
|
+
if (!client) {
|
|
255
|
+
return undefined;
|
|
256
|
+
}
|
|
257
|
+
const deadline = Date.now() + patienceMs;
|
|
258
|
+
for (let wait = FIRST_POLL_MS; this.holds.has(id); wait = Math.min(wait * 2, MAX_POLL_MS)) {
|
|
259
|
+
const bill = await fetchBill(client, generationId);
|
|
260
|
+
if (bill === 'stop') {
|
|
261
|
+
return undefined;
|
|
262
|
+
}
|
|
263
|
+
if (bill) {
|
|
264
|
+
return this.settle(id, bill);
|
|
265
|
+
}
|
|
266
|
+
if (Date.now() + wait > deadline) {
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
await sleep(wait);
|
|
270
|
+
}
|
|
271
|
+
return undefined;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Settle a held dispatch: drop its record, release its hold, and charge its bill
|
|
275
|
+
* once. The record goes first, so a crash part-way loses a settlement rather than
|
|
276
|
+
* counting one twice. A record already gone was settled by another harness over the
|
|
277
|
+
* same storage, which charged it; one that could not be deleted stays held, to be
|
|
278
|
+
* settled by a later reconcile.
|
|
279
|
+
*/
|
|
280
|
+
async settle(id, bill, writtenOff = false) {
|
|
281
|
+
const hold = this.holds.get(id);
|
|
282
|
+
if (!hold || hold.settling) {
|
|
283
|
+
return undefined;
|
|
284
|
+
}
|
|
285
|
+
// The hold stays in place until the record is gone, so a reconcile listing storage
|
|
286
|
+
// meanwhile joins this settlement instead of holding the dispatch again.
|
|
287
|
+
hold.settling = true;
|
|
288
|
+
const taken = await this.take(id);
|
|
289
|
+
if (taken === 'failed') {
|
|
290
|
+
hold.settling = false;
|
|
291
|
+
return undefined;
|
|
292
|
+
}
|
|
293
|
+
this.holds.delete(id);
|
|
294
|
+
if (hold.ctx && hold.ceiling !== undefined) {
|
|
295
|
+
hold.ctx.heldCost = Math.max(0, hold.ctx.heldCost - hold.ceiling);
|
|
296
|
+
}
|
|
297
|
+
if (taken === 'gone') {
|
|
298
|
+
return undefined;
|
|
299
|
+
}
|
|
300
|
+
await this.charge(hold, bill);
|
|
301
|
+
const { executionId, threadId } = hold.record;
|
|
302
|
+
this.emit(hold, 'spend_settled', {
|
|
303
|
+
id,
|
|
304
|
+
cost: bill.cost,
|
|
305
|
+
...(writtenOff
|
|
306
|
+
? {
|
|
307
|
+
writtenOff,
|
|
308
|
+
}
|
|
309
|
+
: {}),
|
|
310
|
+
});
|
|
311
|
+
return {
|
|
312
|
+
id,
|
|
313
|
+
...(executionId !== undefined
|
|
314
|
+
? {
|
|
315
|
+
executionId,
|
|
316
|
+
}
|
|
317
|
+
: {}),
|
|
318
|
+
...(threadId !== undefined
|
|
319
|
+
? {
|
|
320
|
+
threadId,
|
|
321
|
+
}
|
|
322
|
+
: {}),
|
|
323
|
+
...bill,
|
|
324
|
+
...(writtenOff
|
|
325
|
+
? {
|
|
326
|
+
writtenOff: true,
|
|
327
|
+
}
|
|
328
|
+
: {}),
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Charge a bill to one place: the run in flight on its execution, else its thread's
|
|
333
|
+
* session, else the context this harness held it on. A run in flight passes the
|
|
334
|
+
* charge on to its turn's usage, so charging the session too would count it twice.
|
|
335
|
+
*/
|
|
336
|
+
async charge(hold, bill) {
|
|
337
|
+
const charge = {
|
|
338
|
+
inputTokens: bill.inputTokens,
|
|
339
|
+
outputTokens: bill.outputTokens,
|
|
340
|
+
cost: bill.cost,
|
|
341
|
+
billedCost: bill.cost,
|
|
342
|
+
};
|
|
343
|
+
const { executionId, threadId } = hold.record;
|
|
344
|
+
const live = executionId !== undefined ? this.host.liveRoot(executionId) : undefined;
|
|
345
|
+
if (live) {
|
|
346
|
+
recordUsage(live, charge);
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (threadId !== undefined && (await this.host.chargeSession(threadId, charge))) {
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
if (hold.ctx) {
|
|
353
|
+
recordUsage(hold.ctx, charge);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
/** Delete a held dispatch's record, unless it is already gone. */
|
|
357
|
+
async take(id) {
|
|
358
|
+
try {
|
|
359
|
+
if (!(await this.host.log.get(id))) {
|
|
360
|
+
return 'gone';
|
|
361
|
+
}
|
|
362
|
+
await this.host.log.remove(id);
|
|
363
|
+
return 'taken';
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
warn('delete', error);
|
|
367
|
+
return 'failed';
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
emit(hold, eventType, data) {
|
|
371
|
+
const threadId = hold.record.threadId;
|
|
372
|
+
emitFrameworkEvent({
|
|
373
|
+
broadcaster: getBroadcaster(hold.ctx) ??
|
|
374
|
+
(threadId !== undefined ? this.host.sessionBroadcaster(threadId) : undefined),
|
|
375
|
+
agentName: this.host.agentName,
|
|
376
|
+
eventType,
|
|
377
|
+
data,
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
//#endregion
|
|
382
|
+
//#region Dispatch
|
|
383
|
+
/**
|
|
384
|
+
* @internal
|
|
385
|
+
* One paid call in flight. Record writes run one at a time, so a generation id saved
|
|
386
|
+
* late never brings back a record that was already deleted.
|
|
387
|
+
*/
|
|
388
|
+
export class Dispatch {
|
|
389
|
+
spend;
|
|
390
|
+
log;
|
|
391
|
+
record;
|
|
392
|
+
root;
|
|
393
|
+
writes = Promise.resolve();
|
|
394
|
+
ended = false;
|
|
395
|
+
constructor(spend, log, record, root) {
|
|
396
|
+
this.spend = spend;
|
|
397
|
+
this.log = log;
|
|
398
|
+
this.record = record;
|
|
399
|
+
this.root = root;
|
|
400
|
+
}
|
|
401
|
+
/** Request headers that tie the response back to this dispatch. */
|
|
402
|
+
get headers() {
|
|
403
|
+
return {
|
|
404
|
+
[DISPATCH_HEADER]: this.record.id,
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
noteGeneration(generationId) {
|
|
408
|
+
if (this.ended || this.record.generationId) {
|
|
409
|
+
return this.writes;
|
|
410
|
+
}
|
|
411
|
+
this.record.generationId = generationId;
|
|
412
|
+
return this.queue('write', () => this.log.put(this.record));
|
|
413
|
+
}
|
|
414
|
+
/** The call's bill reached the run, or the provider refused it: drop the record. */
|
|
415
|
+
settle() {
|
|
416
|
+
if (this.ended) {
|
|
417
|
+
return this.writes;
|
|
418
|
+
}
|
|
419
|
+
this.ended = true;
|
|
420
|
+
this.spend.release(this.record.id);
|
|
421
|
+
return this.queue('delete', () => this.log.remove(this.record.id));
|
|
422
|
+
}
|
|
423
|
+
/** The call is over. Without a settled bill its record stays, pending. */
|
|
424
|
+
end() {
|
|
425
|
+
if (this.ended) {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
this.ended = true;
|
|
429
|
+
this.spend.release(this.record.id);
|
|
430
|
+
void this.writes.then(() => this.spend.leave(this.record, this.root));
|
|
431
|
+
}
|
|
432
|
+
queue(what, write) {
|
|
433
|
+
this.writes = this.writes.then(() => quietly(what, write));
|
|
434
|
+
return this.writes;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
//#endregion
|
|
438
|
+
//#region Helpers
|
|
439
|
+
function rootOf(ctx) {
|
|
440
|
+
let node = ctx;
|
|
441
|
+
while (node?.parent) {
|
|
442
|
+
node = node.parent;
|
|
443
|
+
}
|
|
444
|
+
const root = node ? laneBase(node) : undefined;
|
|
445
|
+
return root instanceof ContextImpl ? root : undefined;
|
|
446
|
+
}
|
|
447
|
+
function pathOf(ctx) {
|
|
448
|
+
return ctx instanceof ContextImpl ? ctx.currentDispatch()?.path : undefined;
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* The provider's bill for a call: undefined while it has not priced it yet, 'stop'
|
|
452
|
+
* when asking again cannot help.
|
|
453
|
+
*/
|
|
454
|
+
async function fetchBill(client, generationId) {
|
|
455
|
+
try {
|
|
456
|
+
const { data } = await client.generations.getGeneration({
|
|
457
|
+
id: generationId,
|
|
458
|
+
}, {
|
|
459
|
+
timeoutMs: LOOKUP_TIMEOUT_MS,
|
|
460
|
+
});
|
|
461
|
+
return {
|
|
462
|
+
cost: data.totalCost,
|
|
463
|
+
inputTokens: data.tokensPrompt ?? 0,
|
|
464
|
+
outputTokens: data.tokensCompletion ?? 0,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
catch (e) {
|
|
468
|
+
const status = statusOf(e);
|
|
469
|
+
const transient = status === undefined || status === 404 || status === 429 || status >= 500;
|
|
470
|
+
return transient ? undefined : 'stop';
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
/** Storage is best-effort here, as for checkpoints: a failed write never fails the call. */
|
|
474
|
+
async function quietly(what, write) {
|
|
475
|
+
try {
|
|
476
|
+
await write();
|
|
477
|
+
}
|
|
478
|
+
catch (error) {
|
|
479
|
+
warn(what, error);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
function warn(what, error) {
|
|
483
|
+
console.warn(`Spend: dispatch ${what} failed:`, error instanceof Error ? error.message : String(error));
|
|
484
|
+
}
|
|
485
|
+
/** A wait that does not keep the host process alive. */
|
|
486
|
+
function sleep(ms) {
|
|
487
|
+
return new Promise((resolve) => {
|
|
488
|
+
const timer = setTimeout(resolve, ms);
|
|
489
|
+
if (typeof timer === 'object' && 'unref' in timer) {
|
|
490
|
+
timer.unref();
|
|
491
|
+
}
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
//#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, ExecuteOptions, 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';
|
|
@@ -1,6 +1,7 @@
|
|
|
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';
|
|
4
5
|
import { allocateBudgets, assembleView, DECISION_PROJECTION, exportSpans, laneBase, } from './action-deps.js';
|
|
5
6
|
import { resolveLazy } from './execute-action.js';
|
|
6
7
|
import { trackUsage } from './message-helpers.js';
|
|
@@ -42,6 +43,7 @@ export async function executeDecide(step, input, ctx, layers) {
|
|
|
42
43
|
samples: step.samples,
|
|
43
44
|
signal: isContextImpl(baseCtx) ? baseCtx.abortSignal : undefined,
|
|
44
45
|
parentSpan: span,
|
|
46
|
+
_billTo: baseCtx,
|
|
45
47
|
});
|
|
46
48
|
trackUsage(baseCtx, {
|
|
47
49
|
items: [],
|
|
@@ -158,6 +160,19 @@ async function resolveModel(step, ctx) {
|
|
|
158
160
|
}
|
|
159
161
|
/** Provider errors arrive raw; give them the step's id and a Noetic kind. */
|
|
160
162
|
async function askHarness(step, ctx, request) {
|
|
163
|
+
const drains = drainsOf(ctx);
|
|
164
|
+
// A graceful stop that began while the step prepared its request sends nothing.
|
|
165
|
+
await drains?.hold(ctx);
|
|
166
|
+
if (ctx.aborted) {
|
|
167
|
+
throw new NoeticErrorImpl({
|
|
168
|
+
kind: 'cancelled',
|
|
169
|
+
reason: ctx.abortReason ?? 'context aborted',
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
const finished = drains?.track(ctx, {
|
|
173
|
+
kind: 'decide',
|
|
174
|
+
model: request.model,
|
|
175
|
+
});
|
|
161
176
|
try {
|
|
162
177
|
return await ctx.harness.decide(request);
|
|
163
178
|
}
|
|
@@ -180,6 +195,9 @@ async function askHarness(step, ctx, request) {
|
|
|
180
195
|
}
|
|
181
196
|
throw wrapModelError(e, step.id, ctx);
|
|
182
197
|
}
|
|
198
|
+
finally {
|
|
199
|
+
finished?.();
|
|
200
|
+
}
|
|
183
201
|
}
|
|
184
202
|
//#endregion
|
|
185
203
|
//#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
|
}
|
|
@@ -19,6 +19,7 @@ export declare class ContextImpl implements Context<ContextData> {
|
|
|
19
19
|
tokens: TokenUsage;
|
|
20
20
|
cost: number;
|
|
21
21
|
billedCost: number;
|
|
22
|
+
heldCost: number;
|
|
22
23
|
state: unknown;
|
|
23
24
|
readonly parent: Context<ContextData> | null;
|
|
24
25
|
readonly usageParent: Context<ContextData> | null;
|