@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
@@ -17,7 +17,8 @@ const EMPTY_USAGE = {
17
17
  * @internal
18
18
  * One thread's stored session. Turns call `history` → `resume` → `begin` → `end`; a
19
19
  * turn that throws never reaches `end`, so its record stays for a re-delivery of the
20
- * same messages to resume. Operations run one at a time, in call order, so a read
20
+ * same messages to resume. Steers sent into a running turn are kept with `keepSteer`
21
+ * until `end`. Operations run one at a time, in call order, so a read
21
22
  * never overtakes a write issued before it.
22
23
  */
23
24
  export class ThreadRecord {
@@ -60,10 +61,45 @@ export class ThreadRecord {
60
61
  return undefined;
61
62
  });
62
63
  }
63
- /** Record the turn about to run on `ctx`, before any of it runs. */
64
+ /** Keep a steer sent into the running turn, so a resumed turn still applies it. */
65
+ keepSteer(message) {
66
+ if (message.deliveryMode !== 'between-rounds' && message.deliveryMode !== 'next-item') {
67
+ return Promise.resolve();
68
+ }
69
+ const steer = {
70
+ id: message.id,
71
+ input: message.input,
72
+ deliveryMode: message.deliveryMode,
73
+ enqueuedAt: message.enqueuedAt,
74
+ };
75
+ return this.update((record) => ({
76
+ ...record,
77
+ steers: [
78
+ ...(record.steers ?? []).filter((kept) => kept.id !== steer.id),
79
+ steer,
80
+ ],
81
+ }));
82
+ }
83
+ /** The steers kept for the turn in flight, as queue messages. */
84
+ steers() {
85
+ return this.run(async () => ((await this.load())?.steers ?? []).map((steer) => ({
86
+ id: steer.id,
87
+ input: this.parseInput(steer.input),
88
+ deliveryMode: steer.deliveryMode,
89
+ // Options carry live objects (layers, state) that storage cannot hold; a
90
+ // steer applied mid-turn never reads them.
91
+ options: {},
92
+ enqueuedAt: steer.enqueuedAt,
93
+ })));
94
+ }
95
+ /**
96
+ * Record the turn about to run on `ctx`, before any of it runs. Kept steers it
97
+ * delivers as input stop being steers: re-delivering the turn re-sends them.
98
+ */
64
99
  begin(ctx, messageIds) {
65
100
  return this.update((record) => ({
66
101
  ...record,
102
+ steers: record.steers?.filter((steer) => !messageIds.includes(steer.id)),
67
103
  turn: {
68
104
  executionId: ctx.id,
69
105
  messageIds: [
@@ -72,10 +108,14 @@ export class ThreadRecord {
72
108
  },
73
109
  }));
74
110
  }
75
- /** The turn on `ctx` finished: store the history it left and drop its checkpoint. */
76
- async end(ctx, history) {
111
+ /**
112
+ * The turn on `ctx` finished: store the history it left and drop its checkpoint.
113
+ * Only steers still queued are kept; the rest were applied or dropped.
114
+ */
115
+ async end(ctx, history, queuedIds) {
77
116
  await this.update((record) => ({
78
117
  ...withoutTurn(record),
118
+ steers: record.steers?.filter((steer) => queuedIds.includes(steer.id)),
79
119
  items: [
80
120
  ...history,
81
121
  ],
@@ -113,6 +153,16 @@ export class ThreadRecord {
113
153
  console.warn(`AgentHarness: failed to persist session "${this.threadId}":`, error instanceof Error ? error.message : String(error));
114
154
  }
115
155
  }
156
+ parseInput(input) {
157
+ if (typeof input === 'string') {
158
+ return input;
159
+ }
160
+ return this.host.parseItems(Array.isArray(input)
161
+ ? input
162
+ : [
163
+ input,
164
+ ]);
165
+ }
116
166
  load() {
117
167
  return this.host.store.load(this.threadId);
118
168
  }
package/dist/index.d.ts CHANGED
@@ -164,7 +164,11 @@ export type { LayerTraceSpan, Span, TraceExporter } from '@noetic-tools/types';
164
164
  /** @public */
165
165
  export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent, StreamingItem, } from '@noetic-tools/types';
166
166
  /** @public */
167
- export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, ExecuteOptions, HarnessJudgmentContract, HarnessStatus, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, SessionScope, SessionUsage, } from '@noetic-tools/types';
167
+ export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, ExecuteOptions, HarnessJudgmentContract, HarnessStatus, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, SessionScope, SessionUsage, } from '@noetic-tools/types';
168
+ /** @public */
169
+ export type { PendingSpend, ReconcileSpendOptions, SpendSettlement, WriteOffSpendOptions, } from '@noetic-tools/types';
170
+ /** @public */
171
+ export { SpendKind } from '@noetic-tools/types';
168
172
  /** @public */
169
173
  export type { AfterModelCallParams, AfterModelCallResult, ApproveToolCallParams, BeforeToolCallParams, BeforeToolCallResult, LedgerEntry, OnSteerParams, OnSteerResult, Steer, SteeringConfig, SteeringDecision, SteeringRule, SteeringState, SteerVerdict, ToolApprover, } from '@noetic-tools/types';
170
174
  /** @public */
package/dist/index.js CHANGED
@@ -107,6 +107,8 @@ export { ChannelSnapshotSchema, CheckpointSchemaVersion, CheckpointSnapshotSchem
107
107
  /** @public */
108
108
  export { Slot } from '@noetic-tools/context';
109
109
  /** @public */
110
+ export { SpendKind } from '@noetic-tools/types';
111
+ /** @public */
110
112
  export { LedgerEntryKind, SteerAction, SteeringAction, SteerPoint } from '@noetic-tools/types';
111
113
  /** @public */
112
114
  export { BooleanQuestionSchema, ChoiceQuestionSchema, choiceValues, DECIDE_LIMITS, DecideOutputError, DecideQuestionSchema, DecideQuestionsSchema, routeOutcomes, ScoreQuestionSchema, scoreLevels, } from '@noetic-tools/types';
@@ -496,7 +496,6 @@ function recordTurnOutcome(params) {
496
496
  }
497
497
  export async function executeCallModel(step, input, ctx, layers) {
498
498
  const baseCtx = frameworkCast(ctx);
499
- const hasLayers = layers !== undefined && layers.length > 0;
500
499
  // Resolve lazy step fields up-front. Function-form getters run once per
501
500
  // step execution with the live context, so `ctx.harness.config.params`,
502
501
  // `ctx.unifiedTools`, and context layer state are all visible at resolution.
@@ -534,7 +533,47 @@ export async function executeCallModel(step, input, ctx, layers) {
534
533
  policy,
535
534
  systemPromptTokens,
536
535
  });
537
- const recallQuery = typeof input === 'string' ? input : '';
536
+ const scope = {
537
+ step,
538
+ ctx: baseCtx,
539
+ layers,
540
+ resolvedModel,
541
+ resolvedInstructions,
542
+ resolvedTools,
543
+ allowedToolNames,
544
+ outputSchema,
545
+ serverToolSpecs,
546
+ viewPolicy,
547
+ budgetMap,
548
+ systemPromptTokens,
549
+ };
550
+ let recallQuery = typeof input === 'string' ? input : '';
551
+ let rerender = rerenderRequests;
552
+ // A steer whose layers asked for recall ends the call early. Recall runs again over
553
+ // the conversation the steer joined, and the call goes on from there.
554
+ for (;;) {
555
+ const response = await callOnFreshView(scope, recallQuery, rerender);
556
+ if (!response.recall) {
557
+ return finalizeStepOutput({
558
+ stepId: step.id,
559
+ emit: step.emit,
560
+ outputCodec,
561
+ outputSchema,
562
+ lastText: extractAssistantText(response.items),
563
+ ctx: baseCtx,
564
+ });
565
+ }
566
+ recallQuery = lastInputText(response.items) ?? recallQuery;
567
+ rerender = [];
568
+ }
569
+ }
570
+ /**
571
+ * Recall, build the view, and call the model on it, retrying on steering guidance.
572
+ * Returns the response once it is recorded on the context and stored by the layers.
573
+ */
574
+ async function callOnFreshView(scope, recallQuery, rerenderRequests) {
575
+ const { step, ctx: baseCtx, layers, resolvedModel, resolvedInstructions, resolvedTools, allowedToolNames, outputSchema, serverToolSpecs, viewPolicy, budgetMap, systemPromptTokens, } = scope;
576
+ const hasLayers = layers !== undefined && layers.length > 0;
538
577
  const slotOf = new Map((layers ?? []).map((l) => [
539
578
  l.id,
540
579
  l.slot,
@@ -668,15 +707,7 @@ export async function executeCallModel(step, input, ctx, layers) {
668
707
  if (hasLayers) {
669
708
  await baseCtx.harness.storeLayers(layers, response, baseCtx);
670
709
  }
671
- const lastText = extractAssistantText(response.items);
672
- return finalizeStepOutput({
673
- stepId: step.id,
674
- emit: step.emit,
675
- outputCodec,
676
- outputSchema,
677
- lastText,
678
- ctx: baseCtx,
679
- });
710
+ return response;
680
711
  }
681
712
  // Safety net: the loop above always returns or throws within the body.
682
713
  // This throw is unreachable but protects against future refactors that
@@ -688,6 +719,24 @@ export async function executeCallModel(step, input, ctx, layers) {
688
719
  retriesExhausted: true,
689
720
  });
690
721
  }
722
+ /** The text of the last input message — the steer that asked for recall. */
723
+ function lastInputText(items) {
724
+ for (const item of [
725
+ ...items,
726
+ ].reverse()) {
727
+ if (item.type !== 'message' || item.role === 'assistant') {
728
+ continue;
729
+ }
730
+ const text = item.content
731
+ .map((part) => ('text' in part && typeof part.text === 'string' ? part.text : ''))
732
+ .join('\n')
733
+ .trim();
734
+ if (text.length > 0) {
735
+ return text;
736
+ }
737
+ }
738
+ return undefined;
739
+ }
691
740
  function isContextConfig(value) {
692
741
  return typeof value === 'object' && value !== null && 'layers' in value;
693
742
  }
@@ -594,6 +594,7 @@ export async function executeLoop(step, input, ctx, executeStep) {
594
594
  },
595
595
  elapsed: Date.now() - startTime,
596
596
  cost: ctx.cost,
597
+ heldCost: ctx.heldCost,
597
598
  lastOutput: output,
598
599
  lastText,
599
600
  history: [
@@ -1,6 +1,7 @@
1
1
  import { choiceValues, DecideOutputError, frameworkCast, hashString, NoeticConfigError, NoeticErrorImpl, scoreLevels, } from '@noetic-tools/types';
2
2
  import { z } from 'zod';
3
3
  import { GenAI, NoeticAttr } from '../observability/genai-attributes.js';
4
+ import { drainsOf } from '../runtime/drain.js';
4
5
  import { allocateBudgets, assembleView, DECISION_PROJECTION, exportSpans, laneBase, } from './action-deps.js';
5
6
  import { resolveLazy } from './execute-action.js';
6
7
  import { trackUsage } from './message-helpers.js';
@@ -42,6 +43,7 @@ export async function executeDecide(step, input, ctx, layers) {
42
43
  samples: step.samples,
43
44
  signal: isContextImpl(baseCtx) ? baseCtx.abortSignal : undefined,
44
45
  parentSpan: span,
46
+ _billTo: baseCtx,
45
47
  });
46
48
  trackUsage(baseCtx, {
47
49
  items: [],
@@ -158,6 +160,19 @@ async function resolveModel(step, ctx) {
158
160
  }
159
161
  /** Provider errors arrive raw; give them the step's id and a Noetic kind. */
160
162
  async function askHarness(step, ctx, request) {
163
+ const drains = drainsOf(ctx);
164
+ // A graceful stop that began while the step prepared its request sends nothing.
165
+ await drains?.hold(ctx);
166
+ if (ctx.aborted) {
167
+ throw new NoeticErrorImpl({
168
+ kind: 'cancelled',
169
+ reason: ctx.abortReason ?? 'context aborted',
170
+ });
171
+ }
172
+ const finished = drains?.track(ctx, {
173
+ kind: 'decide',
174
+ model: request.model,
175
+ });
161
176
  try {
162
177
  return await ctx.harness.decide(request);
163
178
  }
@@ -180,6 +195,9 @@ async function askHarness(step, ctx, request) {
180
195
  }
181
196
  throw wrapModelError(e, step.id, ctx);
182
197
  }
198
+ finally {
199
+ finished?.();
200
+ }
183
201
  }
184
202
  //#endregion
185
203
  //#region State
@@ -1,6 +1,7 @@
1
1
  import { frameworkCast, NoeticErrorImpl } from '@noetic-tools/types';
2
2
  import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
3
3
  import { ContextImpl } from '../runtime/context-impl.js';
4
+ import { drainsOf } from '../runtime/drain.js';
4
5
  import { REPLAY_KEY_PREFIX } from '../runtime/durable/step-ledger.js';
5
6
  import { DetachedHandleImpl } from '../util/detached-handle.js';
6
7
  import { allowCustomItems, appendReplayed, beginEmitItems, emitStepItems } from './emit-items.js';
@@ -252,6 +253,9 @@ async function recordToLedger(opts) {
252
253
  */
253
254
  export async function execute(step, input, ctx) {
254
255
  const baseCtx = frameworkCast(ctx);
256
+ // Under a graceful stop no new step starts: it waits here until the tree is cancelled.
257
+ const drains = drainsOf(baseCtx);
258
+ await drains?.hold(baseCtx);
255
259
  // Depth guard — classified as step_failed (not budget_exceeded) because depth
256
260
  // is a structural safety limit, not a user-configurable budget field.
257
261
  if (ctx.depth >= MAX_DEPTH) {
@@ -393,6 +397,7 @@ export async function execute(step, input, ctx) {
393
397
  }
394
398
  catch (error) {
395
399
  lane?.releaseDispatch();
400
+ drains?.release(frameworkCast(stepCtx));
396
401
  throw error;
397
402
  }
398
403
  finally {
@@ -427,5 +432,9 @@ export async function execute(step, input, ctx) {
427
432
  * step produced. A no-op unless the harness has a CheckpointStore, and a failing
428
433
  * save is logged rather than thrown — durability must never fail a good step. */
429
434
  await baseCtx.checkpoint();
435
+ // The model calls the step made stop counting as in flight only now, once
436
+ // they are charged and the step recorded. A call a failed record leaves
437
+ // behind is released when an enclosing step ends.
438
+ drains?.release(frameworkCast(stepCtx));
430
439
  return result;
431
440
  }
@@ -19,6 +19,7 @@ export declare class ContextImpl implements Context<ContextData> {
19
19
  tokens: TokenUsage;
20
20
  cost: number;
21
21
  billedCost: number;
22
+ heldCost: number;
22
23
  state: unknown;
23
24
  readonly parent: Context<ContextData> | null;
24
25
  readonly usageParent: Context<ContextData> | null;
@@ -51,6 +51,7 @@ export class ContextImpl {
51
51
  };
52
52
  cost = 0;
53
53
  billedCost = 0;
54
+ heldCost = 0;
54
55
  state;
55
56
  parent;
56
57
  usageParent;
@@ -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