@noetic-tools/core 5.13.0 → 5.14.1
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/builders/decide-builders.d.ts +2 -2
- package/dist/builders/dynamic-workflow.js +2 -0
- package/dist/builders/provide-builder.d.ts +2 -2
- package/dist/builders/spawn-builder.d.ts +2 -2
- package/dist/builders/step-builders.d.ts +5 -5
- package/dist/builders/workflow-hydrator.d.ts +1 -1
- package/dist/builders/workflow-hydrator.js +53 -3
- package/dist/expression/check.js +14 -0
- package/dist/expression/jsonata.d.ts +7 -0
- package/dist/expression/jsonata.js +11 -1
- package/dist/harness/agent-harness.d.ts +59 -5
- package/dist/harness/agent-harness.js +176 -25
- package/dist/harness/deps/runtime.d.ts +4 -0
- package/dist/harness/deps/runtime.js +2 -0
- package/dist/harness/model-call.js +69 -0
- package/dist/harness/model-rounds.d.ts +52 -0
- package/dist/harness/model-rounds.js +115 -0
- package/dist/harness/thread-record.d.ts +54 -0
- package/dist/harness/thread-record.js +159 -0
- package/dist/index.d.ts +2 -2
- package/dist/interpreter/emit-items.d.ts +19 -0
- package/dist/interpreter/emit-items.js +106 -0
- package/dist/interpreter/execute-action.js +4 -1
- package/dist/interpreter/execute-control.js +7 -3
- package/dist/interpreter/execute.js +66 -9
- package/dist/observability/span-impl.d.ts +9 -0
- package/dist/observability/span-impl.js +13 -0
- package/dist/runtime/context-impl.d.ts +156 -14
- package/dist/runtime/context-impl.js +326 -28
- package/dist/runtime/durable/harness-checkpoints.d.ts +13 -3
- package/dist/runtime/durable/harness-checkpoints.js +66 -7
- package/dist/runtime/durable/session-store.d.ts +37 -0
- package/dist/runtime/durable/session-store.js +58 -0
- package/dist/runtime/durable/step-ledger.d.ts +77 -40
- package/dist/runtime/durable/step-ledger.js +193 -73
- package/dist/runtime/item-log-impl.d.ts +6 -0
- package/dist/runtime/item-log-impl.js +12 -0
- package/dist/runtime/session-runner.d.ts +25 -1
- package/dist/runtime/session-runner.js +83 -11
- package/dist/schemas/workflow.d.ts +1 -1
- package/dist/types/checkpoint.d.ts +21 -4
- package/dist/types/checkpoint.js +33 -3
- package/package.json +2 -2
- package/schema/noetic-workflow.schema.json +391 -0
|
@@ -17,11 +17,19 @@
|
|
|
17
17
|
* `key:<replayKey>` instead: content-addressed, so it finds its output wherever it
|
|
18
18
|
* runs. A `durable: false` step has no key and is never recorded.
|
|
19
19
|
*
|
|
20
|
+
* An entry also carries what replay must put back: the items the step appended to its
|
|
21
|
+
* context's item log (a checkpoint holds the log as it stood when the run began, so the
|
|
22
|
+
* replayed steps rebuild the rest), and a hash of the step's input, so a step whose input
|
|
23
|
+
* changed since it was recorded runs again instead of replaying an answer to a
|
|
24
|
+
* different question.
|
|
25
|
+
*
|
|
20
26
|
* Sharding bounds the cost of one append but not the total, so retention is bounded on
|
|
21
27
|
* two axes (`StepLedgerRetention`): an oversized entry is dropped rather than written,
|
|
22
|
-
* and
|
|
23
|
-
*
|
|
24
|
-
*
|
|
28
|
+
* and once `maxEntries` are live nothing more is recorded. Entries beneath a parent that
|
|
29
|
+
* recorded are pruned, since a resumed run replays the parent without descending, so the
|
|
30
|
+
* live count tracks the open part of the run rather than its length. Both degradations
|
|
31
|
+
* are safe by construction — a missing entry re-runs its step, which costs work rather
|
|
32
|
+
* than correctness.
|
|
25
33
|
*/
|
|
26
34
|
import { storageGetMany } from '@noetic-tools/context';
|
|
27
35
|
import { NoeticConfigError } from '@noetic-tools/types';
|
|
@@ -40,6 +48,18 @@ export const StepLedgerEntrySchema = z.object({
|
|
|
40
48
|
kind: z.string(),
|
|
41
49
|
/** Replayed verbatim in place of re-running the step. */
|
|
42
50
|
output: z.unknown(),
|
|
51
|
+
/**
|
|
52
|
+
* Hash of the step's input when it ran (`hashStepInput`). Replay requires the new
|
|
53
|
+
* dispatch's input to hash the same. Absent when the input could not be encoded.
|
|
54
|
+
*/
|
|
55
|
+
inputHash: z.string().optional(),
|
|
56
|
+
/** Items the step appended to its context's item log, re-appended on replay. */
|
|
57
|
+
items: z.array(z.unknown()).optional(),
|
|
58
|
+
/**
|
|
59
|
+
* Indices into `items` of those `step.emitItems` emitted (spec 01 § Emitting items),
|
|
60
|
+
* streamed again on replay when the harness sets `emitItemsOnReplay`.
|
|
61
|
+
*/
|
|
62
|
+
streamed: z.array(z.number().int().nonnegative()).optional(),
|
|
43
63
|
completedAt: z.string(),
|
|
44
64
|
});
|
|
45
65
|
/** @public Retention applied when a harness does not configure `stepLedgerRetention`. */
|
|
@@ -90,6 +110,41 @@ function fitsByteCap(json, cap) {
|
|
|
90
110
|
return new TextEncoder().encode(json).length <= cap;
|
|
91
111
|
}
|
|
92
112
|
//#endregion
|
|
113
|
+
//#region Input hash
|
|
114
|
+
/**
|
|
115
|
+
* @internal
|
|
116
|
+
* A short, stable hash of a step input's JSON encoding, or undefined when the input
|
|
117
|
+
* cannot be encoded (a cycle, a `BigInt`). A replayed output becomes the next step's
|
|
118
|
+
* input after a JSON round trip, and `JSON.stringify` gives the same text for a value
|
|
119
|
+
* and its round-tripped copy, so a resumed run hashes the same inputs the first run did.
|
|
120
|
+
*/
|
|
121
|
+
export function hashStepInput(input) {
|
|
122
|
+
let json;
|
|
123
|
+
try {
|
|
124
|
+
json = JSON.stringify(input);
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
return cyrb53(json ?? 'undefined');
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* 53-bit string hash (cyrb53, public domain: https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js).
|
|
133
|
+
* Not cryptographic — it tells "same input" from "changed input", nothing more.
|
|
134
|
+
*/
|
|
135
|
+
function cyrb53(text) {
|
|
136
|
+
let h1 = 0xdeadbeef;
|
|
137
|
+
let h2 = 0x41c6ce57;
|
|
138
|
+
for (let i = 0; i < text.length; i++) {
|
|
139
|
+
const ch = text.charCodeAt(i);
|
|
140
|
+
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
141
|
+
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
142
|
+
}
|
|
143
|
+
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
144
|
+
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
145
|
+
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
|
|
146
|
+
}
|
|
147
|
+
//#endregion
|
|
93
148
|
//#region Store
|
|
94
149
|
/** Storage key prefix owning every ledger entry for one execution. */
|
|
95
150
|
export function stepLedgerPrefix(executionId) {
|
|
@@ -123,20 +178,21 @@ export function createStepLedgerStore(opts) {
|
|
|
123
178
|
* moment a network-backed adapter can least afford an N+1. */
|
|
124
179
|
const raws = await storageGetMany(storage, keys);
|
|
125
180
|
const entries = new Map();
|
|
126
|
-
/*
|
|
127
|
-
* parse still occupies its key, so it must not be handed back out
|
|
181
|
+
/* The next sequence number comes from the KEYS, not the parsed rows: a row that
|
|
182
|
+
* fails to parse still occupies its key, so it must not be handed back out. */
|
|
128
183
|
let highestSeq = -1;
|
|
129
|
-
|
|
130
|
-
// Walk
|
|
131
|
-
//
|
|
132
|
-
for (const key of
|
|
184
|
+
const seqs = new Map();
|
|
185
|
+
// Walk the keys sorted: `seqKey`'s zero-padding makes key order dispatch order,
|
|
186
|
+
// and a later entry at a path must win over an earlier one.
|
|
187
|
+
for (const key of [
|
|
188
|
+
...keys,
|
|
189
|
+
].sort()) {
|
|
133
190
|
const seq = seqFromKey(executionId, key);
|
|
134
191
|
if (seq !== null) {
|
|
135
192
|
highestSeq = Math.max(highestSeq, seq);
|
|
136
|
-
oldestSeq = oldestSeq === -1 ? seq : Math.min(oldestSeq, seq);
|
|
137
193
|
}
|
|
138
194
|
const raw = raws.get(key);
|
|
139
|
-
if (raw === undefined) {
|
|
195
|
+
if (raw === undefined || seq === null) {
|
|
140
196
|
continue;
|
|
141
197
|
}
|
|
142
198
|
const parsed = StepLedgerEntrySchema.safeParse(raw);
|
|
@@ -147,11 +203,12 @@ export function createStepLedgerStore(opts) {
|
|
|
147
203
|
continue;
|
|
148
204
|
}
|
|
149
205
|
entries.set(parsed.data.path, parsed.data);
|
|
206
|
+
seqs.set(parsed.data.path, seq);
|
|
150
207
|
}
|
|
151
208
|
return {
|
|
152
209
|
entries,
|
|
210
|
+
seqs,
|
|
153
211
|
nextSeq: highestSeq + 1,
|
|
154
|
-
oldestSeq: oldestSeq === -1 ? 0 : oldestSeq,
|
|
155
212
|
};
|
|
156
213
|
},
|
|
157
214
|
clear: async (executionId) => {
|
|
@@ -169,16 +226,16 @@ export function createStepLedgerStore(opts) {
|
|
|
169
226
|
*
|
|
170
227
|
* Shared by reference across inParallel/spawn children so one execution has one ledger —
|
|
171
228
|
* path keys are globally unique across the step tree, so a flat map is correct. That
|
|
172
|
-
* sharing is also why retention lives here rather than in the store: the
|
|
173
|
-
*
|
|
229
|
+
* sharing is also why retention lives here rather than in the store: the live set that
|
|
230
|
+
* the entry cap counts belongs to the execution, not to the harness.
|
|
174
231
|
*/
|
|
175
232
|
export class StepLedger {
|
|
176
|
-
/** Recovered entries, by path.
|
|
177
|
-
replayable;
|
|
233
|
+
/** Recovered entries, by path. */
|
|
234
|
+
replayable = new Map();
|
|
235
|
+
/** Sequence number holding each live entry, recovered or recorded, by path. */
|
|
236
|
+
live;
|
|
178
237
|
/** Sequence number the next recorded entry takes. */
|
|
179
238
|
seq;
|
|
180
|
-
/** Lowest sequence number still in storage — advances as eviction proceeds. */
|
|
181
|
-
oldestSeq;
|
|
182
239
|
store;
|
|
183
240
|
executionId;
|
|
184
241
|
retention;
|
|
@@ -186,15 +243,33 @@ export class StepLedger {
|
|
|
186
243
|
recorded: 0,
|
|
187
244
|
droppedOversize: 0,
|
|
188
245
|
droppedUnserialisable: 0,
|
|
189
|
-
|
|
246
|
+
droppedFull: 0,
|
|
247
|
+
pruned: 0,
|
|
190
248
|
};
|
|
191
249
|
constructor(opts) {
|
|
192
250
|
this.executionId = opts.executionId;
|
|
193
251
|
this.store = opts.store;
|
|
194
252
|
this.retention = resolveStepLedgerRetention(opts.retention);
|
|
195
|
-
this.
|
|
196
|
-
this.seq =
|
|
197
|
-
|
|
253
|
+
this.live = new Map();
|
|
254
|
+
this.seq = 0;
|
|
255
|
+
if (opts.recovered) {
|
|
256
|
+
this.adopt(opts.recovered);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Take what storage now holds for this execution in place of what this ledger has
|
|
261
|
+
* in memory — for a run retried in place, which replays what was stored.
|
|
262
|
+
*/
|
|
263
|
+
adopt(recovered) {
|
|
264
|
+
this.replayable.clear();
|
|
265
|
+
for (const [path, entry] of recovered.entries) {
|
|
266
|
+
this.replayable.set(path, entry);
|
|
267
|
+
}
|
|
268
|
+
this.live.clear();
|
|
269
|
+
for (const [path, seq] of recovered.seqs) {
|
|
270
|
+
this.live.set(path, seq);
|
|
271
|
+
}
|
|
272
|
+
this.seq = Math.max(this.seq, recovered.nextSeq);
|
|
198
273
|
}
|
|
199
274
|
/** True when this execution has nothing recovered to replay (the common, fresh case). */
|
|
200
275
|
get isEmpty() {
|
|
@@ -207,39 +282,40 @@ export class StepLedger {
|
|
|
207
282
|
};
|
|
208
283
|
}
|
|
209
284
|
/**
|
|
210
|
-
* The recorded
|
|
211
|
-
* A divergence
|
|
212
|
-
* runs fresh. At a positional path it also discards every entry
|
|
213
|
-
* the subtree's
|
|
214
|
-
* entry discards only itself:
|
|
215
|
-
*
|
|
285
|
+
* The recorded entry for `path`, when a previous run completed the same step there on
|
|
286
|
+
* the same input. A divergence — a different step id, kind, or input — returns
|
|
287
|
+
* undefined so the step runs fresh. At a positional path it also discards every entry
|
|
288
|
+
* recorded beneath it: the subtree's outputs belong to a run that no longer exists. A
|
|
289
|
+
* `key:` entry discards only itself: nothing is nested under a content key.
|
|
290
|
+
*
|
|
291
|
+
* An entry recorded without an input hash matches on identity alone.
|
|
216
292
|
*/
|
|
217
293
|
take(path, step) {
|
|
218
294
|
const entry = this.replayable.get(path);
|
|
219
295
|
if (!entry) {
|
|
220
296
|
return undefined;
|
|
221
297
|
}
|
|
222
|
-
if (entry
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
this.discardSubtree(path);
|
|
298
|
+
if (matches(entry, step)) {
|
|
299
|
+
return entry;
|
|
300
|
+
}
|
|
301
|
+
if (path.startsWith(REPLAY_KEY_PREFIX)) {
|
|
302
|
+
this.replayable.delete(path);
|
|
228
303
|
return undefined;
|
|
229
304
|
}
|
|
230
|
-
return entry;
|
|
231
|
-
}
|
|
232
|
-
/** Drop `path` and everything recorded below it. */
|
|
233
|
-
discardSubtree(path) {
|
|
234
305
|
for (const key of [
|
|
235
306
|
...this.replayable.keys(),
|
|
236
307
|
]) {
|
|
237
|
-
if (key === path || key
|
|
308
|
+
if (key === path || isBeneath(key, path)) {
|
|
238
309
|
this.replayable.delete(key);
|
|
239
310
|
}
|
|
240
311
|
}
|
|
312
|
+
return undefined;
|
|
241
313
|
}
|
|
242
|
-
/**
|
|
314
|
+
/**
|
|
315
|
+
* Record a completed step, then prune what it makes dead: a resumed run replays this
|
|
316
|
+
* entry without descending, so nothing recorded beneath it will be read again.
|
|
317
|
+
* Best-effort: a failed write costs resumability, not the run.
|
|
318
|
+
*/
|
|
243
319
|
async record(entry) {
|
|
244
320
|
if (!this.store) {
|
|
245
321
|
return;
|
|
@@ -249,9 +325,7 @@ export class StepLedger {
|
|
|
249
325
|
}
|
|
250
326
|
/* Reserve the sequence number BEFORE awaiting: concurrent inParallel legs record through
|
|
251
327
|
* the one shared ledger, and two of them reading the same counter would write the
|
|
252
|
-
* same key, silently overwriting a sibling's entry.
|
|
253
|
-
* gap, which only makes the window below a slight over-estimate of the live count —
|
|
254
|
-
* eviction runs marginally early, never late. */
|
|
328
|
+
* same key, silently overwriting a sibling's entry. */
|
|
255
329
|
const seq = this.seq;
|
|
256
330
|
this.seq = seq + 1;
|
|
257
331
|
try {
|
|
@@ -261,56 +335,92 @@ export class StepLedger {
|
|
|
261
335
|
console.warn(`StepLedger: failed to record "${entry.path}":`, error instanceof Error ? error.message : String(error));
|
|
262
336
|
return;
|
|
263
337
|
}
|
|
338
|
+
const replaced = this.live.get(entry.path);
|
|
339
|
+
this.live.set(entry.path, seq);
|
|
264
340
|
this.counts.recorded += 1;
|
|
265
|
-
|
|
341
|
+
if (replaced !== undefined) {
|
|
342
|
+
await this.deleteSeq(replaced);
|
|
343
|
+
}
|
|
344
|
+
if (!entry.path.startsWith(REPLAY_KEY_PREFIX)) {
|
|
345
|
+
await this.prune((path) => isBeneath(path, entry.path));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Drop every positional entry. A host calls this once a run has finished and the
|
|
350
|
+
* checkpoint holds its result: every later resume starts past them, so they are dead.
|
|
351
|
+
* `key:` entries stay — they are keyed by content, and a later run may ask the same.
|
|
352
|
+
*/
|
|
353
|
+
async dropPaths() {
|
|
354
|
+
await this.prune((path) => !path.startsWith(REPLAY_KEY_PREFIX));
|
|
355
|
+
for (const path of [
|
|
356
|
+
...this.replayable.keys(),
|
|
357
|
+
]) {
|
|
358
|
+
if (!path.startsWith(REPLAY_KEY_PREFIX)) {
|
|
359
|
+
this.replayable.delete(path);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
async prune(dead) {
|
|
364
|
+
for (const [path, seq] of [
|
|
365
|
+
...this.live,
|
|
366
|
+
]) {
|
|
367
|
+
if (!dead(path)) {
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
this.live.delete(path);
|
|
371
|
+
this.replayable.delete(path);
|
|
372
|
+
this.counts.pruned += 1;
|
|
373
|
+
await this.deleteSeq(seq);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
async deleteSeq(seq) {
|
|
377
|
+
try {
|
|
378
|
+
await this.store?.delete(this.executionId, seq);
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
console.warn(`StepLedger: failed to delete entry ${seq} of "${this.executionId}":`, error instanceof Error ? error.message : String(error));
|
|
382
|
+
}
|
|
266
383
|
}
|
|
267
384
|
/**
|
|
268
|
-
* Whether this entry is small enough
|
|
269
|
-
*
|
|
270
|
-
* not recorded, so the step re-runs.
|
|
385
|
+
* Whether this entry is small enough, encodable, and within the live cap. An entry
|
|
386
|
+
* that fails any test is not recorded, so its step re-runs on resume.
|
|
271
387
|
*/
|
|
272
388
|
retainable(entry) {
|
|
273
|
-
|
|
389
|
+
if (!this.live.has(entry.path) && this.liveAfter(entry.path) >= this.retention.maxEntries) {
|
|
390
|
+
this.counts.droppedFull += 1;
|
|
391
|
+
this.warnOnFirstDrop(this.counts.droppedFull, `StepLedger: not recording "${entry.path}" — ${this.retention.maxEntries} entries (maxEntries) are already live.`);
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
let bytes;
|
|
274
395
|
try {
|
|
275
|
-
|
|
396
|
+
// `undefined` stringifies to nothing; there is no size to bound.
|
|
397
|
+
bytes =
|
|
398
|
+
(JSON.stringify(entry.output) ?? '') + (entry.items ? JSON.stringify(entry.items) : '');
|
|
276
399
|
}
|
|
277
400
|
catch {
|
|
278
401
|
this.counts.droppedUnserialisable += 1;
|
|
279
402
|
this.warnOnFirstDrop(this.counts.droppedUnserialisable, `StepLedger: not recording "${entry.path}" — its output does not survive JSON encoding.`);
|
|
280
403
|
return false;
|
|
281
404
|
}
|
|
282
|
-
|
|
283
|
-
if (json !== undefined && !fitsByteCap(json, this.retention.maxEntryBytes)) {
|
|
405
|
+
if (!fitsByteCap(bytes, this.retention.maxEntryBytes)) {
|
|
284
406
|
this.counts.droppedOversize += 1;
|
|
285
|
-
this.warnOnFirstDrop(this.counts.droppedOversize, `StepLedger: not recording "${entry.path}" — output
|
|
407
|
+
this.warnOnFirstDrop(this.counts.droppedOversize, `StepLedger: not recording "${entry.path}" — output and items exceed maxEntryBytes (${this.retention.maxEntryBytes}).`);
|
|
286
408
|
return false;
|
|
287
409
|
}
|
|
288
410
|
return true;
|
|
289
411
|
}
|
|
290
|
-
/**
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
*/
|
|
295
|
-
async evictOverflow() {
|
|
296
|
-
const store = this.store;
|
|
297
|
-
if (!store) {
|
|
298
|
-
return;
|
|
412
|
+
/** Live entries once recording at `path` has pruned what lies beneath it. */
|
|
413
|
+
liveAfter(path) {
|
|
414
|
+
if (this.live.size < this.retention.maxEntries || path.startsWith(REPLAY_KEY_PREFIX)) {
|
|
415
|
+
return this.live.size;
|
|
299
416
|
}
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
417
|
+
let beneath = 0;
|
|
418
|
+
for (const key of this.live.keys()) {
|
|
419
|
+
if (isBeneath(key, path)) {
|
|
420
|
+
beneath += 1;
|
|
304
421
|
}
|
|
305
|
-
catch (error) {
|
|
306
|
-
/* Leave the cursor where it is and stop: the next append retries this victim
|
|
307
|
-
* rather than spinning on a store that is currently refusing deletes. */
|
|
308
|
-
console.warn(`StepLedger: failed to evict entry ${victim} of "${this.executionId}":`, error instanceof Error ? error.message : String(error));
|
|
309
|
-
return;
|
|
310
|
-
}
|
|
311
|
-
this.oldestSeq = victim + 1;
|
|
312
|
-
this.counts.evicted += 1;
|
|
313
422
|
}
|
|
423
|
+
return this.live.size - beneath;
|
|
314
424
|
}
|
|
315
425
|
/** One warning per reason per execution — a long run would otherwise flood the log. */
|
|
316
426
|
warnOnFirstDrop(count, message) {
|
|
@@ -320,4 +430,14 @@ export class StepLedger {
|
|
|
320
430
|
console.warn(`${message} The step will re-run on resume; further drops are silent.`);
|
|
321
431
|
}
|
|
322
432
|
}
|
|
433
|
+
function matches(entry, step) {
|
|
434
|
+
if (entry.stepId !== step.id || entry.kind !== step.kind) {
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
return entry.inputHash === undefined || entry.inputHash === step.inputHash;
|
|
438
|
+
}
|
|
439
|
+
/** Whether `path` lies in the subtree under `parent` — a lane below it or a child context's prefix. */
|
|
440
|
+
function isBeneath(path, parent) {
|
|
441
|
+
return path.startsWith(`${parent}/`) || path.startsWith(`${parent}[`);
|
|
442
|
+
}
|
|
323
443
|
//#endregion
|
|
@@ -5,5 +5,11 @@ export declare class ItemLogImpl implements ItemLog {
|
|
|
5
5
|
private _frozenCache;
|
|
6
6
|
constructor(itemSchemas?: ItemSchemaRegistry);
|
|
7
7
|
get items(): ReadonlyArray<Item>;
|
|
8
|
+
/**
|
|
9
|
+
* @internal
|
|
10
|
+
* Swap the whole log for `items`. Only for a context rebuilding itself from storage
|
|
11
|
+
* before a run starts; nothing reads a log while it is replaced.
|
|
12
|
+
*/
|
|
13
|
+
replace(items: ReadonlyArray<Item>): void;
|
|
8
14
|
append(item: Item): void;
|
|
9
15
|
}
|
|
@@ -18,6 +18,18 @@ export class ItemLogImpl {
|
|
|
18
18
|
}
|
|
19
19
|
return frozenItems;
|
|
20
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* @internal
|
|
23
|
+
* Swap the whole log for `items`. Only for a context rebuilding itself from storage
|
|
24
|
+
* before a run starts; nothing reads a log while it is replaced.
|
|
25
|
+
*/
|
|
26
|
+
replace(items) {
|
|
27
|
+
this._items.length = 0;
|
|
28
|
+
for (const item of items) {
|
|
29
|
+
this._items.push(this.itemSchemas.parse(item));
|
|
30
|
+
}
|
|
31
|
+
this._frozenCache = null;
|
|
32
|
+
}
|
|
21
33
|
append(item) {
|
|
22
34
|
this._items.push(this.itemSchemas.parse(item));
|
|
23
35
|
this._frozenCache = null;
|
|
@@ -17,12 +17,25 @@ export interface TurnContext {
|
|
|
17
17
|
* plus the messages being delivered this turn so the harness can honour
|
|
18
18
|
* per-turn `ExecuteOptions` (the first message's options establish
|
|
19
19
|
* resourceId/state/context for the turn). */
|
|
20
|
-
export type CreateContextFn = (items: ReadonlyArray<Item>, turnId: string, messages: ReadonlyArray<QueuedMessage>) => Context
|
|
20
|
+
export type CreateContextFn = (items: ReadonlyArray<Item>, turnId: string, messages: ReadonlyArray<QueuedMessage>) => Context | Promise<Context>;
|
|
21
|
+
/** @internal What one turn spent: its context's usage at the end, less at the start. */
|
|
22
|
+
export interface TurnUsage {
|
|
23
|
+
inputTokens: number;
|
|
24
|
+
outputTokens: number;
|
|
25
|
+
cachedTokens?: number;
|
|
26
|
+
cost: number;
|
|
27
|
+
billedCost: number;
|
|
28
|
+
}
|
|
21
29
|
export interface SessionRunnerOpts {
|
|
22
30
|
readonly threadId: string;
|
|
23
31
|
readonly agentName: string;
|
|
24
32
|
readonly runTurn: RunTurnFn;
|
|
25
33
|
readonly createContext: CreateContextFn;
|
|
34
|
+
/**
|
|
35
|
+
* Called once per turn, success or not, with what the turn spent. A durable host
|
|
36
|
+
* writes it to storage and hands the stored totals back through `seedUsage`.
|
|
37
|
+
*/
|
|
38
|
+
readonly onTurnUsage?: (usage: TurnUsage) => Promise<void>;
|
|
26
39
|
}
|
|
27
40
|
/**
|
|
28
41
|
* @internal
|
|
@@ -55,6 +68,8 @@ export declare class SessionRunner {
|
|
|
55
68
|
* that reports nothing about caching at all (see `SessionUsage`). */
|
|
56
69
|
private totalCachedTokens;
|
|
57
70
|
private totalCost;
|
|
71
|
+
private totalBilledCost;
|
|
72
|
+
private readonly onTurnUsage?;
|
|
58
73
|
private currentController?;
|
|
59
74
|
private currentCtx?;
|
|
60
75
|
private loopPromise?;
|
|
@@ -65,6 +80,8 @@ export declare class SessionRunner {
|
|
|
65
80
|
getStatus(): HarnessStatus;
|
|
66
81
|
/** Cumulative token usage and cost across all turns this session has run. */
|
|
67
82
|
getUsage(): SessionUsage;
|
|
83
|
+
/** Replace the totals with ones a durable host read back from storage. */
|
|
84
|
+
seedUsage(usage: SessionUsage): void;
|
|
68
85
|
/** Resolves once the queue has been drained and the runner is idle with a
|
|
69
86
|
* response available. If nothing has run yet, waits for the first turn.
|
|
70
87
|
*
|
|
@@ -80,6 +97,13 @@ export declare class SessionRunner {
|
|
|
80
97
|
kick(): void;
|
|
81
98
|
private drain;
|
|
82
99
|
private runOneTurn;
|
|
100
|
+
/**
|
|
101
|
+
* Add what the turn spent to the session's totals, before anyone waiting on the turn
|
|
102
|
+
* hears it settled — so `getUsage()` after `getAgentResponse()` includes it.
|
|
103
|
+
*/
|
|
104
|
+
private settleUsage;
|
|
105
|
+
/** A turn whose context could not be built: report it like any other failed turn. */
|
|
106
|
+
private failBeforeStart;
|
|
83
107
|
private resolveWaiters;
|
|
84
108
|
private rejectWaiters;
|
|
85
109
|
}
|
|
@@ -74,6 +74,8 @@ export class SessionRunner {
|
|
|
74
74
|
* that reports nothing about caching at all (see `SessionUsage`). */
|
|
75
75
|
totalCachedTokens;
|
|
76
76
|
totalCost = 0;
|
|
77
|
+
totalBilledCost = 0;
|
|
78
|
+
onTurnUsage;
|
|
77
79
|
currentController;
|
|
78
80
|
currentCtx;
|
|
79
81
|
loopPromise;
|
|
@@ -85,6 +87,7 @@ export class SessionRunner {
|
|
|
85
87
|
this.agentName = opts.agentName;
|
|
86
88
|
this.runTurn = opts.runTurn;
|
|
87
89
|
this.createContext = opts.createContext;
|
|
90
|
+
this.onTurnUsage = opts.onTurnUsage;
|
|
88
91
|
this.queue.subscribe(() => {
|
|
89
92
|
this.kick();
|
|
90
93
|
});
|
|
@@ -99,8 +102,17 @@ export class SessionRunner {
|
|
|
99
102
|
outputTokens: this.totalOutputTokens,
|
|
100
103
|
cachedTokens: this.totalCachedTokens,
|
|
101
104
|
cost: this.totalCost > 0 ? this.totalCost : undefined,
|
|
105
|
+
billedCost: this.totalBilledCost > 0 ? this.totalBilledCost : undefined,
|
|
102
106
|
};
|
|
103
107
|
}
|
|
108
|
+
/** Replace the totals with ones a durable host read back from storage. */
|
|
109
|
+
seedUsage(usage) {
|
|
110
|
+
this.totalInputTokens = usage.inputTokens;
|
|
111
|
+
this.totalOutputTokens = usage.outputTokens;
|
|
112
|
+
this.totalCachedTokens = usage.cachedTokens;
|
|
113
|
+
this.totalCost = usage.cost ?? 0;
|
|
114
|
+
this.totalBilledCost = usage.billedCost ?? 0;
|
|
115
|
+
}
|
|
104
116
|
/** Resolves once the queue has been drained and the runner is idle with a
|
|
105
117
|
* response available. If nothing has run yet, waits for the first turn.
|
|
106
118
|
*
|
|
@@ -182,8 +194,18 @@ export class SessionRunner {
|
|
|
182
194
|
// the harness's createContext callback receives Item[] directly and
|
|
183
195
|
// seeds the context without re-converting.
|
|
184
196
|
const items = mergeInputsToItems(messages);
|
|
185
|
-
|
|
197
|
+
let ctx;
|
|
198
|
+
try {
|
|
199
|
+
ctx = await this.createContext(items, turnId, messages);
|
|
200
|
+
}
|
|
201
|
+
catch (err) {
|
|
202
|
+
this.failBeforeStart(turnId, err);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
186
205
|
this.currentCtx = ctx;
|
|
206
|
+
// A resumed turn's context already carries what the cut-off attempt spent; only
|
|
207
|
+
// the increase belongs to this turn.
|
|
208
|
+
const start = usageOf(ctx);
|
|
187
209
|
emitFrameworkEvent({
|
|
188
210
|
broadcaster: this.broadcaster,
|
|
189
211
|
agentName: this.agentName,
|
|
@@ -211,6 +233,7 @@ export class SessionRunner {
|
|
|
211
233
|
};
|
|
212
234
|
try {
|
|
213
235
|
const text = await this.runTurn(ctx, turn, controller.signal);
|
|
236
|
+
await this.settleUsage(start, ctx);
|
|
214
237
|
const response = buildResponse(text, ctx);
|
|
215
238
|
this.lastResponse = response;
|
|
216
239
|
this.lastError = undefined;
|
|
@@ -232,6 +255,8 @@ export class SessionRunner {
|
|
|
232
255
|
}
|
|
233
256
|
}
|
|
234
257
|
catch (err) {
|
|
258
|
+
// An aborted turn still consumed whatever the model billed before the cut.
|
|
259
|
+
await this.settleUsage(start, ctx);
|
|
235
260
|
const error = err instanceof Error ? err : new Error(String(err));
|
|
236
261
|
this.lastError = error;
|
|
237
262
|
emitFrameworkEvent({
|
|
@@ -249,16 +274,6 @@ export class SessionRunner {
|
|
|
249
274
|
this.rejectWaiters(error);
|
|
250
275
|
}
|
|
251
276
|
finally {
|
|
252
|
-
// Accumulate the turn's token accounting whatever the outcome — an
|
|
253
|
-
// aborted turn still consumed whatever the model billed before the cut.
|
|
254
|
-
this.totalInputTokens += ctx.tokens.input;
|
|
255
|
-
this.totalOutputTokens += ctx.tokens.output;
|
|
256
|
-
// Only ever leave `undefined` behind when NO turn reported a figure —
|
|
257
|
-
// a turn that reported 0 must surface as 0, not "unreported".
|
|
258
|
-
if (ctx.tokens.cached !== undefined) {
|
|
259
|
-
this.totalCachedTokens = (this.totalCachedTokens ?? 0) + ctx.tokens.cached;
|
|
260
|
-
}
|
|
261
|
-
this.totalCost += ctx.cost;
|
|
262
277
|
this.currentCtx = undefined;
|
|
263
278
|
this.currentController = undefined;
|
|
264
279
|
this.status = {
|
|
@@ -266,6 +281,43 @@ export class SessionRunner {
|
|
|
266
281
|
};
|
|
267
282
|
}
|
|
268
283
|
}
|
|
284
|
+
/**
|
|
285
|
+
* Add what the turn spent to the session's totals, before anyone waiting on the turn
|
|
286
|
+
* hears it settled — so `getUsage()` after `getAgentResponse()` includes it.
|
|
287
|
+
*/
|
|
288
|
+
async settleUsage(start, ctx) {
|
|
289
|
+
const spent = usageSince(start, ctx);
|
|
290
|
+
this.totalInputTokens += spent.inputTokens;
|
|
291
|
+
this.totalOutputTokens += spent.outputTokens;
|
|
292
|
+
// Only ever leave `undefined` behind when NO turn reported a figure —
|
|
293
|
+
// a turn that reported 0 must surface as 0, not "unreported".
|
|
294
|
+
if (spent.cachedTokens !== undefined) {
|
|
295
|
+
this.totalCachedTokens = (this.totalCachedTokens ?? 0) + spent.cachedTokens;
|
|
296
|
+
}
|
|
297
|
+
this.totalCost += spent.cost;
|
|
298
|
+
this.totalBilledCost += spent.billedCost;
|
|
299
|
+
await this.onTurnUsage?.(spent);
|
|
300
|
+
}
|
|
301
|
+
/** A turn whose context could not be built: report it like any other failed turn. */
|
|
302
|
+
failBeforeStart(turnId, err) {
|
|
303
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
304
|
+
this.lastError = error;
|
|
305
|
+
emitFrameworkEvent({
|
|
306
|
+
broadcaster: this.broadcaster,
|
|
307
|
+
agentName: this.agentName,
|
|
308
|
+
eventType: 'turn_aborted',
|
|
309
|
+
data: {
|
|
310
|
+
turnId,
|
|
311
|
+
reason: error.message,
|
|
312
|
+
errorKind: isNoeticError(error) ? error.noeticError.kind : undefined,
|
|
313
|
+
},
|
|
314
|
+
});
|
|
315
|
+
this.rejectWaiters(error);
|
|
316
|
+
this.currentController = undefined;
|
|
317
|
+
this.status = {
|
|
318
|
+
kind: 'idle',
|
|
319
|
+
};
|
|
320
|
+
}
|
|
269
321
|
resolveWaiters(response) {
|
|
270
322
|
const pending = this.responseWaiters.splice(0, this.responseWaiters.length);
|
|
271
323
|
for (const w of pending) {
|
|
@@ -281,6 +333,25 @@ export class SessionRunner {
|
|
|
281
333
|
}
|
|
282
334
|
//#endregion
|
|
283
335
|
//#region buildResponse
|
|
336
|
+
function usageOf(ctx) {
|
|
337
|
+
return {
|
|
338
|
+
inputTokens: ctx.tokens.input,
|
|
339
|
+
outputTokens: ctx.tokens.output,
|
|
340
|
+
cachedTokens: ctx.tokens.cached,
|
|
341
|
+
cost: ctx.cost,
|
|
342
|
+
billedCost: ctx.billedCost,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
function usageSince(start, ctx) {
|
|
346
|
+
const now = usageOf(ctx);
|
|
347
|
+
return {
|
|
348
|
+
inputTokens: now.inputTokens - start.inputTokens,
|
|
349
|
+
outputTokens: now.outputTokens - start.outputTokens,
|
|
350
|
+
cachedTokens: now.cachedTokens === undefined ? undefined : now.cachedTokens - (start.cachedTokens ?? 0),
|
|
351
|
+
cost: now.cost - start.cost,
|
|
352
|
+
billedCost: now.billedCost - start.billedCost,
|
|
353
|
+
};
|
|
354
|
+
}
|
|
284
355
|
function buildResponse(text, ctx) {
|
|
285
356
|
return {
|
|
286
357
|
items: ctx.itemLog.items,
|
|
@@ -294,6 +365,7 @@ function buildResponse(text, ctx) {
|
|
|
294
365
|
cachedTokens: ctx.tokens.cached,
|
|
295
366
|
},
|
|
296
367
|
cost: ctx.cost > 0 ? ctx.cost : undefined,
|
|
368
|
+
billedCost: ctx.billedCost > 0 ? ctx.billedCost : undefined,
|
|
297
369
|
text,
|
|
298
370
|
lastLayerUsage: ctx.lastLayerUsage,
|
|
299
371
|
};
|
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
* consumers can validate workflow documents without importing core.
|
|
4
4
|
* This barrel keeps core's public and intra-core import paths unchanged.
|
|
5
5
|
*/
|
|
6
|
-
export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, OutputCodecRef, RouteSwitchWorkflowNode, RunCodeWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowGraph, WorkflowNode, WorkflowReplayKey, } from '@noetic-tools/types';
|
|
6
|
+
export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, OutputCodecRef, RouteSwitchWorkflowNode, RunCodeWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowEmitItems, WorkflowGraph, WorkflowNode, WorkflowReplayKey, } from '@noetic-tools/types';
|
|
7
7
|
export { MergeStrategy, MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDocumentSchema, WorkflowNodeSchema, walkWorkflow, workflowDepth, workflowGraph, } from '@noetic-tools/types';
|