@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.
Files changed (45) hide show
  1. package/dist/adapters/openrouter.d.ts +7 -0
  2. package/dist/adapters/openrouter.js +23 -0
  3. package/dist/conditions/conditions.js +3 -0
  4. package/dist/harness/agent-harness.d.ts +63 -9
  5. package/dist/harness/agent-harness.js +222 -22
  6. package/dist/harness/call-spend.d.ts +34 -0
  7. package/dist/harness/call-spend.js +125 -0
  8. package/dist/harness/decide-call.d.ts +3 -0
  9. package/dist/harness/decide-call.js +51 -12
  10. package/dist/harness/deps/adapters.d.ts +1 -1
  11. package/dist/harness/deps/adapters.js +1 -1
  12. package/dist/harness/deps/runtime.d.ts +3 -1
  13. package/dist/harness/deps/runtime.js +3 -1
  14. package/dist/harness/deps/types.d.ts +1 -1
  15. package/dist/harness/model-call.d.ts +3 -0
  16. package/dist/harness/model-call.js +123 -66
  17. package/dist/harness/model-price.d.ts +51 -0
  18. package/dist/harness/model-price.js +158 -0
  19. package/dist/harness/model-rounds.d.ts +13 -0
  20. package/dist/harness/model-rounds.js +42 -2
  21. package/dist/harness/spend.d.ts +144 -0
  22. package/dist/harness/spend.js +534 -0
  23. package/dist/index.d.ts +5 -1
  24. package/dist/index.js +2 -0
  25. package/dist/interpreter/execute-action.js +2 -0
  26. package/dist/interpreter/execute-control.js +1 -0
  27. package/dist/interpreter/execute-decide.js +43 -1
  28. package/dist/interpreter/execute.js +9 -0
  29. package/dist/runtime/context-impl.d.ts +1 -0
  30. package/dist/runtime/context-impl.js +1 -0
  31. package/dist/runtime/drain.d.ts +68 -0
  32. package/dist/runtime/drain.js +280 -0
  33. package/dist/runtime/durable/spend-log.d.ts +58 -0
  34. package/dist/runtime/durable/spend-log.js +133 -0
  35. package/dist/runtime/durable/step-ledger.d.ts +9 -2
  36. package/dist/runtime/durable/step-ledger.js +9 -6
  37. package/dist/runtime/session-runner.d.ts +5 -3
  38. package/dist/runtime/session-runner.js +9 -4
  39. package/dist/until/predicates.d.ts +5 -1
  40. package/dist/until/predicates.js +12 -7
  41. package/dist/util/spent.d.ts +14 -0
  42. package/dist/util/spent.js +67 -0
  43. package/dist/util/status-code.d.ts +5 -0
  44. package/dist/util/status-code.js +8 -0
  45. package/package.json +2 -2
@@ -54,6 +54,13 @@ export declare function resolveWireJsonSchema(params: {
54
54
  }): Record<string, unknown>;
55
55
  /** @internal */
56
56
  export declare function convertTools({ tools }: ConvertToolsParams): SdkTool[];
57
+ /**
58
+ * @internal
59
+ * Tools as the wire carries them, for sizing a request. The agent turns each live
60
+ * Zod input schema into JSON Schema only when it sends, so serializing `convertTools`
61
+ * output would drop every description and constraint the provider bills for.
62
+ */
63
+ export declare function toolsOnWire(tools: ReadonlyArray<SdkTool>): unknown[];
57
64
  /** @internal */
58
65
  export interface ExecuteToolCallParams {
59
66
  toolName: string;
@@ -288,6 +288,29 @@ export function convertTools({ tools }) {
288
288
  },
289
289
  }));
290
290
  }
