@noetic-tools/core 5.18.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 +2 -0
- package/dist/harness/agent-harness.d.ts +16 -7
- package/dist/harness/agent-harness.js +64 -21
- package/dist/harness/call-spend.d.ts +34 -0
- package/dist/harness/call-spend.js +125 -0
- package/dist/harness/decide-call.js +8 -2
- package/dist/harness/deps/types.d.ts +1 -1
- package/dist/harness/model-call.js +51 -64
- package/dist/harness/model-price.d.ts +20 -4
- package/dist/harness/model-price.js +94 -17
- package/dist/harness/model-rounds.d.ts +11 -0
- package/dist/harness/model-rounds.js +37 -1
- package/dist/harness/spend.d.ts +9 -3
- package/dist/harness/spend.js +59 -19
- package/dist/index.d.ts +1 -1
- package/dist/interpreter/execute-action.js +2 -0
- package/dist/interpreter/execute-decide.js +26 -2
- package/dist/runtime/drain.d.ts +13 -22
- package/dist/runtime/drain.js +17 -5
- package/dist/runtime/durable/spend-log.d.ts +23 -3
- package/dist/runtime/durable/spend-log.js +79 -11
- package/dist/runtime/durable/step-ledger.d.ts +3 -2
- package/dist/runtime/durable/step-ledger.js +6 -4
- package/dist/util/spent.d.ts +14 -0
- package/dist/util/spent.js +67 -0
- package/package.json +2 -2
package/dist/harness/spend.js
CHANGED
|
@@ -8,12 +8,13 @@
|
|
|
8
8
|
* leaves the record behind. It is then *pending*: held at its ceiling, and priced
|
|
9
9
|
* through the provider's generation lookup once the provider has billed it.
|
|
10
10
|
*/
|
|
11
|
-
import {
|
|
11
|
+
import { recordUsage, SpendKind } from '@noetic-tools/types';
|
|
12
12
|
import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
|
|
13
|
+
import { isUnreadable } from '../runtime/durable/spend-log.js';
|
|
13
14
|
import { hashText } from '../runtime/durable/step-ledger.js';
|
|
14
15
|
import { statusOf } from '../util/status-code.js';
|
|
15
16
|
import { ContextImpl, laneBase } from './deps/runtime.js';
|
|
16
|
-
import { ceilingOf, createPriceBook, LOOKUP_TIMEOUT_MS } from './model-price.js';
|
|
17
|
+
import { ceilingOf, createPriceBook, LOOKUP_TIMEOUT_MS, measureRequest } from './model-price.js';
|
|
17
18
|
import { roundPath } from './model-rounds.js';
|
|
18
19
|
//#region Types
|
|
19
20
|
/** @internal Request header that ties a response back to its dispatch. */
|
|
@@ -49,13 +50,13 @@ export class Spend {
|
|
|
49
50
|
async open(params) {
|
|
50
51
|
const root = rootOf(params.ctx);
|
|
51
52
|
const path = pathOf(params.ctx);
|
|
52
|
-
const json =
|
|
53
|
+
const { json, inputTokens } = measureRequest(params.body);
|
|
53
54
|
const record = {
|
|
54
55
|
id: crypto.randomUUID(),
|
|
55
56
|
kind: params.kind,
|
|
56
57
|
model: params.model,
|
|
57
58
|
requestHash: hashText(json),
|
|
58
|
-
inputTokens
|
|
59
|
+
inputTokens,
|
|
59
60
|
...(params.maxOutputTokens !== undefined
|
|
60
61
|
? {
|
|
61
62
|
maxOutputTokens: params.maxOutputTokens,
|
|
@@ -83,10 +84,13 @@ export class Spend {
|
|
|
83
84
|
noteGeneration(dispatchId, generationId) {
|
|
84
85
|
return this.live.get(dispatchId)?.noteGeneration(generationId) ?? Promise.resolve();
|
|
85
86
|
}
|
|
86
|
-
/** Unsettled dispatches, each with its ceiling. */
|
|
87
|
+
/** Unsettled dispatches, each with its ceiling. Unreadable ones have none. */
|
|
87
88
|
async pending(executionId) {
|
|
88
89
|
const records = await this.unsettled(executionId);
|
|
89
90
|
return Promise.all(records.map(async (record) => {
|
|
91
|
+
if (isUnreadable(record)) {
|
|
92
|
+
return unreadablePending(record);
|
|
93
|
+
}
|
|
90
94
|
const ceiling = await this.ceilingOf(record);
|
|
91
95
|
return ceiling === undefined
|
|
92
96
|
? record
|
|
@@ -172,10 +176,16 @@ export class Spend {
|
|
|
172
176
|
.then(() => this.lookup(record, DEFAULT_PATIENCE_MS))
|
|
173
177
|
.catch((error) => warn('reconcile', error));
|
|
174
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
|
+
*/
|
|
175
183
|
async unsettled(executionId) {
|
|
176
184
|
const records = await this.host.log.list();
|
|
177
185
|
return records.filter((record) => !this.live.has(record.id) &&
|
|
178
|
-
(executionId === undefined ||
|
|
186
|
+
(executionId === undefined ||
|
|
187
|
+
record.executionId === executionId ||
|
|
188
|
+
(isUnreadable(record) && record.executionId === undefined)));
|
|
179
189
|
}
|
|
180
190
|
/**
|
|
181
191
|
* Hold `record` at its ceiling, on `ctx` when given. A dispatch already held moves to
|
|
@@ -183,6 +193,12 @@ export class Spend {
|
|
|
183
193
|
*/
|
|
184
194
|
hold(record, ctx) {
|
|
185
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
|
+
}
|
|
186
202
|
if (known) {
|
|
187
203
|
if (ctx && known.ctx !== ctx) {
|
|
188
204
|
if (known.ctx && known.ceiling !== undefined) {
|
|
@@ -207,27 +223,37 @@ export class Spend {
|
|
|
207
223
|
if (hold.ctx && ceiling !== undefined) {
|
|
208
224
|
hold.ctx.heldCost += ceiling;
|
|
209
225
|
}
|
|
210
|
-
this.emit(hold, 'spend_pending',
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
:
|
|
221
|
-
|
|
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
|
+
});
|
|
222
244
|
});
|
|
223
245
|
return hold.ready;
|
|
224
246
|
}
|
|
225
247
|
async ceilingOf(record) {
|
|
248
|
+
if (isUnreadable(record)) {
|
|
249
|
+
return undefined;
|
|
250
|
+
}
|
|
226
251
|
const price = await this.price(record.model);
|
|
227
252
|
return price ? ceilingOf(record, price) : undefined;
|
|
228
253
|
}
|
|
254
|
+
/** Unreadable records carry no generation id, so they are never priced. */
|
|
229
255
|
lookup(record, patienceMs) {
|
|
230
|
-
const generationId = record.generationId;
|
|
256
|
+
const generationId = isUnreadable(record) ? undefined : record.generationId;
|
|
231
257
|
if (!generationId) {
|
|
232
258
|
return Promise.resolve(undefined);
|
|
233
259
|
}
|
|
@@ -436,6 +462,20 @@ export class Dispatch {
|
|
|
436
462
|
}
|
|
437
463
|
//#endregion
|
|
438
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
|
+
}
|
|
439
479
|
function rootOf(ctx) {
|
|
440
480
|
let node = ctx;
|
|
441
481
|
while (node?.parent) {
|
package/dist/index.d.ts
CHANGED
|
@@ -164,7 +164,7 @@ 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, CancelOptions, 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
168
|
/** @public */
|
|
169
169
|
export type { PendingSpend, ReconcileSpendOptions, SpendSettlement, WriteOffSpendOptions, } from '@noetic-tools/types';
|
|
170
170
|
/** @public */
|
|
@@ -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
|
|
@@ -2,6 +2,7 @@ import { choiceValues, DecideOutputError, frameworkCast, hashString, NoeticConfi
|
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { GenAI, NoeticAttr } from '../observability/genai-attributes.js';
|
|
4
4
|
import { drainsOf } from '../runtime/drain.js';
|
|
5
|
+
import { chargeSpent } from '../util/spent.js';
|
|
5
6
|
import { allocateBudgets, assembleView, DECISION_PROJECTION, exportSpans, laneBase, } from './action-deps.js';
|
|
6
7
|
import { resolveLazy } from './execute-action.js';
|
|
7
8
|
import { trackUsage } from './message-helpers.js';
|
|
@@ -173,12 +174,35 @@ async function askHarness(step, ctx, request) {
|
|
|
173
174
|
kind: 'decide',
|
|
174
175
|
model: request.model,
|
|
175
176
|
});
|
|
177
|
+
let bill;
|
|
176
178
|
try {
|
|
177
|
-
|
|
179
|
+
const response = await ctx.harness.decide(request);
|
|
180
|
+
bill = {
|
|
181
|
+
cost: response.cost ?? 0,
|
|
182
|
+
usage: response.usage,
|
|
183
|
+
};
|
|
184
|
+
return response;
|
|
178
185
|
}
|
|
179
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
|
+
}
|
|
180
200
|
if (e instanceof DecideOutputError && !ctx.aborted) {
|
|
181
201
|
if (e.usage) {
|
|
202
|
+
bill = {
|
|
203
|
+
cost: e.cost ?? 0,
|
|
204
|
+
usage: e.usage,
|
|
205
|
+
};
|
|
182
206
|
trackUsage(ctx, {
|
|
183
207
|
items: [],
|
|
184
208
|
usage: e.usage,
|
|
@@ -196,7 +220,7 @@ async function askHarness(step, ctx, request) {
|
|
|
196
220
|
throw wrapModelError(e, step.id, ctx);
|
|
197
221
|
}
|
|
198
222
|
finally {
|
|
199
|
-
finished?.();
|
|
223
|
+
finished?.(bill);
|
|
200
224
|
}
|
|
201
225
|
}
|
|
202
226
|
//#endregion
|
package/dist/runtime/drain.d.ts
CHANGED
|
@@ -1,17 +1,4 @@
|
|
|
1
|
-
import type { Context } from '@noetic-tools/types';
|
|
2
|
-
/** @internal A provider call as a drain reports it in `drain_started` / `drain_finished`. */
|
|
3
|
-
export interface DrainCall {
|
|
4
|
-
readonly kind: 'model_round' | 'decide';
|
|
5
|
-
readonly model: string;
|
|
6
|
-
/** Id of the context that made the call. */
|
|
7
|
-
readonly executionId: string;
|
|
8
|
-
/** The round within its `callModel`, for model rounds. */
|
|
9
|
-
readonly round?: number;
|
|
10
|
-
/** Id of the call's dispatch record, when the harness keeps them (spec 23). */
|
|
11
|
-
readonly dispatchId?: string;
|
|
12
|
-
/** The provider's id for the call, once its response headers arrived. */
|
|
13
|
-
readonly generationId?: string;
|
|
14
|
-
}
|
|
1
|
+
import type { Context, DrainCall, DrainReport, RoundUsage } from '@noetic-tools/types';
|
|
15
2
|
/**
|
|
16
3
|
* @internal The dispatch record of a tracked call. Read when a drain reports, so a
|
|
17
4
|
* generation id saved after dispatch still shows.
|
|
@@ -20,9 +7,12 @@ export interface DrainRecord {
|
|
|
20
7
|
readonly id: string;
|
|
21
8
|
readonly generationId?: string;
|
|
22
9
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
10
|
+
/** @internal What a finished call cost, as charged to its context. */
|
|
11
|
+
export interface DrainBill {
|
|
12
|
+
readonly cost: number;
|
|
13
|
+
readonly usage: RoundUsage;
|
|
14
|
+
}
|
|
15
|
+
type DrainCallInfo = Pick<DrainCall, 'kind' | 'model' | 'round'>;
|
|
26
16
|
/**
|
|
27
17
|
* @internal
|
|
28
18
|
*
|
|
@@ -41,9 +31,9 @@ export declare class Drains {
|
|
|
41
31
|
private readonly active;
|
|
42
32
|
/**
|
|
43
33
|
* Note a provider call about to be dispatched on `ctx` under `record`. Call the
|
|
44
|
-
* returned function once its response is in
|
|
34
|
+
* returned function once its response is in, with its bill, or once it failed.
|
|
45
35
|
*/
|
|
46
|
-
track(ctx: Context | undefined, info: DrainCallInfo, record?: DrainRecord): () => void;
|
|
36
|
+
track(ctx: Context | undefined, info: DrainCallInfo, record?: DrainRecord): (bill?: DrainBill) => void;
|
|
47
37
|
/**
|
|
48
38
|
* The dispatch gate. Under a drain, release `ctx`'s finished calls and wait
|
|
49
39
|
* until a drain over it stops the tree; the caller then sees `ctx.aborted`.
|
|
@@ -62,13 +52,14 @@ export declare class Drains {
|
|
|
62
52
|
/**
|
|
63
53
|
* Drain `ctx` for up to `ms`, then run `stop`, which must abort the tree
|
|
64
54
|
* before its first `await`: held steps wake as soon as it is called.
|
|
55
|
+
* Resolves with the drain's report once the stop is done.
|
|
65
56
|
*/
|
|
66
|
-
run(ctx: Context, ms: number, stop: () => Promise<void>): Promise<
|
|
57
|
+
run(ctx: Context, ms: number, stop: () => Promise<void>): Promise<DrainReport>;
|
|
67
58
|
/**
|
|
68
59
|
* Cut short the drain on `ctx`, if one is running, and return the promise
|
|
69
|
-
* of its
|
|
60
|
+
* of its report. A second cancel cancels at once.
|
|
70
61
|
*/
|
|
71
|
-
stop(ctx: Context): Promise<
|
|
62
|
+
stop(ctx: Context): Promise<DrainReport> | undefined;
|
|
72
63
|
private finish;
|
|
73
64
|
private settleIfIdle;
|
|
74
65
|
}
|
package/dist/runtime/drain.js
CHANGED
|
@@ -20,7 +20,7 @@ export class Drains {
|
|
|
20
20
|
active = new Set();
|
|
21
21
|
/**
|
|
22
22
|
* Note a provider call about to be dispatched on `ctx` under `record`. Call the
|
|
23
|
-
* returned function once its response is in
|
|
23
|
+
* returned function once its response is in, with its bill, or once it failed.
|
|
24
24
|
*/
|
|
25
25
|
track(ctx, info, record) {
|
|
26
26
|
if (!ctx) {
|
|
@@ -38,8 +38,9 @@ export class Drains {
|
|
|
38
38
|
drain.calls.add(call);
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
-
return () => {
|
|
41
|
+
return (bill) => {
|
|
42
42
|
call.done = true;
|
|
43
|
+
call.bill = bill;
|
|
43
44
|
// Kept until a hold or step end releases it only while a drain may be
|
|
44
45
|
// waiting on it; otherwise nothing will ever release it.
|
|
45
46
|
if (this.active.size === 0) {
|
|
@@ -95,6 +96,7 @@ export class Drains {
|
|
|
95
96
|
/**
|
|
96
97
|
* Drain `ctx` for up to `ms`, then run `stop`, which must abort the tree
|
|
97
98
|
* before its first `await`: held steps wake as soon as it is called.
|
|
99
|
+
* Resolves with the drain's report once the stop is done.
|
|
98
100
|
*/
|
|
99
101
|
run(ctx, ms, stop) {
|
|
100
102
|
const drain = openDrain(ctx, ms);
|
|
@@ -109,7 +111,7 @@ export class Drains {
|
|
|
109
111
|
}
|
|
110
112
|
/**
|
|
111
113
|
* Cut short the drain on `ctx`, if one is running, and return the promise
|
|
112
|
-
* of its
|
|
114
|
+
* of its report. A second cancel cancels at once.
|
|
113
115
|
*/
|
|
114
116
|
stop(ctx) {
|
|
115
117
|
for (const drain of this.active) {
|
|
@@ -141,16 +143,20 @@ export class Drains {
|
|
|
141
143
|
const calls = [
|
|
142
144
|
...drain.calls,
|
|
143
145
|
];
|
|
144
|
-
|
|
146
|
+
const drained = {
|
|
145
147
|
executionId: drain.root.id,
|
|
146
148
|
reason,
|
|
147
149
|
durationMs: Date.now() - drain.startedAt,
|
|
148
150
|
finished: calls.filter((call) => call.done).map(report),
|
|
149
151
|
cutOff: calls.filter((call) => !call.done).map(report),
|
|
152
|
+
};
|
|
153
|
+
emit(drain.root, 'drain_finished', {
|
|
154
|
+
...drained,
|
|
150
155
|
});
|
|
151
156
|
const stopping = stop();
|
|
152
157
|
drain.wake();
|
|
153
158
|
await stopping;
|
|
159
|
+
return drained;
|
|
154
160
|
}
|
|
155
161
|
settleIfIdle(drain) {
|
|
156
162
|
for (const call of this.calls) {
|
|
@@ -206,7 +212,7 @@ function openDrain(root, ms) {
|
|
|
206
212
|
};
|
|
207
213
|
}
|
|
208
214
|
function report(call) {
|
|
209
|
-
const { record } = call;
|
|
215
|
+
const { record, bill } = call;
|
|
210
216
|
return {
|
|
211
217
|
...call.info,
|
|
212
218
|
executionId: call.ctx.id,
|
|
@@ -220,6 +226,12 @@ function report(call) {
|
|
|
220
226
|
generationId: record.generationId,
|
|
221
227
|
}
|
|
222
228
|
: {}),
|
|
229
|
+
...(bill
|
|
230
|
+
? {
|
|
231
|
+
cost: bill.cost,
|
|
232
|
+
usage: bill.usage,
|
|
233
|
+
}
|
|
234
|
+
: {}),
|
|
223
235
|
};
|
|
224
236
|
}
|
|
225
237
|
/** Whether `ctx` is `root` or runs beneath it. Lanes share their context's id. */
|
|
@@ -26,13 +26,33 @@ export declare const DispatchRecordSchema: z.ZodObject<{
|
|
|
26
26
|
}, z.core.$strip>;
|
|
27
27
|
/** @internal */
|
|
28
28
|
export type DispatchRecord = z.infer<typeof DispatchRecordSchema>;
|
|
29
|
+
/**
|
|
30
|
+
* @internal
|
|
31
|
+
* A `spend:<id>` value that does not read as a record. Only the owner fields the
|
|
32
|
+
* damaged value still names are kept; nothing else in it is trusted.
|
|
33
|
+
*/
|
|
34
|
+
export interface UnreadableRecord {
|
|
35
|
+
readonly id: string;
|
|
36
|
+
readonly unreadable: true;
|
|
37
|
+
readonly executionId?: string;
|
|
38
|
+
readonly threadId?: string;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* @internal
|
|
42
|
+
* What a `spend:<id>` key holds: a record, or a value that does not read as one. An
|
|
43
|
+
* unreadable value is still evidence that a paid call was sent, so it is kept and
|
|
44
|
+
* reported rather than skipped.
|
|
45
|
+
*/
|
|
46
|
+
export type SpendRecord = DispatchRecord | UnreadableRecord;
|
|
47
|
+
/** @internal */
|
|
48
|
+
export declare function isUnreadable(record: SpendRecord): record is UnreadableRecord;
|
|
29
49
|
/** @internal */
|
|
30
50
|
export interface SpendLog {
|
|
31
51
|
put(record: DispatchRecord): Promise<void>;
|
|
32
|
-
get(id: string): Promise<
|
|
52
|
+
get(id: string): Promise<SpendRecord | undefined>;
|
|
33
53
|
remove(id: string): Promise<void>;
|
|
34
|
-
/** Every record
|
|
35
|
-
list(): Promise<
|
|
54
|
+
/** Every record: unreadable ones first, since their age is unknown, then oldest first. */
|
|
55
|
+
list(): Promise<SpendRecord[]>;
|
|
36
56
|
}
|
|
37
57
|
/** @internal */
|
|
38
58
|
export declare function createSpendLog(storage: StorageAdapter): SpendLog;
|
|
@@ -27,39 +27,107 @@ export const DispatchRecordSchema = z.object({
|
|
|
27
27
|
sentAt: z.string(),
|
|
28
28
|
});
|
|
29
29
|
/** @internal */
|
|
30
|
+
export function isUnreadable(record) {
|
|
31
|
+
return 'unreadable' in record;
|
|
32
|
+
}
|
|
33
|
+
/** @internal */
|
|
30
34
|
export function createSpendLog(storage) {
|
|
31
35
|
return {
|
|
32
36
|
put: async (record) => {
|
|
33
37
|
await storage.set(keyOf(record.id), record);
|
|
34
38
|
},
|
|
35
|
-
get: async (id) =>
|
|
39
|
+
get: async (id) => {
|
|
40
|
+
const key = keyOf(id);
|
|
41
|
+
const raw = await storage.get(key);
|
|
42
|
+
if (!isNothing(raw)) {
|
|
43
|
+
return parse(id, raw);
|
|
44
|
+
}
|
|
45
|
+
return (await storage.list(key)).includes(key) ? unreadable(id) : undefined;
|
|
46
|
+
},
|
|
36
47
|
remove: async (id) => {
|
|
37
48
|
await storage.delete(keyOf(id));
|
|
38
49
|
},
|
|
39
50
|
list: async () => {
|
|
40
51
|
const keys = await storage.list(SPEND_PREFIX);
|
|
41
52
|
const raws = await storageGetMany(storage, keys);
|
|
53
|
+
const damaged = [];
|
|
42
54
|
const records = [];
|
|
43
55
|
for (const [key, raw] of raws) {
|
|
44
|
-
|
|
45
|
-
if (!record) {
|
|
46
|
-
console.warn(`SpendLog: skipping unreadable dispatch record "${key}"`);
|
|
56
|
+
if (isNothing(raw)) {
|
|
47
57
|
continue;
|
|
48
58
|
}
|
|
49
|
-
|
|
59
|
+
const record = parse(key.slice(SPEND_PREFIX.length), raw);
|
|
60
|
+
if (isUnreadable(record)) {
|
|
61
|
+
damaged.push(record);
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
records.push(record);
|
|
65
|
+
}
|
|
50
66
|
}
|
|
51
|
-
|
|
67
|
+
for (const key of await stillListed(keys.filter((key) => isNothing(raws.get(key))))) {
|
|
68
|
+
damaged.push(unreadable(key.slice(SPEND_PREFIX.length)));
|
|
69
|
+
}
|
|
70
|
+
return [
|
|
71
|
+
...damaged,
|
|
72
|
+
...records.sort((a, b) => a.sentAt.localeCompare(b.sentAt)),
|
|
73
|
+
];
|
|
52
74
|
},
|
|
53
75
|
};
|
|
76
|
+
/**
|
|
77
|
+
* Of keys that listed but read as nothing, the ones that still list. A store may
|
|
78
|
+
* read a value it cannot parse as nothing (`createFileStorage` does), and that value
|
|
79
|
+
* is damaged, not gone; a key settled since it was listed no longer lists.
|
|
80
|
+
*/
|
|
81
|
+
async function stillListed(missing) {
|
|
82
|
+
if (missing.length === 0) {
|
|
83
|
+
return [];
|
|
84
|
+
}
|
|
85
|
+
const listed = new Set(await storage.list(SPEND_PREFIX));
|
|
86
|
+
return missing.filter((key) => listed.has(key));
|
|
87
|
+
}
|
|
54
88
|
}
|
|
55
89
|
function keyOf(id) {
|
|
56
90
|
return `${SPEND_PREFIX}${id}`;
|
|
57
91
|
}
|
|
58
|
-
function
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
92
|
+
function isNothing(raw) {
|
|
93
|
+
return raw === null || raw === undefined;
|
|
94
|
+
}
|
|
95
|
+
function parse(id, raw) {
|
|
62
96
|
const parsed = DispatchRecordSchema.safeParse(raw);
|
|
63
|
-
return parsed.success ? parsed.data :
|
|
97
|
+
return parsed.success ? parsed.data : unreadable(id, owner(raw));
|
|
98
|
+
}
|
|
99
|
+
function unreadable(id, named = {}) {
|
|
100
|
+
return {
|
|
101
|
+
id,
|
|
102
|
+
unreadable: true,
|
|
103
|
+
...named,
|
|
104
|
+
};
|
|
64
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* The execution and thread a damaged record still names, so its write-off is charged
|
|
108
|
+
* where its call ran. Any other field is not trusted.
|
|
109
|
+
*/
|
|
110
|
+
function owner(raw) {
|
|
111
|
+
const parsed = OwnerSchema.safeParse(raw);
|
|
112
|
+
if (!parsed.success) {
|
|
113
|
+
return {};
|
|
114
|
+
}
|
|
115
|
+
const { executionId, threadId } = parsed.data;
|
|
116
|
+
return {
|
|
117
|
+
...(executionId !== undefined
|
|
118
|
+
? {
|
|
119
|
+
executionId,
|
|
120
|
+
}
|
|
121
|
+
: {}),
|
|
122
|
+
...(threadId !== undefined
|
|
123
|
+
? {
|
|
124
|
+
threadId,
|
|
125
|
+
}
|
|
126
|
+
: {}),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
const OwnerSchema = z.object({
|
|
130
|
+
executionId: z.string().min(1).optional().catch(undefined),
|
|
131
|
+
threadId: z.string().min(1).optional().catch(undefined),
|
|
132
|
+
});
|
|
65
133
|
//#endregion
|
|
@@ -212,9 +212,10 @@ export declare class StepLedger {
|
|
|
212
212
|
/**
|
|
213
213
|
* Record a completed step, then prune what it makes dead: a resumed run replays this
|
|
214
214
|
* entry without descending, so nothing recorded beneath it will be read again.
|
|
215
|
-
* Best-effort: a failed write costs resumability, not the run.
|
|
215
|
+
* Best-effort: a failed write costs resumability, not the run. Resolves whether
|
|
216
|
+
* the entry was stored.
|
|
216
217
|
*/
|
|
217
|
-
record(entry: StepLedgerEntry): Promise<
|
|
218
|
+
record(entry: StepLedgerEntry): Promise<boolean>;
|
|
218
219
|
/**
|
|
219
220
|
* Drop every positional entry. A host calls this once a run has finished and the
|
|
220
221
|
* checkpoint holds its result: every later resume starts past them, so they are dead.
|
|
@@ -314,14 +314,15 @@ export class StepLedger {
|
|
|
314
314
|
/**
|
|
315
315
|
* Record a completed step, then prune what it makes dead: a resumed run replays this
|
|
316
316
|
* entry without descending, so nothing recorded beneath it will be read again.
|
|
317
|
-
* Best-effort: a failed write costs resumability, not the run.
|
|
317
|
+
* Best-effort: a failed write costs resumability, not the run. Resolves whether
|
|
318
|
+
* the entry was stored.
|
|
318
319
|
*/
|
|
319
320
|
async record(entry) {
|
|
320
321
|
if (!this.store) {
|
|
321
|
-
return;
|
|
322
|
+
return false;
|
|
322
323
|
}
|
|
323
324
|
if (!this.retainable(entry)) {
|
|
324
|
-
return;
|
|
325
|
+
return false;
|
|
325
326
|
}
|
|
326
327
|
/* Reserve the sequence number BEFORE awaiting: concurrent inParallel legs record through
|
|
327
328
|
* the one shared ledger, and two of them reading the same counter would write the
|
|
@@ -333,7 +334,7 @@ export class StepLedger {
|
|
|
333
334
|
}
|
|
334
335
|
catch (error) {
|
|
335
336
|
console.warn(`StepLedger: failed to record "${entry.path}":`, error instanceof Error ? error.message : String(error));
|
|
336
|
-
return;
|
|
337
|
+
return false;
|
|
337
338
|
}
|
|
338
339
|
const replaced = this.live.get(entry.path);
|
|
339
340
|
this.live.set(entry.path, seq);
|
|
@@ -344,6 +345,7 @@ export class StepLedger {
|
|
|
344
345
|
if (!entry.path.startsWith(REPLAY_KEY_PREFIX)) {
|
|
345
346
|
await this.prune(this.live.beneath(entry.path));
|
|
346
347
|
}
|
|
348
|
+
return true;
|
|
347
349
|
}
|
|
348
350
|
/**
|
|
349
351
|
* Drop every positional entry. A host calls this once a run has finished and the
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Context, UsageCharge } from '@noetic-tools/types';
|
|
2
|
+
/**
|
|
3
|
+
* Tie `charge` to `error` and return the error to throw. A charge the error already
|
|
4
|
+
* carries — from a call nested inside this one that nobody charged — is added to.
|
|
5
|
+
* A thrown value that is not an object is wrapped in an `Error` to carry the charge;
|
|
6
|
+
* one that spent nothing is returned as is.
|
|
7
|
+
*/
|
|
8
|
+
export declare function markSpent(error: unknown, charge: UsageCharge, onCharge?: () => void): unknown;
|
|
9
|
+
/**
|
|
10
|
+
* Charge `ctx` with what the call behind `error` spent, and return that charge. The
|
|
11
|
+
* mark is dropped once charged, so an error rethrown through an outer call is charged
|
|
12
|
+
* only by that call.
|
|
13
|
+
*/
|
|
14
|
+
export declare function chargeSpent(ctx: Context, error: unknown): UsageCharge | undefined;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { recordUsage } from '@noetic-tools/types';
|
|
2
|
+
/**
|
|
3
|
+
* What a call had spent when it threw. A model call that fails after the provider
|
|
4
|
+
* billed some of its rounds returns no `LLMResponse`, so the bill rides on the error
|
|
5
|
+
* and the caller charges it. Kept beside the error rather than on it, so a provider
|
|
6
|
+
* error keeps its own shape.
|
|
7
|
+
*/
|
|
8
|
+
const spends = new WeakMap();
|
|
9
|
+
/**
|
|
10
|
+
* Tie `charge` to `error` and return the error to throw. A charge the error already
|
|
11
|
+
* carries — from a call nested inside this one that nobody charged — is added to.
|
|
12
|
+
* A thrown value that is not an object is wrapped in an `Error` to carry the charge;
|
|
13
|
+
* one that spent nothing is returned as is.
|
|
14
|
+
*/
|
|
15
|
+
export function markSpent(error, charge, onCharge) {
|
|
16
|
+
if (isEmpty(charge)) {
|
|
17
|
+
return error;
|
|
18
|
+
}
|
|
19
|
+
const thrown = typeof error === 'object' && error !== null ? error : new Error(String(error));
|
|
20
|
+
const prior = spends.get(thrown);
|
|
21
|
+
spends.set(thrown, {
|
|
22
|
+
charge: prior ? addCharges(prior.charge, charge) : charge,
|
|
23
|
+
onCharge: () => {
|
|
24
|
+
prior?.onCharge?.();
|
|
25
|
+
onCharge?.();
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
return thrown;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Charge `ctx` with what the call behind `error` spent, and return that charge. The
|
|
32
|
+
* mark is dropped once charged, so an error rethrown through an outer call is charged
|
|
33
|
+
* only by that call.
|
|
34
|
+
*/
|
|
35
|
+
export function chargeSpent(ctx, error) {
|
|
36
|
+
if (typeof error !== 'object' || error === null) {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
const spent = spends.get(error);
|
|
40
|
+
if (!spent) {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
spends.delete(error);
|
|
44
|
+
recordUsage(ctx, spent.charge);
|
|
45
|
+
spent.onCharge?.();
|
|
46
|
+
return spent.charge;
|
|
47
|
+
}
|
|
48
|
+
function isEmpty(charge) {
|
|
49
|
+
return (charge.inputTokens === 0 &&
|
|
50
|
+
charge.outputTokens === 0 &&
|
|
51
|
+
!charge.cachedTokens &&
|
|
52
|
+
!charge.cost &&
|
|
53
|
+
!charge.billedCost);
|
|
54
|
+
}
|
|
55
|
+
function addCharges(a, b) {
|
|
56
|
+
return {
|
|
57
|
+
inputTokens: a.inputTokens + b.inputTokens,
|
|
58
|
+
outputTokens: a.outputTokens + b.outputTokens,
|
|
59
|
+
...(a.cachedTokens !== undefined || b.cachedTokens !== undefined
|
|
60
|
+
? {
|
|
61
|
+
cachedTokens: (a.cachedTokens ?? 0) + (b.cachedTokens ?? 0),
|
|
62
|
+
}
|
|
63
|
+
: {}),
|
|
64
|
+
cost: (a.cost ?? 0) + (b.cost ?? 0),
|
|
65
|
+
billedCost: (a.billedCost ?? a.cost ?? 0) + (b.billedCost ?? b.cost ?? 0),
|
|
66
|
+
};
|
|
67
|
+
}
|