@noetic-tools/core 5.17.0 → 5.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/conditions/conditions.js +1 -0
  2. package/dist/harness/agent-harness.d.ts +54 -9
  3. package/dist/harness/agent-harness.js +179 -22
  4. package/dist/harness/decide-call.d.ts +3 -0
  5. package/dist/harness/decide-call.js +45 -12
  6. package/dist/harness/deps/adapters.d.ts +1 -1
  7. package/dist/harness/deps/adapters.js +1 -1
  8. package/dist/harness/deps/runtime.d.ts +3 -1
  9. package/dist/harness/deps/runtime.js +3 -1
  10. package/dist/harness/deps/types.d.ts +1 -1
  11. package/dist/harness/model-call.d.ts +3 -0
  12. package/dist/harness/model-call.js +87 -17
  13. package/dist/harness/model-price.d.ts +35 -0
  14. package/dist/harness/model-price.js +81 -0
  15. package/dist/harness/model-rounds.d.ts +2 -0
  16. package/dist/harness/model-rounds.js +5 -1
  17. package/dist/harness/spend.d.ts +138 -0
  18. package/dist/harness/spend.js +494 -0
  19. package/dist/index.d.ts +5 -1
  20. package/dist/index.js +2 -0
  21. package/dist/interpreter/execute-control.js +1 -0
  22. package/dist/interpreter/execute-decide.js +18 -0
  23. package/dist/interpreter/execute.js +9 -0
  24. package/dist/runtime/context-impl.d.ts +1 -0
  25. package/dist/runtime/context-impl.js +1 -0
  26. package/dist/runtime/drain.d.ts +77 -0
  27. package/dist/runtime/drain.js +268 -0
  28. package/dist/runtime/durable/spend-log.d.ts +38 -0
  29. package/dist/runtime/durable/spend-log.js +65 -0
  30. package/dist/runtime/durable/step-ledger.d.ts +6 -0
  31. package/dist/runtime/durable/step-ledger.js +3 -2
  32. package/dist/runtime/session-runner.d.ts +5 -3
  33. package/dist/runtime/session-runner.js +9 -4
  34. package/dist/until/predicates.d.ts +5 -1
  35. package/dist/until/predicates.js +12 -7
  36. package/dist/util/status-code.d.ts +5 -0
  37. package/dist/util/status-code.js +8 -0
  38. package/package.json +2 -2