291
+ /**
292
+ * @internal
293
+ * Tools as the wire carries them, for sizing a request. The agent turns each live
294
+ * Zod input schema into JSON Schema only when it sends, so serializing `convertTools`
295
+ * output would drop every description and constraint the provider bills for.
296
+ */
297
+ export function toolsOnWire(tools) {
298
+ return tools.map((tool) => {
299
+ if (!('function' in tool) || !isZodSchema(tool.function.inputSchema)) {
300
+ return tool;
301
+ }
302
+ return {
303
+ ...tool,
304
+ function: {
305
+ ...tool.function,
306
+ inputSchema: z.toJSONSchema(tool.function.inputSchema, {
307
+ target: 'draft-07',
308
+ unrepresentable: 'any',
309
+ }),
310
+ },
311
+ };
312
+ });
313
+ }
291
314
  function isAsyncGenerator(value) {
292
315
  if (typeof value !== 'object' || value === null) {
293
316
  return false;
@@ -1,6 +1,7 @@
1
1
  import { storageGetMany } from '@noetic-tools/context';
2
2
  import { DecideOutputError, isNoeticError, NoeticErrorImpl, trackUsage } from '@noetic-tools/types';
3
3
  import { z } from 'zod';
4
+ import { chargeSpent } from '../util/spent.js';
4
5
  import { cosineSimilarity } from './cosine-similarity.js';
5
6
  //#endregion
6
7
  //#region Helpers
@@ -264,6 +265,7 @@ export function aiCondition(opts) {
264
265
  threshold: opts.threshold,
265
266
  },
266
267
  },
268
+ _billTo: ctx,
267
269
  });
