@noetic-tools/core 5.13.0 → 6.0.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.
@@ -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
- const ctx = this.createContext(items, turnId, messages);
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
  };
@@ -14,8 +14,13 @@ import { z } from 'zod';
14
14
  * layer id, so a v1 snapshot carries state under ids no current layer reads
15
15
  * — restoring it would silently drop that state. There is no migration;
16
16
  * discard via `CheckpointStore.clear()` and start fresh.
17
+ * - v2 → v3: `itemLog` holds the log as it stood when the run in flight began, not
18
+ * at the moment of capture, and `occurrences` records the dispatch counts from that
19
+ * same moment. A resumed run replays its recorded steps, which put their items
20
+ * back; a v2 log already holds them, so restoring it would duplicate history. No
21
+ * migration — discard and start fresh.
17
22
  */
18
- export declare const CheckpointSchemaVersion = 2;
23
+ export declare const CheckpointSchemaVersion = 3;
19
24
  /**
20
25
  * @public
21
26
  * One entry in the execution frontier — a pointer to a step currently in
@@ -60,8 +65,9 @@ export declare const PendingAskUserSnapshotSchema: z.ZodObject<{
60
65
  export type PendingAskUserSnapshot = z.infer<typeof PendingAskUserSnapshotSchema>;
61
66
  /**
62
67
  * @public
63
- * Item log state captured in a snapshot. We store the ordered list of items
64
- * directly — the `ItemLogImpl` is append-only so the list is its own cursor.
68
+ * Item log state captured in a snapshot: the log as it stood when the run in
69
+ * flight began, or the live log when no run is in flight. The steps a resumed run
70
+ * replays put the rest back, from the items the step ledger recorded for each.
65
71
  *
66
72
  * Items are carried as `unknown` here and re-parsed on restore via the
67
73
  * harness's `ItemSchemaRegistry`, which is the same gate production traffic
@@ -99,7 +105,7 @@ export type ChannelSnapshot = z.infer<typeof ChannelSnapshotSchema>;
99
105
  * instead of producing a silently corrupt restored context.
100
106
  */
101
107
  export declare const CheckpointSnapshotSchema: z.ZodObject<{
102
- schemaVersion: z.ZodLiteral<2>;
108
+ schemaVersion: z.ZodLiteral<3>;
103
109
  executionId: z.ZodString;
104
110
  threadId: z.ZodOptional<z.ZodString>;
105
111
  resourceId: z.ZodOptional<z.ZodString>;
@@ -121,6 +127,17 @@ export declare const CheckpointSnapshotSchema: z.ZodObject<{
121
127
  itemLog: z.ZodObject<{
122
128
  items: z.ZodArray<z.ZodUnknown>;
123
129
  }, z.core.$strip>;
130
+ occurrences: z.ZodRecord<z.ZodString, z.ZodNumber>;
131
+ state: z.ZodOptional<z.ZodUnknown>;
132
+ usage: z.ZodOptional<z.ZodObject<{
133
+ tokens: z.ZodObject<{
134
+ input: z.ZodNumber;
135
+ output: z.ZodNumber;
136
+ total: z.ZodNumber;
137
+ cached: z.ZodOptional<z.ZodNumber>;
138
+ }, z.core.$strip>;
139
+ cost: z.ZodNumber;
140
+ }, z.core.$strip>>;
124
141
  channels: z.ZodOptional<z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
125
142
  name: z.ZodString;
126
143
  mode: z.ZodLiteral<"value">;
@@ -15,8 +15,13 @@ import { z } from 'zod';
15
15
  * layer id, so a v1 snapshot carries state under ids no current layer reads
16
16
  * — restoring it would silently drop that state. There is no migration;
17
17
  * discard via `CheckpointStore.clear()` and start fresh.
18
+ * - v2 → v3: `itemLog` holds the log as it stood when the run in flight began, not
19
+ * at the moment of capture, and `occurrences` records the dispatch counts from that
20
+ * same moment. A resumed run replays its recorded steps, which put their items
21
+ * back; a v2 log already holds them, so restoring it would duplicate history. No
22
+ * migration — discard and start fresh.
18
23
  */
19
- export const CheckpointSchemaVersion = 2;
24
+ export const CheckpointSchemaVersion = 3;
20
25
  /**
21
26
  * @public
22
27
  * One entry in the execution frontier — a pointer to a step currently in
@@ -58,8 +63,9 @@ export const PendingAskUserSnapshotSchema = z.object({
58
63
  });
59
64
  /**
60
65
  * @public
61
- * Item log state captured in a snapshot. We store the ordered list of items
62
- * directly — the `ItemLogImpl` is append-only so the list is its own cursor.
66
+ * Item log state captured in a snapshot: the log as it stood when the run in
67
+ * flight began, or the live log when no run is in flight. The steps a resumed run
68
+ * replays put the rest back, from the items the step ledger recorded for each.
63
69
  *
64
70
  * Items are carried as `unknown` here and re-parsed on restore via the
65
71
  * harness's `ItemSchemaRegistry`, which is the same gate production traffic
@@ -107,6 +113,30 @@ export const CheckpointSnapshotSchema = z.object({
107
113
  cwd: CwdSnapshotSchema.nullable(),
108
114
  askUser: z.array(PendingAskUserSnapshotSchema),
109
115
  itemLog: ItemLogSnapshotSchema,
116
+ /**
117
+ * Dispatch counts per `<parent path>/<step id>`, taken at the same moment as
118
+ * `itemLog`. A restored context numbers its dispatches from here, so a resumed run
119
+ * meets its recorded steps at the paths they were recorded under, and a later run
120
+ * on the same execution does not land on an earlier run's paths.
121
+ */
122
+ occurrences: z.record(z.string(), z.number()),
123
+ /**
124
+ * The execution's `ctx.state` at capture time. Absent when the state does not survive
125
+ * JSON encoding, in which case restore keeps whatever state the host passes.
126
+ */
127
+ state: z.unknown().optional(),
128
+ /** Tokens and cost the execution had spent at capture time, so budgets carry over. */
129
+ usage: z
130
+ .object({
131
+ tokens: z.object({
132
+ input: z.number(),
133
+ output: z.number(),
134
+ total: z.number(),
135
+ cached: z.number().optional(),
136
+ }),
137
+ cost: z.number(),
138
+ })
139
+ .optional(),
110
140
  /**
111
141
  * Stored state of every channel the execution used. Optional so snapshots
112
142
  * written before channels were captured still load (they restore with no
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.13.0",
3
+ "version": "6.0.0",
4
4
  "type": "module",
5
5
  "description": "Step primitives, interpreter, runtime, and context layer contract for Noetic agents.",
6
6
  "license": "Apache-2.0",
@@ -69,7 +69,7 @@
69
69
  },
70
70
  "dependencies": {
71
71
  "@noetic-tools/context": "^1.9.0",
72
- "@noetic-tools/types": "^3.11.0",
72
+ "@noetic-tools/types": "^4.0.0",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "jsonata": "2.2.2",