@@ -0,0 +1,77 @@
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
+ }
15
+ /**
16
+ * @internal The dispatch record of a tracked call. Read when a drain reports, so a
17
+ * generation id saved after dispatch still shows.
18
+ */
19
+ export interface DrainRecord {
20
+ readonly id: string;
21
+ readonly generationId?: string;
22
+ }
23
+ type DrainCallInfo = Omit<DrainCall, 'executionId' | 'dispatchId' | 'generationId'>;
24
+ /** @internal Why a drain ended. */
25
+ export type DrainEnd = 'settled' | 'deadline' | 'stopped';
26
+ /**
27
+ * @internal
28
+ *
29
+ * Graceful stops for one harness. A drain on a context holds back new steps,
30
+ * model rounds and tool calls anywhere beneath it, lets the provider calls
31
+ * already in flight finish, then stops the tree: when nothing is left in
32
+ * flight, at its deadline, or when a second stop cuts it short.
33
+ *
34
+ * A call counts as in flight from dispatch until its caller reaches the next
35
+ * hold or step end, not merely until its response arrives: the response
36
+ * still has to be charged to the context and the step recorded, and stopping
37
+ * the tree before then would lose both.
38
+ */
39
+ export declare class Drains {
40
+ private readonly calls;
41
+ private readonly active;
42
+ /**
43
+ * Note a provider call about to be dispatched on `ctx` under `record`. Call the
44
+ * returned function once its response is in (or it failed).
45
+ */
46
+ track(ctx: Context | undefined, info: DrainCallInfo, record?: DrainRecord): () => void;
47
+ /**
48
+ * The dispatch gate. Under a drain, release `ctx`'s finished calls and wait
49
+ * until a drain over it stops the tree; the caller then sees `ctx.aborted`.
50
+ */
51
+ hold(ctx: Context | undefined): Promise<void>;
52
+ /**
53
+ * The step running on `ctx` ended, or reached a hold: the finished calls it
54
+ * made are charged and recorded. Calls a concurrent dispatch on the same
55
+ * context made stay in flight until that dispatch ends.
56
+ */
57
+ release(ctx: Context): void;
58
+ /** The deadline of the drain on `ctx` or one of its ancestors, if one is running. */
59
+ covering(ctx: Context): {
60
+ readonly deadline: number;
61
+ } | undefined;
62
+ /**
63
+ * Drain `ctx` for up to `ms`, then run `stop`, which must abort the tree
64
+ * before its first `await`: held steps wake as soon as it is called.
65
+ */
66
+ run(ctx: Context, ms: number, stop: () => Promise<void>): Promise<void>;
67
+ /**
68
+ * Cut short the drain on `ctx`, if one is running, and return the promise
69
+ * of its stop. A second cancel cancels at once.
70
+ */
71
+ stop(ctx: Context): Promise<void> | undefined;
72
+ private finish;
73
+ private settleIfIdle;
74
+ }
75
+ /** The harness's drains, when `ctx` runs on a harness that has them. */
76
+ export declare function drainsOf(ctx: Context | undefined): Drains | undefined;
77
+ export {};
@@ -0,0 +1,268 @@
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 (or 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 () => {
42
+ call.done = true;
43
+ // Kept until a hold or step end releases it only while a drain may be
44
+ // waiting on it; otherwise nothing will ever release it.
45
+ if (this.active.size === 0) {
46
+ this.calls.delete(call);
47
+ }
48
+ };
49
+ }
50
+ /**
51
+ * The dispatch gate. Under a drain, release `ctx`'s finished calls and wait
52
+ * until a drain over it stops the tree; the caller then sees `ctx.aborted`.
53
+ */
54
+ async hold(ctx) {
55
+ if (!ctx || this.active.size === 0 || ctx.aborted) {
56
+ return;
57
+ }
58
+ this.release(ctx);
59
+ const over = [
60
+ ...this.active,
61
+ ]
62
+ .filter((drain) => within(ctx, drain.root))
63
+ .map((drain) => drain.over);
64
+ if (over.length > 0) {
65
+ await Promise.race(over);
66
+ }
67
+ }
68
+ /**
69
+ * The step running on `ctx` ended, or reached a hold: the finished calls it
70
+ * made are charged and recorded. Calls a concurrent dispatch on the same
71
+ * context made stay in flight until that dispatch ends.
72
+ */
73
+ release(ctx) {
74
+ if (this.active.size === 0) {
75
+ return;
76
+ }
77
+ for (const call of this.calls) {
78
+ if (call.done && inside(call.ctx, ctx)) {
79
+ this.calls.delete(call);
80
+ }
81
+ }
82
+ for (const drain of this.active) {
83
+ this.settleIfIdle(drain);
84
+ }
85
+ }
86
+ /** The deadline of the drain on `ctx` or one of its ancestors, if one is running. */
87
+ covering(ctx) {
88
+ for (const drain of this.active) {
89
+ if (within(ctx, drain.root)) {
90
+ return drain;
91
+ }
92
+ }
93
+ return undefined;
94
+ }
95
+ /**
96
+ * Drain `ctx` for up to `ms`, then run `stop`, which must abort the tree
97
+ * before its first `await`: held steps wake as soon as it is called.
98
+ */
99
+ run(ctx, ms, stop) {
100
+ const drain = openDrain(ctx, ms);
101
+ for (const call of this.calls) {
102
+ if (within(call.ctx, ctx)) {
103
+ drain.calls.add(call);
104
+ }
105
+ }
106
+ this.active.add(drain);
107
+ drain.done = this.finish(drain, stop);
108
+ return drain.done;
109
+ }
110
+ /**
111
+ * Cut short the drain on `ctx`, if one is running, and return the promise
112
+ * of its stop. A second cancel cancels at once.
113
+ */
114
+ stop(ctx) {
115
+ for (const drain of this.active) {
116
+ if (drain.root.id === ctx.id) {
117
+ drain.end('stopped');
118
+ return drain.done;
119
+ }
120
+ }
121
+ return undefined;
122
+ }
123
+ async finish(drain, stop) {
124
+ emit(drain.root, 'drain_started', {
125
+ executionId: drain.root.id,
126
+ deadline: drain.deadline,
127
+ inFlight: [
128
+ ...drain.calls,
129
+ ].map(report),
130
+ });
131
+ this.settleIfIdle(drain);
132
+ const reason = await drain.ended;
133
+ this.active.delete(drain);
134
+ if (this.active.size === 0) {
135
+ for (const call of this.calls) {
136
+ if (call.done) {
137
+ this.calls.delete(call);
138
+ }
139
+ }
140
+ }
141
+ const calls = [
142
+ ...drain.calls,
143
+ ];
144
+ emit(drain.root, 'drain_finished', {
145
+ executionId: drain.root.id,
146
+ reason,
147
+ durationMs: Date.now() - drain.startedAt,
148
+ finished: calls.filter((call) => call.done).map(report),
149
+ cutOff: calls.filter((call) => !call.done).map(report),
150
+ });
151
+ const stopping = stop();
152
+ drain.wake();
153
+ await stopping;
154
+ }
155
+ settleIfIdle(drain) {
156
+ for (const call of this.calls) {
157
+ if (within(call.ctx, drain.root)) {
158
+ return;
159
+ }
160
+ }
161
+ drain.end('settled');
162
+ }
163
+ }
164
+ /** The harness's drains, when `ctx` runs on a harness that has them. */
165
+ export function drainsOf(ctx) {
166
+ const harness = ctx?.harness;
167
+ if (!harness || !('drains' in harness)) {
168
+ return undefined;
169
+ }
170
+ return harness.drains instanceof Drains ? harness.drains : undefined;
171
+ }
172
+ //#endregion
173
+ //#region Helpers
174
+ /** Timers round longer delays down to 1 ms; the longest a timer can wait. */
175
+ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
176
+ function openDrain(root, ms) {
177
+ const startedAt = Date.now();
178
+ let end = () => { };
179
+ const ended = new Promise((resolve) => {
180
+ end = resolve;
181
+ });
182
+ let wake = () => { };
183
+ const over = new Promise((resolve) => {
184
+ wake = resolve;
185
+ });
186
+ const timer = setTimeout(() => end('deadline'), Math.min(ms, MAX_TIMEOUT_MS));
187
+ // Someone else aborting the tree ends the wait: there is nothing left to drain into.
188
+ const signal = root instanceof ContextImpl ? root.abortSignal : undefined;
189
+ const onAbort = () => end('stopped');
190
+ signal?.addEventListener('abort', onAbort, {
191
+ once: true,
192
+ });
193
+ void ended.then(() => {
194
+ clearTimeout(timer);
195
+ signal?.removeEventListener('abort', onAbort);
196
+ });
197
+ return {
198
+ root,
199
+ startedAt,
200
+ deadline: startedAt + ms,
201
+ calls: new Set(),
202
+ end,
203
+ ended,
204
+ over,
205
+ wake,
206
+ };
207
+ }
208
+ function report(call) {
209
+ const { record } = call;
210
+ return {
211
+ ...call.info,
212
+ executionId: call.ctx.id,
213
+ ...(record
214
+ ? {
215
+ dispatchId: record.id,
216
+ }
217
+ : {}),
218
+ ...(record?.generationId
219
+ ? {
220
+ generationId: record.generationId,
221
+ }
222
+ : {}),
223
+ };
224
+ }
225
+ /** Whether `ctx` is `root` or runs beneath it. Lanes share their context's id. */
226
+ function within(ctx, root) {
227
+ let node = ctx;
228
+ while (node) {
229
+ if (node.id === root.id) {
230
+ return true;
231
+ }
232
+ node = node.parent;
233
+ }
234
+ return false;
235
+ }
236
+ /**
237
+ * Whether `ctx` runs within the dispatch `step` is the lane of: beneath its
238
+ * context, or on that context under its execution path. Lanes of one context
239
+ * share its id, so the path is what tells concurrent dispatches apart.
240
+ */
241
+ function inside(ctx, step) {
242
+ for (let node = ctx; node; node = node.parent) {
243
+ if (node.id === step.id) {
244
+ return under(pathOf(node), pathOf(step));
245
+ }
246
+ }
247
+ return false;
248
+ }
249
+ function pathOf(ctx) {
250
+ return ctx instanceof ContextImpl ? ctx.currentPath() : '';
251
+ }
252
+ /** Whether `path` is `base` or a path beneath it (`/step#n` or `[i]` segments). */
253
+ function under(path, base) {
254
+ if (!path.startsWith(base)) {
255
+ return false;
256
+ }
257
+ const next = path[base.length];
258
+ return next === undefined || next === '/' || next === '[';
259
+ }
260
+ function emit(ctx, eventType, data) {
261
+ emitFrameworkEvent({
262
+ broadcaster: getBroadcaster(ctx),
263
+ agentName: ctx.harness.config.name,
264
+ eventType,
265
+ data,
266
+ });
267
+ }
268
+ //#endregion
@@ -0,0 +1,38 @@
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
+ /** @internal */
30
+ export interface SpendLog {
31
+ put(record: DispatchRecord): Promise<void>;
32
+ get(id: string): Promise<DispatchRecord | undefined>;
33
+ remove(id: string): Promise<void>;
34
+ /** Every record, oldest first. Unreadable rows are skipped. */
35
+ list(): Promise<DispatchRecord[]>;
36
+ }
37
+ /** @internal */
38
+ export declare function createSpendLog(storage: StorageAdapter): SpendLog;
@@ -0,0 +1,65 @@
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 createSpendLog(storage) {
31
+ return {
32
+ put: async (record) => {
33
+ await storage.set(keyOf(record.id), record);
34
+ },
35
+ get: async (id) => parse(await storage.get(keyOf(id))),
36
+ remove: async (id) => {
37
+ await storage.delete(keyOf(id));
38
+ },
39
+ list: async () => {
40
+ const keys = await storage.list(SPEND_PREFIX);
41
+ const raws = await storageGetMany(storage, keys);
42
+ const records = [];
43
+ for (const [key, raw] of raws) {
44
+ const record = parse(raw);
45
+ if (!record) {
46
+ console.warn(`SpendLog: skipping unreadable dispatch record "${key}"`);
47
+ continue;
48
+ }
49
+ records.push(record);
50
+ }
51
+ return records.sort((a, b) => a.sentAt.localeCompare(b.sentAt));
52
+ },
53
+ };
54
+ }
55
+ function keyOf(id) {
56
+ return `${SPEND_PREFIX}${id}`;
57
+ }
58
+ function parse(raw) {
59
+ if (raw === null || raw === undefined) {
60
+ return undefined;
61
+ }
62
+ const parsed = DispatchRecordSchema.safeParse(raw);
63
+ return parsed.success ? parsed.data : undefined;
64
+ }
65
+ //#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
  /**
@@ -126,13 +126,14 @@ export function hashStepInput(input) {
126
126
  catch {
127
127
  return undefined;
128
128
  }
129
- return cyrb53(json ?? 'undefined');
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 cyrb53(text) {
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++) {
@@ -40,7 +40,7 @@ export interface SessionRunnerOpts {
40
40
  /**
41
41
  * @internal
42
42
  *
43
- * Per-thread runner. Drains the MessageQueue and drives turns on the shared
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 drain loop if not already running. Safe to call many times. */
101
+ /** Start the queue loop if not already running. Safe to call many times. */
100
102
  kick(): void;
