@noetic-tools/core 5.16.1 → 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 (45) 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 +192 -23
  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 +4 -2
  9. package/dist/harness/deps/runtime.js +4 -2
  10. package/dist/harness/deps/types.d.ts +1 -1
  11. package/dist/harness/model-call.d.ts +5 -1
  12. package/dist/harness/model-call.js +107 -21
  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/harness/steer-inbox.d.ts +5 -0
  20. package/dist/harness/steer-inbox.js +45 -5
  21. package/dist/harness/thread-record.d.ts +17 -5
  22. package/dist/harness/thread-record.js +54 -4
  23. package/dist/index.d.ts +5 -1
  24. package/dist/index.js +2 -0
  25. package/dist/interpreter/execute-action.js +60 -11
  26. package/dist/interpreter/execute-control.js +1 -0
  27. package/dist/interpreter/execute-decide.js +18 -0
  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 +77 -0
  32. package/dist/runtime/drain.js +268 -0
  33. package/dist/runtime/durable/session-store.d.ts +12 -0
  34. package/dist/runtime/durable/session-store.js +16 -0
  35. package/dist/runtime/durable/spend-log.d.ts +38 -0
  36. package/dist/runtime/durable/spend-log.js +65 -0
  37. package/dist/runtime/durable/step-ledger.d.ts +6 -0
  38. package/dist/runtime/durable/step-ledger.js +3 -2
  39. package/dist/runtime/session-runner.d.ts +5 -3
  40. package/dist/runtime/session-runner.js +9 -4
  41. package/dist/until/predicates.d.ts +5 -1
  42. package/dist/until/predicates.js +12 -7
  43. package/dist/util/status-code.d.ts +5 -0
  44. package/dist/util/status-code.js +8 -0
  45. package/package.json +3 -3
@@ -264,6 +264,7 @@ export function aiCondition(opts) {
264
264
  threshold: opts.threshold,
265
265
  },
266
266
  },
267
+ _billTo: ctx,
267
268
  });
