@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
|
@@ -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;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { Context, DrainCall, DrainReport, RoundUsage } from '@noetic-tools/types';
|
|
2
|
+
/**
|
|
3
|
+
* @internal The dispatch record of a tracked call. Read when a drain reports, so a
|
|
4
|
+
* generation id saved after dispatch still shows.
|
|
5
|
+
*/
|
|
6
|
+
export interface DrainRecord {
|
|
7
|
+
readonly id: string;
|
|
8
|
+
readonly generationId?: string;
|
|
9
|
+
}
|
|
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'>;
|
|
16
|
+
/**
|
|
17
|
+
* @internal
|
|
18
|
+
*
|
|
19
|
+
* Graceful stops for one harness. A drain on a context holds back new steps,
|
|
20
|
+
* model rounds and tool calls anywhere beneath it, lets the provider calls
|
|
21
|
+
* already in flight finish, then stops the tree: when nothing is left in
|
|
22
|
+
* flight, at its deadline, or when a second stop cuts it short.
|
|
23
|
+
*
|
|
24
|
+
* A call counts as in flight from dispatch until its caller reaches the next
|
|
25
|
+
* hold or step end, not merely until its response arrives: the response
|
|
26
|
+
* still has to be charged to the context and the step recorded, and stopping
|
|
27
|
+
* the tree before then would lose both.
|
|
28
|
+
*/
|
|
29
|
+
export declare class Drains {
|
|
30
|
+
private readonly calls;
|
|
31
|
+
private readonly active;
|
|
32
|
+
/**
|
|
33
|
+
* Note a provider call about to be dispatched on `ctx` under `record`. Call the
|
|
34
|
+
* returned function once its response is in, with its bill, or once it failed.
|
|
35
|
+
*/
|
|
36
|
+
track(ctx: Context | undefined, info: DrainCallInfo, record?: DrainRecord): (bill?: DrainBill) => void;
|
|
37
|
+
/**
|
|
38
|
+
* The dispatch gate. Under a drain, release `ctx`'s finished calls and wait
|
|
39
|
+
* until a drain over it stops the tree; the caller then sees `ctx.aborted`.
|
|
40
|
+
*/
|
|
41
|
+
hold(ctx: Context | undefined): Promise<void>;
|
|
42
|
+
/**
|
|
43
|
+
* The step running on `ctx` ended, or reached a hold: the finished calls it
|
|
44
|
+
* made are charged and recorded. Calls a concurrent dispatch on the same
|
|
45
|
+
* context made stay in flight until that dispatch ends.
|
|
46
|
+
*/
|
|
47
|
+
release(ctx: Context): void;
|
|
48
|
+
/** The deadline of the drain on `ctx` or one of its ancestors, if one is running. */
|
|
49
|
+
covering(ctx: Context): {
|
|
50
|
+
readonly deadline: number;
|
|
51
|
+
} | undefined;
|
|
52
|
+
/**
|
|
53
|
+
* Drain `ctx` for up to `ms`, then run `stop`, which must abort the tree
|
|
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.
|
|
56
|
+
*/
|
|
57
|
+
run(ctx: Context, ms: number, stop: () => Promise<void>): Promise<DrainReport>;
|
|
58
|
+
/**
|
|
59
|
+
* Cut short the drain on `ctx`, if one is running, and return the promise
|
|
60
|
+
* of its report. A second cancel cancels at once.
|
|
61
|
+
*/
|
|
62
|
+
stop(ctx: Context): Promise<DrainReport> | undefined;
|
|
63
|
+
private finish;
|
|
64
|
+
private settleIfIdle;
|
|
65
|
+
}
|
|
66
|
+
/** The harness's drains, when `ctx` runs on a harness that has them. */
|
|
67
|
+
export declare function drainsOf(ctx: Context | undefined): Drains | undefined;
|
|
68
|
+
export {};
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { emitFrameworkEvent, getBroadcaster } from './broadcaster-utils.js';
|
|
2
|
+
import { ContextImpl } from './context-impl.js';
|
|
3
|
+
//#endregion
|
|
4
|
+
//#region Drains
|
|
5
|
+
/**
|
|
6
|
+
* @internal
|
|
7
|
+
*
|
|
8
|
+
* Graceful stops for one harness. A drain on a context holds back new steps,
|
|
9
|
+
* model rounds and tool calls anywhere beneath it, lets the provider calls
|
|
10
|
+
* already in flight finish, then stops the tree: when nothing is left in
|
|
11
|
+
* flight, at its deadline, or when a second stop cuts it short.
|
|
12
|
+
*
|
|
13
|
+
* A call counts as in flight from dispatch until its caller reaches the next
|
|
14
|
+
* hold or step end, not merely until its response arrives: the response
|
|
15
|
+
* still has to be charged to the context and the step recorded, and stopping
|
|
16
|
+
* the tree before then would lose both.
|
|
17
|
+
*/
|
|
18
|
+
export class Drains {
|
|
19
|
+
calls = new Set();
|
|
20
|
+
active = new Set();
|
|
21
|
+
/**
|
|
22
|
+
* Note a provider call about to be dispatched on `ctx` under `record`. Call the
|
|
23
|
+
* returned function once its response is in, with its bill, or once it failed.
|
|
24
|
+
*/
|
|
25
|
+
track(ctx, info, record) {
|
|
26
|
+
if (!ctx) {
|
|
27
|
+
return () => { };
|
|
28
|
+
}
|
|
29
|
+
const call = {
|
|
30
|
+
info,
|
|
31
|
+
ctx,
|
|
32
|
+
record,
|
|
33
|
+
done: false,
|
|
34
|
+
};
|
|
35
|
+
this.calls.add(call);
|
|
36
|
+
for (const drain of this.active) {
|
|
37
|
+
if (within(ctx, drain.root)) {
|
|
38
|
+
drain.calls.add(call);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return (bill) => {
|
|
42
|
+
call.done = true;
|
|
43
|
+
call.bill = bill;
|
|
44
|
+
// Kept until a hold or step end releases it only while a drain may be
|
|
45
|
+
// waiting on it; otherwise nothing will ever release it.
|
|
46
|
+
if (this.active.size === 0) {
|
|
47
|
+
this.calls.delete(call);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The dispatch gate. Under a drain, release `ctx`'s finished calls and wait
|
|
53
|
+
* until a drain over it stops the tree; the caller then sees `ctx.aborted`.
|
|
54
|
+
*/
|
|
55
|
+
async hold(ctx) {
|
|
56
|
+
if (!ctx || this.active.size === 0 || ctx.aborted) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
this.release(ctx);
|
|
60
|
+
const over = [
|
|
61
|
+
...this.active,
|
|
62
|
+
]
|
|
63
|
+
.filter((drain) => within(ctx, drain.root))
|
|
64
|
+
.map((drain) => drain.over);
|
|
65
|
+
if (over.length > 0) {
|
|
66
|
+
await Promise.race(over);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The step running on `ctx` ended, or reached a hold: the finished calls it
|
|
71
|
+
* made are charged and recorded. Calls a concurrent dispatch on the same
|
|
72
|
+
* context made stay in flight until that dispatch ends.
|
|
73
|
+
*/
|
|
74
|
+
release(ctx) {
|
|
75
|
+
if (this.active.size === 0) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
for (const call of this.calls) {
|
|
79
|
+
if (call.done && inside(call.ctx, ctx)) {
|
|
80
|
+
this.calls.delete(call);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
for (const drain of this.active) {
|
|
84
|
+
this.settleIfIdle(drain);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** The deadline of the drain on `ctx` or one of its ancestors, if one is running. */
|
|
88
|
+
covering(ctx) {
|
|
89
|
+
for (const drain of this.active) {
|
|
90
|
+
if (within(ctx, drain.root)) {
|
|
91
|
+
return drain;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Drain `ctx` for up to `ms`, then run `stop`, which must abort the tree
|
|
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.
|
|
100
|
+
*/
|
|
101
|
+
run(ctx, ms, stop) {
|
|
102
|
+
const drain = openDrain(ctx, ms);
|
|
103
|
+
for (const call of this.calls) {
|
|
104
|
+
if (within(call.ctx, ctx)) {
|
|
105
|
+
drain.calls.add(call);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
this.active.add(drain);
|
|
109
|
+
drain.done = this.finish(drain, stop);
|
|
110
|
+
return drain.done;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Cut short the drain on `ctx`, if one is running, and return the promise
|
|
114
|
+
* of its report. A second cancel cancels at once.
|
|
115
|
+
*/
|
|
116
|
+
stop(ctx) {
|
|
117
|
+
for (const drain of this.active) {
|
|
118
|
+
if (drain.root.id === ctx.id) {
|
|
119
|
+
drain.end('stopped');
|
|
120
|
+
return drain.done;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
async finish(drain, stop) {
|
|
126
|
+
emit(drain.root, 'drain_started', {
|
|
127
|
+
executionId: drain.root.id,
|
|
128
|
+
deadline: drain.deadline,
|
|
129
|
+
inFlight: [
|
|
130
|
+
...drain.calls,
|
|
131
|
+
].map(report),
|
|
132
|
+
});
|
|
133
|
+
this.settleIfIdle(drain);
|
|
134
|
+
const reason = await drain.ended;
|
|
135
|
+
this.active.delete(drain);
|
|
136
|
+
if (this.active.size === 0) {
|
|
137
|
+
for (const call of this.calls) {
|
|
138
|
+
if (call.done) {
|
|
139
|
+
this.calls.delete(call);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const calls = [
|
|
144
|
+
...drain.calls,
|
|
145
|
+
];
|
|
146
|
+
const drained = {
|
|
147
|
+
executionId: drain.root.id,
|
|
148
|
+
reason,
|
|
149
|
+
durationMs: Date.now() - drain.startedAt,
|
|
150
|
+
finished: calls.filter((call) => call.done).map(report),
|
|
151
|
+
cutOff: calls.filter((call) => !call.done).map(report),
|
|
152
|
+
};
|
|
153
|
+
emit(drain.root, 'drain_finished', {
|
|
154
|
+
...drained,
|
|
155
|
+
});
|
|
156
|
+
const stopping = stop();
|
|
157
|
+
drain.wake();
|
|
158
|
+
await stopping;
|
|
159
|
+
return drained;
|
|
160
|
+
}
|
|
161
|
+
settleIfIdle(drain) {
|
|
162
|
+
for (const call of this.calls) {
|
|
163
|
+
if (within(call.ctx, drain.root)) {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
drain.end('settled');
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/** The harness's drains, when `ctx` runs on a harness that has them. */
|
|
171
|
+
export function drainsOf(ctx) {
|
|
172
|
+
const harness = ctx?.harness;
|
|
173
|
+
if (!harness || !('drains' in harness)) {
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
return harness.drains instanceof Drains ? harness.drains : undefined;
|
|
177
|
+
}
|
|
178
|
+
//#endregion
|
|
179
|
+
//#region Helpers
|
|
180
|
+
/** Timers round longer delays down to 1 ms; the longest a timer can wait. */
|
|
181
|
+
const MAX_TIMEOUT_MS = 2 ** 31 - 1;
|
|
182
|
+
function openDrain(root, ms) {
|
|
183
|
+
const startedAt = Date.now();
|
|
184
|
+
let end = () => { };
|
|
185
|
+
const ended = new Promise((resolve) => {
|
|
186
|
+
end = resolve;
|
|
187
|
+
});
|
|
188
|
+
let wake = () => { };
|
|
189
|
+
const over = new Promise((resolve) => {
|
|
190
|
+
wake = resolve;
|
|
191
|
+
});
|
|
192
|
+
const timer = setTimeout(() => end('deadline'), Math.min(ms, MAX_TIMEOUT_MS));
|
|
193
|
+
// Someone else aborting the tree ends the wait: there is nothing left to drain into.
|
|
194
|
+
const signal = root instanceof ContextImpl ? root.abortSignal : undefined;
|
|
195
|
+
const onAbort = () => end('stopped');
|
|
196
|
+
signal?.addEventListener('abort', onAbort, {
|
|
197
|
+
once: true,
|
|
198
|
+
});
|
|
199
|
+
void ended.then(() => {
|
|
200
|
+
clearTimeout(timer);
|
|
201
|
+
signal?.removeEventListener('abort', onAbort);
|
|
202
|
+
});
|
|
203
|
+
return {
|
|
204
|
+
root,
|
|
205
|
+
startedAt,
|
|
206
|
+
deadline: startedAt + ms,
|
|
207
|
+
calls: new Set(),
|
|
208
|
+
end,
|
|
209
|
+
ended,
|
|
210
|
+
over,
|
|
211
|
+
wake,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
function report(call) {
|
|
215
|
+
const { record, bill } = call;
|
|
216
|
+
return {
|
|
217
|
+
...call.info,
|
|
218
|
+
executionId: call.ctx.id,
|
|
219
|
+
...(record
|
|
220
|
+
? {
|
|
221
|
+
dispatchId: record.id,
|
|
222
|
+
}
|
|
223
|
+
: {}),
|
|
224
|
+
...(record?.generationId
|
|
225
|
+
? {
|
|
226
|
+
generationId: record.generationId,
|
|
227
|
+
}
|
|
228
|
+
: {}),
|
|
229
|
+
...(bill
|
|
230
|
+
? {
|
|
231
|
+
cost: bill.cost,
|
|
232
|
+
usage: bill.usage,
|
|
233
|
+
}
|
|
234
|
+
: {}),
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
/** Whether `ctx` is `root` or runs beneath it. Lanes share their context's id. */
|
|
238
|
+
function within(ctx, root) {
|
|
239
|
+
let node = ctx;
|
|
240
|
+
while (node) {
|
|
241
|
+
if (node.id === root.id) {
|
|
242
|
+
return true;
|
|
243
|
+
}
|
|
244
|
+
node = node.parent;
|
|
245
|
+
}
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Whether `ctx` runs within the dispatch `step` is the lane of: beneath its
|
|
250
|
+
* context, or on that context under its execution path. Lanes of one context
|
|
251
|
+
* share its id, so the path is what tells concurrent dispatches apart.
|
|
252
|
+
*/
|
|
253
|
+
function inside(ctx, step) {
|
|
254
|
+
for (let node = ctx; node; node = node.parent) {
|
|
255
|
+
if (node.id === step.id) {
|
|
256
|
+
return under(pathOf(node), pathOf(step));
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return false;
|
|
260
|
+
}
|
|
261
|
+
function pathOf(ctx) {
|
|
262
|
+
return ctx instanceof ContextImpl ? ctx.currentPath() : '';
|
|
263
|
+
}
|
|
264
|
+
/** Whether `path` is `base` or a path beneath it (`/step#n` or `[i]` segments). */
|
|
265
|
+
function under(path, base) {
|
|
266
|
+
if (!path.startsWith(base)) {
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
const next = path[base.length];
|
|
270
|
+
return next === undefined || next === '/' || next === '[';
|
|
271
|
+
}
|
|
272
|
+
function emit(ctx, eventType, data) {
|
|
273
|
+
emitFrameworkEvent({
|
|
274
|
+
broadcaster: getBroadcaster(ctx),
|
|
275
|
+
agentName: ctx.harness.config.name,
|
|
276
|
+
eventType,
|
|
277
|
+
data,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
//#endregion
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The spend log: one record per paid provider call, written before the call is sent
|
|
3
|
+
* and deleted once its bill is known (spec 23 § Paid dispatches).
|
|
4
|
+
*
|
|
5
|
+
* Records live under `spend:<id>`, outside the `execution:<id>:` prefix, so clearing a
|
|
6
|
+
* checkpoint or abandoning a turn never discards evidence that money was spent.
|
|
7
|
+
*/
|
|
8
|
+
import type { StorageAdapter } from '@noetic-tools/context';
|
|
9
|
+
import { z } from 'zod';
|
|
10
|
+
/** @internal A dispatch record as stored. */
|
|
11
|
+
export declare const DispatchRecordSchema: z.ZodObject<{
|
|
12
|
+
id: z.ZodString;
|
|
13
|
+
kind: z.ZodEnum<{
|
|
14
|
+
model: "model";
|
|
15
|
+
decide: "decide";
|
|
16
|
+
}>;
|
|
17
|
+
model: z.ZodString;
|
|
18
|
+
requestHash: z.ZodString;
|
|
19
|
+
inputTokens: z.ZodNumber;
|
|
20
|
+
maxOutputTokens: z.ZodOptional<z.ZodNumber>;
|
|
21
|
+
executionId: z.ZodOptional<z.ZodString>;
|
|
22
|
+
threadId: z.ZodOptional<z.ZodString>;
|
|
23
|
+
path: z.ZodOptional<z.ZodString>;
|
|
24
|
+
generationId: z.ZodOptional<z.ZodString>;
|
|
25
|
+
sentAt: z.ZodString;
|
|
26
|
+
}, z.core.$strip>;
|
|
27
|
+
/** @internal */
|
|
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;
|
|
49
|
+
/** @internal */
|
|
50
|
+
export interface SpendLog {
|
|
51
|
+
put(record: DispatchRecord): Promise<void>;
|
|
52
|
+
get(id: string): Promise<SpendRecord | undefined>;
|
|
53
|
+
remove(id: string): Promise<void>;
|
|
54
|
+
/** Every record: unreadable ones first, since their age is unknown, then oldest first. */
|
|
55
|
+
list(): Promise<SpendRecord[]>;
|
|
56
|
+
}
|
|
57
|
+
/** @internal */
|
|
58
|
+
export declare function createSpendLog(storage: StorageAdapter): SpendLog;
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The spend log: one record per paid provider call, written before the call is sent
|
|
3
|
+
* and deleted once its bill is known (spec 23 § Paid dispatches).
|
|
4
|
+
*
|
|
5
|
+
* Records live under `spend:<id>`, outside the `execution:<id>:` prefix, so clearing a
|
|
6
|
+
* checkpoint or abandoning a turn never discards evidence that money was spent.
|
|
7
|
+
*/
|
|
8
|
+
import { storageGetMany } from '@noetic-tools/context';
|
|
9
|
+
import { z } from 'zod';
|
|
10
|
+
//#region Schema
|
|
11
|
+
const SPEND_PREFIX = 'spend:';
|
|
12
|
+
/** @internal A dispatch record as stored. */
|
|
13
|
+
export const DispatchRecordSchema = z.object({
|
|
14
|
+
id: z.string().min(1),
|
|
15
|
+
kind: z.enum([
|
|
16
|
+
'model',
|
|
17
|
+
'decide',
|
|
18
|
+
]),
|
|
19
|
+
model: z.string(),
|
|
20
|
+
requestHash: z.string(),
|
|
21
|
+
inputTokens: z.number(),
|
|
22
|
+
maxOutputTokens: z.number().optional(),
|
|
23
|
+
executionId: z.string().optional(),
|
|
24
|
+
threadId: z.string().optional(),
|
|
25
|
+
path: z.string().optional(),
|
|
26
|
+
generationId: z.string().optional(),
|
|
27
|
+
sentAt: z.string(),
|
|
28
|
+
});
|
|
29
|
+
/** @internal */
|
|
30
|
+
export function isUnreadable(record) {
|
|
31
|
+
return 'unreadable' in record;
|
|
32
|
+
}
|
|
33
|
+
/** @internal */
|
|
34
|
+
export function createSpendLog(storage) {
|
|
35
|
+
return {
|
|
36
|
+
put: async (record) => {
|
|
37
|
+
await storage.set(keyOf(record.id), record);
|
|
38
|
+
},
|
|
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
|
+
},
|
|
47
|
+
remove: async (id) => {
|
|
48
|
+
await storage.delete(keyOf(id));
|
|
49
|
+
},
|
|
50
|
+
list: async () => {
|
|
51
|
+
const keys = await storage.list(SPEND_PREFIX);
|
|
52
|
+
const raws = await storageGetMany(storage, keys);
|
|
53
|
+
const damaged = [];
|
|
54
|
+
const records = [];
|
|
55
|
+
for (const [key, raw] of raws) {
|
|
56
|
+
if (isNothing(raw)) {
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
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
|
+
}
|
|
66
|
+
}
|
|
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
|
+
];
|
|
74
|
+
},
|
|
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
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function keyOf(id) {
|
|
90
|
+
return `${SPEND_PREFIX}${id}`;
|
|
91
|
+
}
|
|
92
|
+
function isNothing(raw) {
|
|
93
|
+
return raw === null || raw === undefined;
|
|
94
|
+
}
|
|
95
|
+
function parse(id, raw) {
|
|
96
|
+
const parsed = DispatchRecordSchema.safeParse(raw);
|
|
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
|
+
};
|
|
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
|
+
});
|
|
133
|
+
//#endregion
|
|
@@ -98,6 +98,12 @@ export declare function resolveStepLedgerRetention(retention?: StepLedgerRetenti
|
|
|
98
98
|
* and its round-tripped copy, so a resumed run hashes the same inputs the first run did.
|
|
99
99
|
*/
|
|
100
100
|
export declare function hashStepInput(input: unknown): string | undefined;
|
|
101
|
+
/**
|
|
102
|
+
* @internal
|
|
103
|
+
* 53-bit string hash (cyrb53, public domain: https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js).
|
|
104
|
+
* Not cryptographic — it tells "same input" from "changed input", nothing more.
|
|
105
|
+
*/
|
|
106
|
+
export declare function hashText(text: string): string;
|
|
101
107
|
/** Storage key prefix owning every ledger entry for one execution. */
|
|
102
108
|
export declare function stepLedgerPrefix(executionId: string): string;
|
|
103
109
|
/**
|
|
@@ -206,9 +212,10 @@ export declare class StepLedger {
|
|
|
206
212
|
/**
|
|
207
213
|
* Record a completed step, then prune what it makes dead: a resumed run replays this
|
|
208
214
|
* entry without descending, so nothing recorded beneath it will be read again.
|
|
209
|
-
* 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.
|
|
210
217
|
*/
|
|
211
|
-
record(entry: StepLedgerEntry): Promise<
|
|
218
|
+
record(entry: StepLedgerEntry): Promise<boolean>;
|
|
212
219
|
/**
|
|
213
220
|
* Drop every positional entry. A host calls this once a run has finished and the
|
|
214
221
|
* checkpoint holds its result: every later resume starts past them, so they are dead.
|
|
@@ -126,13 +126,14 @@ export function hashStepInput(input) {
|
|
|
126
126
|
catch {
|
|
127
127
|
return undefined;
|
|
128
128
|
}
|
|
129
|
-
return
|
|
129
|
+
return hashText(json ?? 'undefined');
|
|
130
130
|
}
|
|
131
131
|
/**
|
|
132
|
+
* @internal
|
|
132
133
|
* 53-bit string hash (cyrb53, public domain: https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js).
|
|
133
134
|
* Not cryptographic — it tells "same input" from "changed input", nothing more.
|
|
134
135
|
*/
|
|
135
|
-
function
|
|
136
|
+
export function hashText(text) {
|
|
136
137
|
let h1 = 0xdeadbeef;
|
|
137
138
|
let h2 = 0x41c6ce57;
|
|
138
139
|
for (let i = 0; i < text.length; i++) {
|
|
@@ -313,14 +314,15 @@ export class StepLedger {
|
|
|
313
314
|
/**
|
|
314
315
|
* Record a completed step, then prune what it makes dead: a resumed run replays this
|
|
315
316
|
* entry without descending, so nothing recorded beneath it will be read again.
|
|
316
|
-
* 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.
|
|
317
319
|
*/
|
|
318
320
|
async record(entry) {
|
|
319
321
|
if (!this.store) {
|
|
320
|
-
return;
|
|
322
|
+
return false;
|
|
321
323
|
}
|
|
322
324
|
if (!this.retainable(entry)) {
|
|
323
|
-
return;
|
|
325
|
+
return false;
|
|
324
326
|
}
|
|
325
327
|
/* Reserve the sequence number BEFORE awaiting: concurrent inParallel legs record through
|
|
326
328
|
* the one shared ledger, and two of them reading the same counter would write the
|
|
@@ -332,7 +334,7 @@ export class StepLedger {
|
|
|
332
334
|
}
|
|
333
335
|
catch (error) {
|
|
334
336
|
console.warn(`StepLedger: failed to record "${entry.path}":`, error instanceof Error ? error.message : String(error));
|
|
335
|
-
return;
|
|
337
|
+
return false;
|
|
336
338
|
}
|
|
337
339
|
const replaced = this.live.get(entry.path);
|
|
338
340
|
this.live.set(entry.path, seq);
|
|
@@ -343,6 +345,7 @@ export class StepLedger {
|
|
|
343
345
|
if (!entry.path.startsWith(REPLAY_KEY_PREFIX)) {
|
|
344
346
|
await this.prune(this.live.beneath(entry.path));
|
|
345
347
|
}
|
|
348
|
+
return true;
|
|
346
349
|
}
|
|
347
350
|
/**
|
|
348
351
|
* Drop every positional entry. A host calls this once a run has finished and the
|
|
@@ -40,7 +40,7 @@ export interface SessionRunnerOpts {
|
|
|
40
40
|
/**
|
|
41
41
|
* @internal
|
|
42
42
|
*
|
|
43
|
-
* Per-thread runner.
|
|
43
|
+
* Per-thread runner. Works through the MessageQueue and drives turns on the shared
|
|
44
44
|
* session broadcaster. Emits `turn_started` / `turn_completed` /
|
|
45
45
|
* `inbox_injected` framework events so consumers can correlate queued
|
|
46
46
|
* messages with the turn that delivered them.
|
|
@@ -78,6 +78,8 @@ export declare class SessionRunner {
|
|
|
78
78
|
private readonly responseWaiters;
|
|
79
79
|
constructor(opts: SessionRunnerOpts);
|
|
80
80
|
getStatus(): HarnessStatus;
|
|
81
|
+
/** The running turn's context, if a turn is running. */
|
|
82
|
+
get context(): Context | undefined;
|
|
81
83
|
/** Queue a message. A steer that arrives mid-turn is announced first, so
|
|
82
84
|
* `steer_accepted` always precedes the `inbox_injected` that applies it. */
|
|
83
85
|
enqueue(message: QueuedMessage): void;
|
|
@@ -96,9 +98,9 @@ export declare class SessionRunner {
|
|
|
96
98
|
/** Cancel the in-flight turn. Does NOT re-kick — callers that want restart
|
|
97
99
|
* behaviour should enqueue a message before/after calling abort. */
|
|
98
100
|
abort(reason?: string): Promise<void>;
|
|
99
|
-
/** Start the
|
|
101
|
+
/** Start the queue loop if not already running. Safe to call many times. */
|
|
100
102
|
kick(): void;
|
|
101
|
-
private
|
|
103
|
+
private runQueue;
|
|
102
104
|
private runOneTurn;
|
|
103
105
|
/**
|
|
104
106
|
* Add what the turn spent to the session's totals, before anyone waiting on the turn
|