101
- private drain;
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
@@ -16,7 +16,7 @@ function mergeInputsToItems(messages) {
16
16
  /**
17
17
  * @internal
18
18
  *
19
- * Per-thread runner. Drains the MessageQueue and drives turns on the shared
19
+ * Per-thread runner. Works through the MessageQueue and drives turns on the shared
20
20
  * session broadcaster. Emits `turn_started` / `turn_completed` /
21
21
  * `inbox_injected` framework events so consumers can correlate queued
22
22
  * messages with the turn that delivered them.
@@ -67,6 +67,10 @@ export class SessionRunner {
67
67
  getStatus() {
68
68
  return this.status;
69
69
  }
70
+ /** The running turn's context, if a turn is running. */
71
+ get context() {
72
+ return this.currentCtx;
73
+ }
70
74
  /** Queue a message. A steer that arrives mid-turn is announced first, so
71
75
  * `steer_accepted` always precedes the `inbox_injected` that applies it. */
72
76
  enqueue(message) {
@@ -144,7 +148,7 @@ export class SessionRunner {
144
148
  // observe it via the broadcaster / lastError, not the abort() return.
145
149
  });
146
150
  }
147
- /** Start the drain loop if not already running. Safe to call many times. */
151
+ /** Start the queue loop if not already running. Safe to call many times. */
148
152
  kick() {
149
153
  if (this.loopPromise) {
150
154
  return;
@@ -152,7 +156,7 @@ export class SessionRunner {
152
156
  if (this.queue.size === 0) {
153
157
  return;
154
158
  }
155
- this.loopPromise = this.drain().finally(() => {
159
+ this.loopPromise = this.runQueue().finally(() => {
156
160
  this.loopPromise = undefined;
157
161
  // If messages arrived during finally, run again.
158
162
  if (this.queue.size > 0) {
@@ -160,7 +164,7 @@ export class SessionRunner {
160
164
  }
161
165
  });
162
166
  }
163
- async drain() {
167
+ async runQueue() {
164
168
  while (this.queue.size > 0) {
165
169
  const messages = this.queue.drainAll();
166
170
  if (messages.length === 0) {
@@ -355,6 +359,7 @@ function buildResponse(text, ctx) {
355
359
  },
356
360
  cost: ctx.cost > 0 ? ctx.cost : undefined,
357
361
  billedCost: ctx.billedCost > 0 ? ctx.billedCost : undefined,
362
+ heldCost: ctx.heldCost > 0 ? ctx.heldCost : undefined,
358
363
  text,
359
364
  lastLayerUsage: ctx.lastLayerUsage,
360
365
  };
@@ -24,7 +24,11 @@ export interface ConvergeConfig {
24
24
  export declare const until: {
25
25
  /** Stops the loop after `n` steps. @public */
26
26
  maxSteps(n: number): Until;
27
- /** Stops the loop when accumulated cost reaches `usd`. @public */
27
+ /**
28
+ * Stops the loop when accumulated cost, plus spend held for cut-off calls with no
29
+ * settled bill, reaches `usd`. Counting the hold keeps a resumed run from spending
30
+ * what its cut-off attempt may already have spent. @public
31
+ */
28
32
  maxCost(usd: number): Until;
29
33
  /** Stops the loop when elapsed time reaches `ms` milliseconds. @public */
30
34
  maxDuration(ms: number): Until;
@@ -14,14 +14,19 @@ export const until = {
14
14
  reason: snap.stepCount >= n ? `Reached max steps (${n})` : undefined,
15
15
  });
16
16
  },
17
- /** Stops the loop when accumulated cost reaches `usd`. @public */
17
+ /**
18
+ * Stops the loop when accumulated cost, plus spend held for cut-off calls with no
19
+ * settled bill, reaches `usd`. Counting the hold keeps a resumed run from spending
20
+ * what its cut-off attempt may already have spent. @public
21
+ */
18
22
  maxCost(usd) {
19
- return (snap) => ({
20
- stop: snap.cost >= usd,
21
- reason: snap.cost >= usd
22
- ? `Cost $${snap.cost.toFixed(2)} exceeded budget $${usd.toFixed(2)}`
23
- : undefined,
24
- });
23
+ return (snap) => {
24
+ const spent = snap.cost + (snap.heldCost ?? 0);
25
+ return {
26
+ stop: spent >= usd,
27
+ reason: spent >= usd ? `Cost $${spent.toFixed(2)} exceeded budget $${usd.toFixed(2)}` : undefined,
28
+ };
29
+ };
25
30
  },
26
31
  /** Stops the loop when elapsed time reaches `ms` milliseconds. @public */
27
32
  maxDuration(ms) {
@@ -1,2 +1,7 @@
1
1
  /** The HTTP status an SDK error carries, when it carries one. */
2
2
  export declare function statusOf(e: unknown): number | undefined;
3
+ /**
4
+ * Whether the provider answered with an error status, so it generated and billed
5
+ * nothing. A 2xx whose body failed to parse also carries a status, but was billed.
6
+ */
7
+ export declare function isErrorStatus(e: unknown): boolean;
@@ -5,3 +5,11 @@ export function statusOf(e) {
5
5
  }
6
6
  return typeof e.statusCode === 'number' ? e.statusCode : undefined;
7
7
  }
8
+ /**
9
+ * Whether the provider answered with an error status, so it generated and billed
10
+ * nothing. A 2xx whose body failed to parse also carries a status, but was billed.
11
+ */
12
+ export function isErrorStatus(e) {
13
+ const status = statusOf(e);
14
+ return status !== undefined && status >= 400;
15
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.17.0",
3
+ "version": "5.18.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.11.0",
72
- "@noetic-tools/types": "^3.15.0",
72
+ "@noetic-tools/types": "^3.16.0",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "jsonata": "2.2.2",