268
270
  trackUsage(ctx, {
269
271
  items: [],
@@ -292,6 +294,7 @@ async function askDecide(ctx, request) {
292
294
  return await ctx.harness.decide(request);
293
295
  }
294
296
  catch (e) {
297
+ chargeSpent(ctx, e);
295
298
  if (isNoeticError(e)) {
296
299
  throw e;
297
300
  }
@@ -3,8 +3,9 @@ import { AcpSessionStore } from '../runtime/acp-session-store.js';
3
3
  import type { LayerStateStore, RecallCache } from './deps/context.js';
4
4
  import type { DetachedSpawnOverrides } from './deps/interpreter.js';
5
5
  import type { CheckpointStore, EventBroadcaster, RestoreCheckpointOptions, StepLedgerRetention, StepLedgerStore } from './deps/runtime.js';
6
- import { ChannelStore } from './deps/runtime.js';
7
- import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, Channel, ChannelHandle, Context, ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, LLMResponse, LlmProviderConfig, OnSteerParams, ProjectionPolicy, RecallLayerOutput, RecallOptions, SessionScope, SessionUsage, ShellAdapter, Span, SteeringDecision, SteerVerdict, Step, StorageAdapter, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, ZodType } from './deps/types.js';
6
+ import { ChannelStore, Drains } from './deps/runtime.js';
7
+ import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, DrainReport, ExecuteInput, ExecuteOptions, ExecutionScope, ExecutionStatus, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, LLMResponse, LlmProviderConfig, OnSteerParams, PendingSpend, ProjectionPolicy, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StorageAdapter, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, WriteOffSpendOptions, ZodType } from './deps/types.js';
8
+ import { Spend } from './spend.js';
8
9
  export { createStreamIdleWatchdog } from './model-call.js';
9
10
  /**
10
11
  * Storage-scoped environment configuration for `AgentHarness`.
@@ -187,8 +188,16 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
187
188
  * without friend-class gymnastics. Do not access from outside core. */
188
189
  readonly _contextLayers?: ContextLayer[];
189
190
  private readonly client?;
190
- /** SDK 1.x client for the decisions endpoint; the agent's client predates it. */
191
- private readonly decisionsClient?;
191
+ /**
192
+ * SDK 1.x client for the endpoints the agent's client predates: decisions, model
193
+ * prices, and generation lookups.
194
+ */
195
+ private readonly sdkClient?;
196
+ /**
197
+ * Paid dispatch records, present exactly when durability is on.
198
+ * @internal
199
+ */
200
+ readonly spend?: Spend;
192
201
  private readonly decideOverride?;
193
202
  /** Model id → whether it answers natively as a decision model. */
194
203
  private readonly decisionModels;
@@ -212,6 +221,8 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
212
221
  * {@link cancelAcpSession}, and {@link closeAcpSessions} from outside core.
213
222
  */
214
223
  readonly acpSessions: AcpSessionStore;
224
+ /** @internal Graceful stops in progress; the interpreter and model loop hold on them. */
225
+ readonly drains: Drains;
215
226
  /**
216
227
  * Snapshot of every live ACP sub-agent, for a UI that wants to show what is
217
228
  * running and let a user act on it. Read-only: a session's turns are driven
@@ -292,10 +303,14 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
292
303
  getReasoningStream(scope?: SessionScope): AsyncIterable<string>;
293
304
  /** Every event raw, including each declared custom item's `custom_item_event`. */
294
305
  getFullStream(scope?: SessionScope): AsyncIterable<StreamEvent | CustomItemStreamEvent<DeclaredItems<TItem>>>;
295
- abort(scope?: SessionScope & {
296
- reason?: string;
297
- }): Promise<void>;
306
+ abort(scope?: SessionScope & CancelOptions): Promise<DrainReport | undefined>;
307
+ getStatus(scope: ExecutionScope): ExecutionStatus;
298
308
  getStatus(scope?: SessionScope): HarnessStatus;
309
+ /**
310
+ * A `run()` execution's state, read from its live root context. Only a root
311
+ * context's outermost run registers, so a context nothing runs on reads idle.
312
+ */
313
+ private executionStatus;
299
314
  getQueueSize(scope?: SessionScope): number;
300
315
  getUsage(scope?: SessionScope): SessionUsage;
301
316
  seedSessionHistory(threadId: string, items: ReadonlyArray<Item>): void;
@@ -456,6 +471,9 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
456
471
  * Decoration applied *after* construction (`Object.assign`ed fields, abort
457
472
  * registration) stays the host's job: apply it to the context this returns,
458
473
  * whose `id` is already the original `executionId`.
474
+ *
475
+ * Paid calls the interrupted run left with no settled bill are held on the
476
+ * returned context (`heldCost`) and reconciled in the background.
459
477
  */
460
478
  restore(executionId: string, opts?: RestoreCheckpointOptions): Promise<Context | null>;
461
479
  /**
@@ -472,6 +490,33 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
472
490
  * behind, and nothing else enumerates them.
473
491
  */
474
492
  clearCheckpoint(executionId: string): Promise<void>;
493
+ /**
494
+ * Paid provider calls with no settled bill — cut off by a crash, a cancel, a steer,
495
+ * or a dropped connection — all of them or one execution's, each with its ceiling.
496
+ * A record that no longer reads is listed as `unreadable`, with no ceiling, until
497
+ * written off. A call still in flight in this harness is not listed. Empty without
498
+ * durable storage. See spec 23 § Paid dispatches.
499
+ * @public
500
+ */
501
+ pendingSpend(executionId?: string): Promise<PendingSpend[]>;
502
+ /**
503
+ * Price pending dispatches through the provider's generation lookup and settle
504
+ * them into usage. The provider prices a call some seconds after it ends, so this
505
+ * keeps asking for up to `patienceMs`. A dispatch with no generation id stays held.
506
+ * Runs on its own after `restore()` and whenever a call is cut off; call it again
507
+ * at any time, for example at boot.
508
+ * @public
509
+ */
510
+ reconcileSpend(opts?: ReconcileSpendOptions): Promise<SpendSettlement[]>;
511
+ /**
512
+ * Settle one pending dispatch at `assumedCost`, for a call that can never be priced,
513
+ * unreadable ones included. Resolves `undefined` when no pending dispatch has that id.
514
+ * @public
515
+ */
516
+ writeOffSpend(id: string, opts: WriteOffSpendOptions): Promise<SpendSettlement | undefined>;
517
+ private createSpend;
518
+ /** Add a settled bill to a thread's stored session. False when the thread has none. */
519
+ private chargeSession;
475
520
  /**
476
521
  * Cancel an execution: abort `ctx` and every live descendant context, then
477
522
  * run the context-layer teardown for each (spec 09, Cancellation).
@@ -490,8 +535,17 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
490
535
  * settle (up to its timeout) before that context's teardown, and step code that ignores `ctx.aborted` between `await`s runs to
491
536
  * its next boundary. Calling `cancel()` on an already-cancelled context is a
492
537
  * no-op.
493
- */
494
- cancel(ctx: Context, reason?: string): Promise<void>;
538
+ *
539
+ * With `{ drainMs }` the cancel is graceful: nothing new starts beneath
540
+ * `ctx`, model calls in flight get up to `drainMs` to finish and be charged,
541
+ * and `{name}:drain_started` / `{name}:drain_finished` report which finished
542
+ * and which were cut off. A second `cancel` during the drain cancels at once.
543
+ * Either call resolves with the drain's report, the same data as
544
+ * `drain_finished`; a cancel with no drain resolves `undefined`.
545
+ */
546
+ cancel(ctx: Context, options?: string | CancelOptions): Promise<DrainReport | undefined>;
547
+ /** Abort `ctx`'s tree and tear its layers down. The abort happens before the first `await`. */
548
+ private cancelNow;
495
549
  /**
496
550
  * Run the layer lifecycle's abort path for one cancelled context: wait for
497
551
  * its in-flight layer hooks to settle, then `onComplete` with
@@ -4,12 +4,13 @@ import { SpanImpl } from '../observability/span-impl.js';
4
4
  import { NoopExporter } from '../observability/trace-exporter.js';
5
5
  import { AcpSessionStore } from '../runtime/acp-session-store.js';
6
6
  import { callDecide } from './decide-call.js';
7
- import { createInMemoryFsAdapter, createInMemoryShellAdapter, createInMemorySubprocessAdapter, OpenRouter, OpenRouterSdk, } from './deps/adapters.js';
7
+ import { createInMemoryFsAdapter, createInMemoryShellAdapter, createInMemorySubprocessAdapter, HTTPClient, OpenRouter, OpenRouterSdk, } from './deps/adapters.js';
8
8
  import { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, initLayers, notifyDecision, onSteerLayers, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from './deps/context.js';
9
9
  import { collectAllTools, collectCustomItems, deduplicateTools, dispatchStepThroughAdapter, execute, prepareBandedView, someStep, } from './deps/interpreter.js';
10
- import { buildItemStream, ChannelStore, ContextImpl, captureCheckpoint, clearCheckpoint, collectContextTree, createCheckpointStore, createInMemoryStorage, createSessionStore, createStepLedgerStore, customItemGates, filterReasoningStream, filterTextStream, INTERRUPT_REASON, isSteer, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, warnToConsole, } from './deps/runtime.js';
10
+ import { buildItemStream, ChannelStore, ContextImpl, captureCheckpoint, clearCheckpoint, collectContextTree, createCheckpointStore, createInMemoryStorage, createSessionStore, createSpendLog, createStepLedgerStore, customItemGates, Drains, filterReasoningStream, filterTextStream, INTERRUPT_REASON, isSteer, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, warnToConsole, } from './deps/runtime.js';
11
11
  import { SteeringAction } from './deps/types.js';
12
12
  import { AgentHarnessModelCaller, noLlmProviderError } from './model-call.js';
13
+ import { DISPATCH_HEADER, GENERATION_HEADER, Spend } from './spend.js';
13
14
  import { ThreadRecord } from './thread-record.js';
14
15
  export { createStreamIdleWatchdog } from './model-call.js';
15
16
  import { buildItemSchemaRegistry } from './model-schema.js';
@@ -116,7 +117,7 @@ async function addCacheBreakpoint(request) {
116
117
  }),
117
118
  });
118
119
  }
119
- function createClient(config, contextCache) {
120
+ function createClient(config, contextCache, http) {
120
121
  const resolved = resolveLlmClient(config, readLlmEnv());
121
122
  if (!resolved) {
122
123
  return undefined;
@@ -127,6 +128,11 @@ function createClient(config, contextCache) {
127
128
  if (resolved.serverURL) {
128
129
  options.serverURL = resolved.serverURL;
129
130
  }
131
+ if (http) {
132
+ // The agent bundles an older SDK whose `HTTPClient` class is nominally different;
133
+ // the agent calls only `request()` on it, which both versions share.
134
+ options.httpClient = frameworkCast(http);
135
+ }
130
136
  // A cache write costs more than a plain read, so the breakpoint only pays off
131
137
  // when something is holding the prefix still — which is what anchoring does.
132
138
  const wantsBreakpoint = contextCache?.enabled !== false;
@@ -147,7 +153,23 @@ function createClient(config, contextCache) {
147
153
  },
148
154
  });
149
155
  }
150
- function createDecisionsClient(config) {
156
+ /**
157
+ * An HTTP client that saves a paid call's generation id the moment its headers
158
+ * arrive. The SDK awaits the hook before it reads the body, so a call cut off after
159
+ * its headers can still be priced. Both the model client and the decisions client
160
+ * send through it; requests without a dispatch header pass untouched.
161
+ */
162
+ function generationHook(spend) {
163
+ return new HTTPClient().addHook('response', async (res, req) => {
164
+ const dispatchId = req.headers.get(DISPATCH_HEADER);
165
+ const generationId = res.headers.get(GENERATION_HEADER);
166
+ // An error response is retried or refused; only a success carries the call's id.
167
+ if (res.ok && dispatchId && generationId) {
168
+ await spend.noteGeneration(dispatchId, generationId);
169
+ }
170
+ });
171
+ }
172
+ function createSdkClient(config, http) {
151
173
  const resolved = resolveLlmClient(config, readLlmEnv());
152
174
  if (!resolved) {
153
175
  return undefined;
@@ -155,6 +177,11 @@ function createDecisionsClient(config) {
155
177
  return new OpenRouterSdk({
156
178
  apiKey: resolved.apiKey,
157
179
  serverURL: resolved.serverURL,
180
+ ...(http
181
+ ? {
182
+ httpClient: http,
183
+ }
184
+ : {}),
158
185
  });
159
186
  }
160
187
  /**
@@ -218,8 +245,16 @@ export class AgentHarness {
218
245
  * without friend-class gymnastics. Do not access from outside core. */
219
246
  _contextLayers;
220
247
  client;
221
- /** SDK 1.x client for the decisions endpoint; the agent's client predates it. */
222
- decisionsClient;
248
+ /**
249
+ * SDK 1.x client for the endpoints the agent's client predates: decisions, model
250
+ * prices, and generation lookups.
251
+ */
252
+ sdkClient;
253
+ /**
254
+ * Paid dispatch records, present exactly when durability is on.
255
+ * @internal
256
+ */
257
+ spend;
223
258
  decideOverride;
224
259
  /** Model id → whether it answers natively as a decision model. */
225
260
  decisionModels = new Map();
@@ -243,6 +278,8 @@ export class AgentHarness {
243
278
  * {@link cancelAcpSession}, and {@link closeAcpSessions} from outside core.
244
279
  */
245
280
  acpSessions = new AcpSessionStore();
281
+ /** @internal Graceful stops in progress; the interpreter and model loop hold on them. */
282
+ drains = new Drains();
246
283
  /**
247
284
  * Snapshot of every live ACP sub-agent, for a UI that wants to show what is
248
285
  * running and let a user act on it. Read-only: a session's turns are driven
@@ -346,17 +383,21 @@ export class AgentHarness {
346
383
  this.sessionStore = this.checkpointStore
347
384
  ? createSessionStore(this.config.storage ?? createInMemoryStorage())
348
385
  : undefined;
386
+ this.spend = this.checkpointStore
387
+ ? this.createSpend(this.config.storage ?? createInMemoryStorage())
388
+ : undefined;
349
389
  this.agentGraph = opts.agentGraph;
350
390
  this.harnessTools = opts.tools ?? [];
351
391
  this._contextLayers = opts.contextLayers;
352
392
  this.callModelOverride = opts._testCallModel;
393
+ const http = this.spend ? generationHook(this.spend) : undefined;
353
394
  this.client = opts._testCallModel
354
395
  ? undefined
355
- : createClient(opts.callModelDefaults, opts.contextCache);
396
+ : createClient(opts.callModelDefaults, opts.contextCache, http);
356
397
  this.decideOverride = opts._testDecide;
357
- this.decisionsClient = opts._testCallModel
398
+ this.sdkClient = opts._testCallModel
358
399
  ? undefined
359
- : createDecisionsClient(opts.callModelDefaults);
400
+ : createSdkClient(opts.callModelDefaults, http);
360
401
  this.channelStore = new ChannelStore({
361
402
  onWarning: (warning) => this.recordChannelWarning(warning),
362
403
  });
@@ -459,11 +500,34 @@ export class AgentHarness {
459
500
  const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
460
501
  const session = this.sessions.get(threadId);
461
502
  if (!session) {
462
- return;
503
+ return undefined;
463
504
  }
464
- await session.runner.abort(scope?.reason);
505
+ const { runner } = session;
506
+ const ctx = runner.context;
507
+ if (!ctx) {
508
+ await runner.abort(scope?.reason);
509
+ return undefined;
510
+ }
511
+ const draining = this.drains.stop(ctx);
512
+ if (draining) {
513
+ return draining;
514
+ }
515
+ if (!scope?.drainMs) {
516
+ await runner.abort(scope?.reason);
517
+ return undefined;
518
+ }
519
+ // The drained turn may end on its own; then the runner has moved on and
520
+ // there is nothing left to abort.
521
+ return this.drains.run(ctx, scope.drainMs, async () => {
522
+ if (runner.context === ctx) {
523
+ await runner.abort(scope.reason);
524
+ }
525
+ });
465
526
  }
466
527
  getStatus(scope) {
528
+ if (scope && 'executionId' in scope) {
529
+ return this.executionStatus(scope.executionId);
530
+ }
467
531
  const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
468
532
  const session = this.sessions.get(threadId);
469
533
  if (!session) {
@@ -471,7 +535,45 @@ export class AgentHarness {
471
535
  kind: 'idle',
472
536
  };
473
537
  }
474
- return session.runner.getStatus();
538
+ const status = session.runner.getStatus();
539
+ const ctx = session.runner.context;
540
+ const drain = ctx && this.drains.covering(ctx);
541
+ if (status.kind !== 'generating' || !drain) {
542
+ return status;
543
+ }
544
+ return {
545
+ kind: 'draining',
546
+ turnId: status.turnId,
547
+ deadline: drain.deadline,
548
+ };
549
+ }
550
+ /**
551
+ * A `run()` execution's state, read from its live root context. Only a root
552
+ * context's outermost run registers, so a context nothing runs on reads idle.
553
+ */
554
+ executionStatus(executionId) {
555
+ const live = this.liveRoots.get(executionId);
556
+ if (!live) {
557
+ return {
558
+ kind: 'idle',
559
+ };
560
+ }
561
+ if (live.ctx.aborted) {
562
+ return {
563
+ kind: 'aborting',
564
+ };
565
+ }
566
+ const drain = this.drains.covering(live.ctx);
567
+ if (drain) {
568
+ return {
569
+ kind: 'draining',
570
+ deadline: drain.deadline,
571
+ };
572
+ }
573
+ return {
574
+ kind: 'generating',
575
+ startedAt: live.startedAt,
576
+ };
475
577
  }
476
578
  getQueueSize(scope) {
477
579
  const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
@@ -480,14 +582,17 @@ export class AgentHarness {
480
582
  }
481
583
  getUsage(scope) {
482
584
  const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
483
- const session = this.sessions.get(threadId);
484
- if (!session) {
485
- return {
486
- inputTokens: 0,
487
- outputTokens: 0,
488
- };
489
- }
490
- return session.runner.getUsage();
585
+ const usage = this.sessions.get(threadId)?.runner.getUsage() ?? {
586
+ inputTokens: 0,
587
+ outputTokens: 0,
588
+ };
589
+ const heldCost = this.spend?.heldFor(threadId) ?? 0;
590
+ return heldCost > 0
591
+ ? {
592
+ ...usage,
593
+ heldCost,
594
+ }
595
+ : usage;
491
596
  }
492
597
  seedSessionHistory(threadId, items) {
493
598
  const session = this.getOrCreateSession(threadId);
@@ -646,6 +751,7 @@ export class AgentHarness {
646
751
  streamIdleTimeoutMs: DEFAULT_STREAM_IDLE_TIMEOUT_MS,
647
752
  harness: this,
648
753
  traceExporter: this.traceExporter,
754
+ spend: this.spend,
649
755
  }).callModel(request);
650
756
  }
651
757
  //#endregion
@@ -655,9 +761,10 @@ export class AgentHarness {
655
761
  return this.decideOverride(request);
656
762
  }
657
763
  return callDecide(request, {
658
- client: this.decisionsClient,
764
+ client: this.sdkClient,
659
765
  callModel: (r) => this.callModel(r),
660
766
  nativeModels: this.decisionModels,
767
+ spend: this.spend,
661
768
  });
662
769
  }
663
770
  async notifyDecision(layers, record, ctx) {
@@ -724,6 +831,7 @@ export class AgentHarness {
724
831
  const entry = live ?? {
725
832
  ctx,
726
833
  depth: 0,
834
+ startedAt: Date.now(),
727
835
  failed: false,
728
836
  ready: Promise.resolve(),
729
837
  };
@@ -1142,6 +1250,9 @@ export class AgentHarness {
1142
1250
  * Decoration applied *after* construction (`Object.assign`ed fields, abort
1143
1251
  * registration) stays the host's job: apply it to the context this returns,
1144
1252
  * whose `id` is already the original `executionId`.
1253
+ *
1254
+ * Paid calls the interrupted run left with no settled bill are held on the
1255
+ * returned context (`heldCost`) and reconciled in the background.
1145
1256
  */
1146
1257
  async restore(executionId, opts) {
1147
1258
  const restored = await restoreFromCheckpoint(this, executionId, opts);
@@ -1151,6 +1262,7 @@ export class AgentHarness {
1151
1262
  if (restored.fromSnapshot) {
1152
1263
  this.restoredExecutions.add(executionId);
1153
1264
  }
1265
+ await this.spend?.adopt(restored.ctx);
1154
1266
  return restored.ctx;
1155
1267
  }
1156
1268
  /**
@@ -1170,6 +1282,67 @@ export class AgentHarness {
1170
1282
  return clearCheckpoint(this, executionId);
1171
1283
  }
1172
1284
  //#endregion
1285
+ //#region Spend
1286
+ /**
1287
+ * Paid provider calls with no settled bill — cut off by a crash, a cancel, a steer,
1288
+ * or a dropped connection — all of them or one execution's, each with its ceiling.
1289
+ * A record that no longer reads is listed as `unreadable`, with no ceiling, until
1290
+ * written off. A call still in flight in this harness is not listed. Empty without
1291
+ * durable storage. See spec 23 § Paid dispatches.
1292
+ * @public
1293
+ */
1294
+ async pendingSpend(executionId) {
1295
+ return (await this.spend?.pending(executionId)) ?? [];
1296
+ }
1297
+ /**
1298
+ * Price pending dispatches through the provider's generation lookup and settle
1299
+ * them into usage. The provider prices a call some seconds after it ends, so this
1300
+ * keeps asking for up to `patienceMs`. A dispatch with no generation id stays held.
1301
+ * Runs on its own after `restore()` and whenever a call is cut off; call it again
1302
+ * at any time, for example at boot.
1303
+ * @public
1304
+ */
1305
+ async reconcileSpend(opts) {
1306
+ return (await this.spend?.reconcile(opts)) ?? [];
1307
+ }
1308
+ /**
1309
+ * Settle one pending dispatch at `assumedCost`, for a call that can never be priced,
1310
+ * unreadable ones included. Resolves `undefined` when no pending dispatch has that id.
1311
+ * @public
1312
+ */
1313
+ async writeOffSpend(id, opts) {
1314
+ return this.spend?.writeOff(id, opts);
1315
+ }
1316
+ createSpend(storage) {
1317
+ return new Spend({
1318
+ agentName: this.config.name,
1319
+ log: createSpendLog(storage),
1320
+ client: () => this.sdkClient,
1321
+ liveRoot: (executionId) => this.liveRoots.get(executionId)?.ctx,
1322
+ chargeSession: (threadId, charge) => this.chargeSession(threadId, charge),
1323
+ sessionBroadcaster: (threadId) => this.sessions.get(threadId)?.runner.broadcaster,
1324
+ });
1325
+ }
1326
+ /** Add a settled bill to a thread's stored session. False when the thread has none. */
1327
+ async chargeSession(threadId, charge) {
1328
+ if (!(await this.sessionStore?.load(threadId))) {
1329
+ return false;
1330
+ }
1331
+ // The live session's own record, when there is one, so the two writes queue in order.
1332
+ const record = this.sessions.get(threadId)?.record ?? this.threadRecord(threadId);
1333
+ if (!record) {
1334
+ return false;
1335
+ }
1336
+ const usage = await record.addUsage({
1337
+ inputTokens: charge.inputTokens,
1338
+ outputTokens: charge.outputTokens,
1339
+ cost: charge.cost ?? 0,
1340
+ billedCost: charge.billedCost ?? charge.cost ?? 0,
1341
+ });
1342
+ this.sessions.get(threadId)?.runner.seedUsage(usage);
1343
+ return true;
1344
+ }
1345
+ //#endregion
1173
1346
  /**
1174
1347
  * Cancel an execution: abort `ctx` and every live descendant context, then
1175
1348
  * run the context-layer teardown for each (spec 09, Cancellation).
@@ -1188,8 +1361,35 @@ export class AgentHarness {
1188
1361
  * settle (up to its timeout) before that context's teardown, and step code that ignores `ctx.aborted` between `await`s runs to
1189
1362
  * its next boundary. Calling `cancel()` on an already-cancelled context is a
1190
1363
  * no-op.
1364
+ *
1365
+ * With `{ drainMs }` the cancel is graceful: nothing new starts beneath
1366
+ * `ctx`, model calls in flight get up to `drainMs` to finish and be charged,
1367
+ * and `{name}:drain_started` / `{name}:drain_finished` report which finished
1368
+ * and which were cut off. A second `cancel` during the drain cancels at once.
1369
+ * Either call resolves with the drain's report, the same data as
1370
+ * `drain_finished`; a cancel with no drain resolves `undefined`.
1191
1371
  */
1192
- async cancel(ctx, reason) {
1372
+ async cancel(ctx, options) {
1373
+ const { reason, drainMs } = typeof options === 'string'
1374
+ ? {
1375
+ reason: options,
1376
+ }
1377
+ : (options ?? {});
1378
+ const draining = this.drains.stop(ctx);
1379
+ if (draining) {
1380
+ return draining;
1381
+ }
1382
+ if (ctx.aborted) {
1383
+ return undefined;
1384
+ }
1385
+ if (drainMs) {
1386
+ return this.drains.run(ctx, drainMs, () => this.cancelNow(ctx, reason));
1387
+ }
1388
+ await this.cancelNow(ctx, reason);
1389
+ return undefined;
1390
+ }
1391
+ /** Abort `ctx`'s tree and tear its layers down. The abort happens before the first `await`. */
1392
+ async cancelNow(ctx, reason) {
1193
1393
  if (ctx.aborted) {
1194
1394
  return;
1195
1395
  }
@@ -0,0 +1,34 @@
1
+ import type { LLMResponse, RoundUsage, UsageCharge } from '@noetic-tools/types';
2
+ /** What one round used and cost. */
3
+ export interface Bill {
4
+ usage: RoundUsage;
5
+ cost: number;
6
+ }
7
+ /**
8
+ * What one model call's rounds used and cost. Every round the provider answered
9
+ * counts, including one the loop rejected and asked again: the provider billed it.
10
+ * A rejected round's bill is held and folded into the round the loop goes on from,
11
+ * so `rounds` lists the rounds the conversation kept, and `rounds[0]` still reports
12
+ * on the first view the model answered.
13
+ */
14
+ export declare class CallSpend {
15
+ private readonly rounds;
16
+ /** Bills counted since the last round the loop went on from. */
17
+ private held;
18
+ /** Count a round the provider answered, whether or not the loop keeps it. */
19
+ count(usage: RoundUsage, cost: number): void;
20
+ /**
21
+ * The loop goes on from the round just counted, or from a steered round that has
22
+ * no bill of its own. Returns its bill, held rejected rounds included, for the
23
+ * round ledger to record.
24
+ */
25
+ keep(): Bill;
26
+ /** Count a round replayed from the round ledger. */
27
+ replay({ usage, cost }: Bill): void;
28
+ totals(): Pick<LLMResponse, 'usage' | 'rounds' | 'cost' | 'billedCost'>;
29
+ /**
30
+ * What a call that throws must charge: every round paid for now. A replayed round
31
+ * was charged by the attempt that paid for it.
32
+ */
33
+ charge(): UsageCharge;
34
+ }