268
269
  trackUsage(ctx, {
269
270
  items: [],
@@ -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, ExecuteInput, ExecuteOptions, 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,9 +303,7 @@ 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<void>;
298
307
  getStatus(scope?: SessionScope): HarnessStatus;
299
308
  getQueueSize(scope?: SessionScope): number;
300
309
  getUsage(scope?: SessionScope): SessionUsage;
@@ -456,6 +465,9 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
456
465
  * Decoration applied *after* construction (`Object.assign`ed fields, abort
457
466
  * registration) stays the host's job: apply it to the context this returns,
458
467
  * whose `id` is already the original `executionId`.
468
+ *
469
+ * Paid calls the interrupted run left with no settled bill are held on the
470
+ * returned context (`heldCost`) and reconciled in the background.
459
471
  */
460
472
  restore(executionId: string, opts?: RestoreCheckpointOptions): Promise<Context | null>;
461
473
  /**
@@ -472,6 +484,32 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
472
484
  * behind, and nothing else enumerates them.
473
485
  */
474
486
  clearCheckpoint(executionId: string): Promise<void>;
487
+ /**
488
+ * Paid provider calls with no settled bill — cut off by a crash, a cancel, a steer,
489
+ * or a dropped connection — all of them or one execution's, each with its ceiling.
490
+ * A call still in flight in this harness is not listed. Empty without durable
491
+ * storage. See spec 23 § Paid dispatches.
492
+ * @public
493
+ */
494
+ pendingSpend(executionId?: string): Promise<PendingSpend[]>;
495
+ /**
496
+ * Price pending dispatches through the provider's generation lookup and settle
497
+ * them into usage. The provider prices a call some seconds after it ends, so this
498
+ * keeps asking for up to `patienceMs`. A dispatch with no generation id stays held.
499
+ * Runs on its own after `restore()` and whenever a call is cut off; call it again
500
+ * at any time, for example at boot.
501
+ * @public
502
+ */
503
+ reconcileSpend(opts?: ReconcileSpendOptions): Promise<SpendSettlement[]>;
504
+ /**
505
+ * Settle one pending dispatch at `assumedCost`, for a call that can never be priced.
506
+ * Resolves `undefined` when no pending dispatch has that id.
507
+ * @public
508
+ */
509
+ writeOffSpend(id: string, opts: WriteOffSpendOptions): Promise<SpendSettlement | undefined>;
510
+ private createSpend;
511
+ /** Add a settled bill to a thread's stored session. False when the thread has none. */
512
+ private chargeSession;
475
513
  /**
476
514
  * Cancel an execution: abort `ctx` and every live descendant context, then
477
515
  * run the context-layer teardown for each (spec 09, Cancellation).
@@ -490,8 +528,15 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
490
528
  * settle (up to its timeout) before that context's teardown, and step code that ignores `ctx.aborted` between `await`s runs to
491
529
  * its next boundary. Calling `cancel()` on an already-cancelled context is a
492
530
  * no-op.
493
- */
494
- cancel(ctx: Context, reason?: string): Promise<void>;
531
+ *
532
+ * With `{ drainMs }` the cancel is graceful: nothing new starts beneath
533
+ * `ctx`, model calls in flight get up to `drainMs` to finish and be charged,
534
+ * and `{name}:drain_started` / `{name}:drain_finished` report which finished
535
+ * and which were cut off. A second `cancel` during the drain cancels at once.
536
+ */
537
+ cancel(ctx: Context, options?: string | CancelOptions): Promise<void>;
538
+ /** Abort `ctx`'s tree and tear its layers down. The abort happens before the first `await`. */
539
+ private cancelNow;
495
540
  /**
496
541
  * Run the layer lifecycle's abort path for one cancelled context: wait for
497
542
  * 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, 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, spend) {
120
121
  const resolved = resolveLlmClient(config, readLlmEnv());
121
122
  if (!resolved) {
122
123
  return undefined;
@@ -127,6 +128,9 @@ function createClient(config, contextCache) {
127
128
  if (resolved.serverURL) {
128
129
  options.serverURL = resolved.serverURL;
129
130
  }
131
+ if (spend) {
132
+ options.httpClient = generationHook(spend);
133
+ }
130
134
  // A cache write costs more than a plain read, so the breakpoint only pays off
131
135
  // when something is holding the prefix still — which is what anchoring does.
132
136
  const wantsBreakpoint = contextCache?.enabled !== false;
@@ -147,7 +151,26 @@ function createClient(config, contextCache) {
147
151
  },
148
152
  });
149
153
  }
150
- function createDecisionsClient(config) {
154
+ /**
155
+ * An HTTP client that saves a paid call's generation id the moment its headers
156
+ * arrive. The SDK awaits the hook before it reads the body, so a stream cut off
157
+ * after its headers can still be priced.
158
+ *
159
+ * The agent bundles an older SDK whose `HTTPClient` class is nominally different;
160
+ * the agent calls only `request()` on it, which both versions share.
161
+ */
162
+ function generationHook(spend) {
163
+ const http = 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
+ return frameworkCast(http);
172
+ }
173
+ function createSdkClient(config) {
151
174
  const resolved = resolveLlmClient(config, readLlmEnv());
152
175
  if (!resolved) {
153
176
  return undefined;
@@ -218,8 +241,16 @@ export class AgentHarness {
218
241
  * without friend-class gymnastics. Do not access from outside core. */
219
242
  _contextLayers;
220
243
  client;
221
- /** SDK 1.x client for the decisions endpoint; the agent's client predates it. */
222
- decisionsClient;
244
+ /**
245
+ * SDK 1.x client for the endpoints the agent's client predates: decisions, model
246
+ * prices, and generation lookups.
247
+ */
248
+ sdkClient;
249
+ /**
250
+ * Paid dispatch records, present exactly when durability is on.
251
+ * @internal
252
+ */
253
+ spend;
223
254
  decideOverride;
224
255
  /** Model id → whether it answers natively as a decision model. */
225
256
  decisionModels = new Map();
@@ -243,6 +274,8 @@ export class AgentHarness {
243
274
  * {@link cancelAcpSession}, and {@link closeAcpSessions} from outside core.
244
275
  */
245
276
  acpSessions = new AcpSessionStore();
277
+ /** @internal Graceful stops in progress; the interpreter and model loop hold on them. */
278
+ drains = new Drains();
246
279
  /**
247
280
  * Snapshot of every live ACP sub-agent, for a UI that wants to show what is
248
281
  * running and let a user act on it. Read-only: a session's turns are driven
@@ -346,17 +379,18 @@ export class AgentHarness {
346
379
  this.sessionStore = this.checkpointStore
347
380
  ? createSessionStore(this.config.storage ?? createInMemoryStorage())
348
381
  : undefined;
382
+ this.spend = this.checkpointStore
383
+ ? this.createSpend(this.config.storage ?? createInMemoryStorage())
384
+ : undefined;
349
385
  this.agentGraph = opts.agentGraph;
350
386
  this.harnessTools = opts.tools ?? [];
351
387
  this._contextLayers = opts.contextLayers;
352
388
  this.callModelOverride = opts._testCallModel;
353
389
  this.client = opts._testCallModel
354
390
  ? undefined
355
- : createClient(opts.callModelDefaults, opts.contextCache);
391
+ : createClient(opts.callModelDefaults, opts.contextCache, this.spend);
356
392
  this.decideOverride = opts._testDecide;
357
- this.decisionsClient = opts._testCallModel
358
- ? undefined
359
- : createDecisionsClient(opts.callModelDefaults);
393
+ this.sdkClient = opts._testCallModel ? undefined : createSdkClient(opts.callModelDefaults);
360
394
  this.channelStore = new ChannelStore({
361
395
  onWarning: (warning) => this.recordChannelWarning(warning),
362
396
  });
@@ -422,7 +456,11 @@ export class AgentHarness {
422
456
  void session.runner.abort(INTERRUPT_REASON);
423
457
  return Promise.resolve();
424
458
  }
459
+ const steersRunningTurn = session.runner.getStatus().kind === 'generating' && isSteer(message);
425
460
  session.runner.enqueue(message);
461
+ if (steersRunningTurn) {
462
+ void session.record?.keepSteer(message);
463
+ }
426
464
  return Promise.resolve();
427
465
  }
428
466
  /** The turn's response. `items` holds final items: standard ones and the graph's declared custom items. */
@@ -457,7 +495,27 @@ export class AgentHarness {
457
495
  if (!session) {
458
496
  return;
459
497
  }
460
- await session.runner.abort(scope?.reason);
498
+ const { runner } = session;
499
+ const ctx = runner.context;
500
+ if (!ctx) {
501
+ await runner.abort(scope?.reason);
502
+ return;
503
+ }
504
+ const draining = this.drains.stop(ctx);
505
+ if (draining) {
506
+ return draining;
507
+ }
508
+ if (!scope?.drainMs) {
509
+ await runner.abort(scope?.reason);
510
+ return;
511
+ }
512
+ // The drained turn may end on its own; then the runner has moved on and
513
+ // there is nothing left to abort.
514
+ return this.drains.run(ctx, scope.drainMs, async () => {
515
+ if (runner.context === ctx) {
516
+ await runner.abort(scope.reason);
517
+ }
518
+ });
461
519
  }
462
520
  getStatus(scope) {
463
521
  const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
@@ -467,7 +525,17 @@ export class AgentHarness {
467
525
  kind: 'idle',
468
526
  };
469
527
  }
470
- return session.runner.getStatus();
528
+ const status = session.runner.getStatus();
529
+ const ctx = session.runner.context;
530
+ const drain = ctx && this.drains.covering(ctx);
531
+ if (status.kind !== 'generating' || !drain) {
532
+ return status;
533
+ }
534
+ return {
535
+ kind: 'draining',
536
+ turnId: status.turnId,
537
+ deadline: drain.deadline,
538
+ };
471
539
  }
472
540
  getQueueSize(scope) {
473
541
  const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
@@ -476,14 +544,17 @@ export class AgentHarness {
476
544
  }
477
545
  getUsage(scope) {
478
546
  const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
479
- const session = this.sessions.get(threadId);
480
- if (!session) {
481
- return {
482
- inputTokens: 0,
483
- outputTokens: 0,
484
- };
485
- }
486
- return session.runner.getUsage();
547
+ const usage = this.sessions.get(threadId)?.runner.getUsage() ?? {
548
+ inputTokens: 0,
549
+ outputTokens: 0,
550
+ };
551
+ const heldCost = this.spend?.heldFor(threadId) ?? 0;
552
+ return heldCost > 0
553
+ ? {
554
+ ...usage,
555
+ heldCost,
556
+ }
557
+ : usage;
487
558
  }
488
559
  seedSessionHistory(threadId, items) {
489
560
  const session = this.getOrCreateSession(threadId);
@@ -505,7 +576,7 @@ export class AgentHarness {
505
576
  // Save a turn's items as the thread's history for the next turn.
506
577
  const keepHistory = async (ctx) => {
507
578
  if (record) {
508
- await record.end(ctx, ctx.itemLog.items);
579
+ await record.end(ctx, ctx.itemLog.items, session.runner.queue.peekAll().map((message) => message.id));
509
580
  return;
510
581
  }
511
582
  session.accumulatedItems = [
@@ -554,6 +625,14 @@ export class AgentHarness {
554
625
  ...this.harnessTools,
555
626
  ]);
556
627
  }
628
+ // Steers the last harness accepted but never applied go back in the queue;
629
+ // ones already in the conversation are skipped when offered.
630
+ for (const steer of (await record?.steers()) ?? []) {
631
+ const queued = session.runner.queue.peekAll().some((m) => m.id === steer.id);
632
+ if (!queued && !messageIds.includes(steer.id)) {
633
+ session.runner.queue.enqueue(steer);
634
+ }
635
+ }
557
636
  await record?.begin(ctx, messageIds);
558
637
  return ctx;
559
638
  },
@@ -634,6 +713,7 @@ export class AgentHarness {
634
713
  streamIdleTimeoutMs: DEFAULT_STREAM_IDLE_TIMEOUT_MS,
635
714
  harness: this,
636
715
  traceExporter: this.traceExporter,
716
+ spend: this.spend,
637
717
  }).callModel(request);
638
718
  }
639
719
  //#endregion
@@ -643,9 +723,10 @@ export class AgentHarness {
643
723
  return this.decideOverride(request);
644
724
  }
645
725
  return callDecide(request, {
646
- client: this.decisionsClient,
726
+ client: this.sdkClient,
647
727
  callModel: (r) => this.callModel(r),
648
728
  nativeModels: this.decisionModels,
729
+ spend: this.spend,
649
730
  });
650
731
  }
651
732
  async notifyDecision(layers, record, ctx) {
@@ -1130,6 +1211,9 @@ export class AgentHarness {
1130
1211
  * Decoration applied *after* construction (`Object.assign`ed fields, abort
1131
1212
  * registration) stays the host's job: apply it to the context this returns,
1132
1213
  * whose `id` is already the original `executionId`.
1214
+ *
1215
+ * Paid calls the interrupted run left with no settled bill are held on the
1216
+ * returned context (`heldCost`) and reconciled in the background.
1133
1217
  */
1134
1218
  async restore(executionId, opts) {
1135
1219
  const restored = await restoreFromCheckpoint(this, executionId, opts);
@@ -1139,6 +1223,7 @@ export class AgentHarness {
1139
1223
  if (restored.fromSnapshot) {
1140
1224
  this.restoredExecutions.add(executionId);
1141
1225
  }
1226
+ await this.spend?.adopt(restored.ctx);
1142
1227
  return restored.ctx;
1143
1228
  }
1144
1229
  /**
@@ -1158,6 +1243,66 @@ export class AgentHarness {
1158
1243
  return clearCheckpoint(this, executionId);
1159
1244
  }
1160
1245
  //#endregion
1246
+ //#region Spend
1247
+ /**
1248
+ * Paid provider calls with no settled bill — cut off by a crash, a cancel, a steer,
1249
+ * or a dropped connection — all of them or one execution's, each with its ceiling.
1250
+ * A call still in flight in this harness is not listed. Empty without durable
1251
+ * storage. See spec 23 § Paid dispatches.
1252
+ * @public
1253
+ */
1254
+ async pendingSpend(executionId) {
1255
+ return (await this.spend?.pending(executionId)) ?? [];
1256
+ }
1257
+ /**
1258
+ * Price pending dispatches through the provider's generation lookup and settle
1259
+ * them into usage. The provider prices a call some seconds after it ends, so this
1260
+ * keeps asking for up to `patienceMs`. A dispatch with no generation id stays held.
1261
+ * Runs on its own after `restore()` and whenever a call is cut off; call it again
1262
+ * at any time, for example at boot.
1263
+ * @public
1264
+ */
1265
+ async reconcileSpend(opts) {
1266
+ return (await this.spend?.reconcile(opts)) ?? [];
1267
+ }
1268
+ /**
1269
+ * Settle one pending dispatch at `assumedCost`, for a call that can never be priced.
1270
+ * Resolves `undefined` when no pending dispatch has that id.
1271
+ * @public
1272
+ */
1273
+ async writeOffSpend(id, opts) {
1274
+ return this.spend?.writeOff(id, opts);
1275
+ }
1276
+ createSpend(storage) {
1277
+ return new Spend({
1278
+ agentName: this.config.name,
1279
+ log: createSpendLog(storage),
1280
+ client: () => this.sdkClient,
1281
+ liveRoot: (executionId) => this.liveRoots.get(executionId)?.ctx,
1282
+ chargeSession: (threadId, charge) => this.chargeSession(threadId, charge),
1283
+ sessionBroadcaster: (threadId) => this.sessions.get(threadId)?.runner.broadcaster,
1284
+ });
1285
+ }
1286
+ /** Add a settled bill to a thread's stored session. False when the thread has none. */
1287
+ async chargeSession(threadId, charge) {
1288
+ if (!(await this.sessionStore?.load(threadId))) {
1289
+ return false;
1290
+ }
1291
+ // The live session's own record, when there is one, so the two writes queue in order.
1292
+ const record = this.sessions.get(threadId)?.record ?? this.threadRecord(threadId);
1293
+ if (!record) {
1294
+ return false;
1295
+ }
1296
+ const usage = await record.addUsage({
1297
+ inputTokens: charge.inputTokens,
1298
+ outputTokens: charge.outputTokens,
1299
+ cost: charge.cost ?? 0,
1300
+ billedCost: charge.billedCost ?? charge.cost ?? 0,
1301
+ });
1302
+ this.sessions.get(threadId)?.runner.seedUsage(usage);
1303
+ return true;
1304
+ }
1305
+ //#endregion
1161
1306
  /**
1162
1307
  * Cancel an execution: abort `ctx` and every live descendant context, then
1163
1308
  * run the context-layer teardown for each (spec 09, Cancellation).
@@ -1176,8 +1321,32 @@ export class AgentHarness {
1176
1321
  * settle (up to its timeout) before that context's teardown, and step code that ignores `ctx.aborted` between `await`s runs to
1177
1322
  * its next boundary. Calling `cancel()` on an already-cancelled context is a
1178
1323
  * no-op.
1324
+ *
1325
+ * With `{ drainMs }` the cancel is graceful: nothing new starts beneath
1326
+ * `ctx`, model calls in flight get up to `drainMs` to finish and be charged,
1327
+ * and `{name}:drain_started` / `{name}:drain_finished` report which finished
1328
+ * and which were cut off. A second `cancel` during the drain cancels at once.
1179
1329
  */
1180
- async cancel(ctx, reason) {
1330
+ async cancel(ctx, options) {
1331
+ const { reason, drainMs } = typeof options === 'string'
1332
+ ? {
1333
+ reason: options,
1334
+ }
1335
+ : (options ?? {});
1336
+ const draining = this.drains.stop(ctx);
1337
+ if (draining) {
1338
+ return draining;
1339
+ }
1340
+ if (ctx.aborted) {
1341
+ return;
1342
+ }
1343
+ if (drainMs) {
1344
+ return this.drains.run(ctx, drainMs, () => this.cancelNow(ctx, reason));
1345
+ }
1346
+ await this.cancelNow(ctx, reason);
1347
+ }
1348
+ /** Abort `ctx`'s tree and tear its layers down. The abort happens before the first `await`. */
1349
+ async cancelNow(ctx, reason) {
1181
1350
  if (ctx.aborted) {
1182
1351
  return;
1183
1352
  }
@@ -1,5 +1,6 @@
1
1
  import type { CallModelRequest, DecideRequest, DecideResponse, LLMResponse } from '@noetic-tools/types';
2
2
  import type { OpenRouter } from '@openrouter/sdk';
3
+ import type { Spend } from './spend.js';
3
4
  /** @internal The slice of the SDK client the decide caller uses. */
4
5
  export type DecisionsClient = Pick<OpenRouter, 'alpha' | 'models'>;
5
6
  /** @internal */
@@ -8,6 +9,8 @@ export interface DecideCallerDeps {
8
9
  callModel: (request: CallModelRequest) => Promise<LLMResponse>;
9
10
  /** Per-harness cache: model id → whether it is a decision model (`undefined` while unknown). */
10
11
  nativeModels: Map<string, Promise<boolean | undefined>>;
12
+ /** Records each native call before it is sent. Absent without durable storage. */
13
+ spend?: Spend;
11
14
  }
12
15
  /**
13
16
  * Answer a decide request. Decision models (those whose OpenRouter output
@@ -1,6 +1,6 @@
1
- import { choiceValues, createMessage, DecideOutputError, extractAssistantText, frameworkCast, scoreLevels, } from '@noetic-tools/types';
1
+ import { choiceValues, createMessage, DecideOutputError, extractAssistantText, frameworkCast, SpendKind, scoreLevels, } from '@noetic-tools/types';
2
2
  import { z } from 'zod';
3
- import { statusOf } from '../util/status-code.js';
3
+ import { isErrorStatus, statusOf } from '../util/status-code.js';
4
4
  //#endregion
5
5
  //#region Public API
6
6
  /**
@@ -12,7 +12,7 @@ import { statusOf } from '../util/status-code.js';
12
12
  */
13
13
  export async function callDecide(request, deps) {
14
14
  if (deps.client && (await isDecisionModel(request.model, deps))) {
15
- return callNative(request, deps.client);
15
+ return callNative(request, deps.client, deps.spend);
16
16
  }
17
17
  return callEstimated(request, deps);
18
18
  }
@@ -54,19 +54,21 @@ async function lookupDecisionModel(model, client) {
54
54
  }
55
55
  //#endregion
56
56
  //#region Native path
57
- async function callNative(request, client) {
57
+ async function callNative(request, client, spend) {
58
58
  const questions = {};
59
59
  for (const [id, question] of Object.entries(request.questions)) {
60
60
  questions[id] = toNativeQuestion(question);
61
61
  }
62
- const response = await client.alpha.decisions.create({
63
- decisionsRequest: {
64
- model: request.model,
65
- state: toNativeState(request.instructions, request.state),
66
- questions,
67
- },
68
- }, {
69
- signal: request.signal,
62
+ const decisionsRequest = {
63
+ model: request.model,
64
+ state: toNativeState(request.instructions, request.state),
65
+ questions,
66
+ };
67
+ const response = await sendNative({
68
+ client,
69
+ decisionsRequest,
70
+ request,
71
+ spend,
70
72
  });
71
73
  const answers = {};
72
74
  for (const [id, question] of Object.entries(request.questions)) {
@@ -86,6 +88,36 @@ async function callNative(request, client) {
86
88
  cost: response.usage.cost,
87
89
  };
88
90
  }
91
+ /**
92
+ * Send one native call under a dispatch record. The provider sends the generation id
93
+ * only with the body, so a call cut off mid-request stays held at its ceiling.
94
+ */
95
+ async function sendNative({ client, decisionsRequest, request, spend, }) {
96
+ const dispatch = await spend?.open({
97
+ ctx: request._billTo,
98
+ kind: SpendKind.Decide,
99
+ model: request.model,
100
+ body: decisionsRequest,
101
+ });
102
+ try {
103
+ const response = await client.alpha.decisions.create({
104
+ decisionsRequest,
105
+ }, {
106
+ signal: request.signal,
107
+ });
108
+ await dispatch?.settle();
109
+ return response;
110
+ }
111
+ catch (e) {
112
+ if (isErrorStatus(e)) {
113
+ await dispatch?.settle();
114
+ }
115
+ throw e;
116
+ }
117
+ finally {
118
+ dispatch?.end();
119
+ }
120
+ }
89
121
  /**
90
122
  * The native APIs require `instructions` on every question, while Noetic lets a
91
123
  * boolean question carry its meaning in `criteria` alone; and TypeSafe needs
@@ -251,6 +283,7 @@ async function callEstimated(request, deps) {
251
283
  outputSchema: schema,
252
284
  signal: request.signal,
253
285
  parentSpan: request.parentSpan,
286
+ _billTo: request._billTo,
254
287
  })));
255
288
  const runs = settled.flatMap((r) => r.status === 'fulfilled'
256
289
  ? [
@@ -1,5 +1,5 @@
1
1
  export { OpenRouter } from '@openrouter/agent';
2
- export { OpenRouter as OpenRouterSdk } from '@openrouter/sdk';
2
+ export { HTTPClient, OpenRouter as OpenRouterSdk } from '@openrouter/sdk';
3
3
  export { createInMemoryFsAdapter } from '../../adapters/in-memory-fs-adapter.js';
4
4
  export { createInMemoryShellAdapter } from '../../adapters/in-memory-shell-adapter.js';
5
5
  export { createInMemorySubprocessAdapter } from '../../adapters/in-memory-subprocess-adapter.js';
@@ -1,5 +1,5 @@
1
1
  export { OpenRouter } from '@openrouter/agent';
2
- export { OpenRouter as OpenRouterSdk } from '@openrouter/sdk';
2
+ export { HTTPClient, OpenRouter as OpenRouterSdk } from '@openrouter/sdk';
3
3
  export { createInMemoryFsAdapter } from '../../adapters/in-memory-fs-adapter.js';
4
4
  export { createInMemoryShellAdapter } from '../../adapters/in-memory-shell-adapter.js';
5
5
  export { createInMemorySubprocessAdapter } from '../../adapters/in-memory-subprocess-adapter.js';
@@ -1,20 +1,22 @@
1
1
  export type { ChannelWarning } from '../../runtime/channel-store.js';
2
2
  export { ChannelStore, warnToConsole } from '../../runtime/channel-store.js';
3
- export { ContextImpl, collectContextTree, rootIdOf } from '../../runtime/context-impl.js';
3
+ export { ContextImpl, collectContextTree, laneBase, rootIdOf } from '../../runtime/context-impl.js';
4
4
  export { snapshotCwdState } from '../../runtime/cwd-helpers.js';
5
+ export { Drains } from '../../runtime/drain.js';
5
6
  export type { CheckpointStore } from '../../runtime/durable/index.js';
6
7
  export { createCheckpointStore } from '../../runtime/durable/checkpoint-store.js';
7
8
  export type { RestoreCheckpointOptions } from '../../runtime/durable/harness-checkpoints.js';
8
9
  export { captureCheckpoint, clearCheckpoint, restoreFromCheckpoint, } from '../../runtime/durable/harness-checkpoints.js';
9
10
  export type { SessionStore } from '../../runtime/durable/session-store.js';
10
11
  export { createSessionStore } from '../../runtime/durable/session-store.js';
12
+ export { createSpendLog } from '../../runtime/durable/spend-log.js';
11
13
  export type { StepLedgerEntry, StepLedgerRetention, StepLedgerStore, } from '../../runtime/durable/step-ledger.js';
12
14
  export { createStepLedgerStore, resolveStepLedgerRetention, StepLedger, } from '../../runtime/durable/step-ledger.js';
13
15
  export type { EventBroadcaster } from '../../runtime/event-broadcaster.js';
14
16
  export { createInMemoryStorage } from '../../runtime/in-memory-storage.js';
15
17
  export { customItemGates } from '../../runtime/item-gates.js';
16
18
  export type { QueuedMessage, SessionCtxExtension } from '../../runtime/message-queue.js';
17
- export { INTERRUPT_REASON } from '../../runtime/message-queue.js';
19
+ export { INTERRUPT_REASON, isSteer } from '../../runtime/message-queue.js';
18
20
  export type { TurnUsage } from '../../runtime/session-runner.js';
19
21
  export { SessionRunner } from '../../runtime/session-runner.js';
20
22
  export { buildItemStream, filterReasoningStream, filterTextStream, } from '../../runtime/session-streams.js';
@@ -1,12 +1,14 @@
1
1
  export { ChannelStore, warnToConsole } from '../../runtime/channel-store.js';
2
- export { ContextImpl, collectContextTree, rootIdOf } from '../../runtime/context-impl.js';
2
+ export { ContextImpl, collectContextTree, laneBase, rootIdOf } from '../../runtime/context-impl.js';
3
3
  export { snapshotCwdState } from '../../runtime/cwd-helpers.js';
4
+ export { Drains } from '../../runtime/drain.js';
4
5
  export { createCheckpointStore } from '../../runtime/durable/checkpoint-store.js';
5
6
  export { captureCheckpoint, clearCheckpoint, restoreFromCheckpoint, } from '../../runtime/durable/harness-checkpoints.js';
6
7
  export { createSessionStore } from '../../runtime/durable/session-store.js';
8
+ export { createSpendLog } from '../../runtime/durable/spend-log.js';
7
9
  export { createStepLedgerStore, resolveStepLedgerRetention, StepLedger, } from '../../runtime/durable/step-ledger.js';
8
10
  export { createInMemoryStorage } from '../../runtime/in-memory-storage.js';
9
11
  export { customItemGates } from '../../runtime/item-gates.js';
10
- export { INTERRUPT_REASON } from '../../runtime/message-queue.js';
12
+ export { INTERRUPT_REASON, isSteer } from '../../runtime/message-queue.js';
11
13
  export { SessionRunner } from '../../runtime/session-runner.js';
12
14
  export { buildItemStream, filterReasoningStream, filterTextStream, } from '../../runtime/session-streams.js';
@@ -1,4 +1,4 @@
1
1
  export type { ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, ExecutionContext, ProjectionPolicy, StorageAdapter, } from '@noetic-tools/context';
2
- export type { AcpKeepAlive, AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, Channel, ChannelHandle, Context, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, ItemSchemaExtensions, LLMResponse, LlmProviderConfig, OnSteerParams, RecallLayerOutput, RecallOptions, SessionScope, SessionUsage, ShellAdapter, Span, SteeringDecision, SteerVerdict, Step, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, } from '@noetic-tools/types';
2
+ export type { AcpKeepAlive, AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, ItemSchemaExtensions, LLMResponse, LlmProviderConfig, OnSteerParams, PendingSpend, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, UsageCharge, WriteOffSpendOptions, } from '@noetic-tools/types';
3
3
  export { SteeringAction } from '@noetic-tools/types';
4
4
  export type { ZodType } from 'zod';