@noetic-tools/core 5.9.0 → 5.10.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.
@@ -15,7 +15,9 @@ export function isStepManifest(value) {
15
15
  typeof value.stepId === 'string' &&
16
16
  typeof value.executionId === 'string' &&
17
17
  typeof value.startedAt === 'string' &&
18
- isRecord(value.overrides));
18
+ isRecord(value.overrides) &&
19
+ (value.parentExecutionId === undefined || typeof value.parentExecutionId === 'string') &&
20
+ (value.metadata === undefined || isRecord(value.metadata)));
19
21
  }
20
22
  //#endregion
21
23
  //#region CRUD
@@ -25,8 +27,10 @@ export async function persistStepManifest(storage, request, handle) {
25
27
  handleId: handle.id,
26
28
  stepId: request.stepId,
27
29
  executionId: request.executionId,
30
+ parentExecutionId: request.parentExecutionId,
28
31
  serializedInput: request.serializedInput,
29
32
  overrides: request.overrides,
33
+ metadata: request.metadata,
30
34
  startedAt: handle.startedAt,
31
35
  reattachMode: 'replay',
32
36
  };
@@ -53,6 +53,7 @@ export function buildStepMetadata(request) {
53
53
  kind: 'step',
54
54
  stepId: request.stepId,
55
55
  executionId: request.executionId,
56
+ parentExecutionId: request.parentExecutionId,
56
57
  };
57
58
  }
58
59
  //#endregion
@@ -81,8 +81,12 @@ export interface InMemoryStepManifest {
81
81
  handleId: string;
82
82
  stepId: string;
83
83
  executionId: string;
84
+ /** See `StepSubprocessRequest.parentExecutionId`. */
85
+ parentExecutionId?: string;
84
86
  serializedInput: unknown;
85
87
  overrides: StepSubprocessRequest['overrides'];
88
+ /** Caller-supplied `request.metadata` tags, restored onto rehydrated handles. */
89
+ metadata?: Record<string, unknown>;
86
90
  startedAt: string;
87
91
  reattachMode: 'replay';
88
92
  }
@@ -113,10 +113,12 @@ export function createInMemorySubprocessAdapter(options = {}) {
113
113
  startedAt: manifest.startedAt,
114
114
  updatedAt: nowIso(),
115
115
  metadata: {
116
+ ...(manifest.metadata ?? {}),
116
117
  runtime: 'in-memory',
117
118
  kind: 'step',
118
119
  stepId: manifest.stepId,
119
120
  executionId: manifest.executionId,
121
+ parentExecutionId: manifest.parentExecutionId,
120
122
  reattachMode: manifest.reattachMode,
121
123
  },
122
124
  };
@@ -1,5 +1,10 @@
1
1
  import type { ContextConfig, ContextData, ContextLayer } from '@noetic-tools/context';
2
2
  import type { Step, StepReplay, StepWithContext } from '@noetic-tools/types';
3
+ export interface WithContextOpts<TContext, I, O> extends StepReplay<TContext, I> {
4
+ id: string;
5
+ child: Step<TContext, I, O>;
6
+ context: ContextConfig | ContextLayer[];
7
+ }
3
8
  /**
4
9
  * Creates a provide step that attaches context layers to its child without creating an isolated context.
5
10
  * Like React's Context.Provider — layers are available to all descendant steps.
@@ -14,8 +19,4 @@ import type { Step, StepReplay, StepWithContext } from '@noetic-tools/types';
14
19
  * @throws `NoeticConfigError` with code `MISSING_CHILD_STEP` if `child` is not provided.
15
20
  * @throws `NoeticConfigError` with code `MISSING_CONTEXT_LAYERS` if `context` is not provided.
16
21
  */
17
- export declare function withContext<TContext = ContextData, I = unknown, O = unknown>(opts: {
18
- id: string;
19
- child: Step<TContext, I, O>;
20
- context: ContextConfig | ContextLayer[];
21
- } & StepReplay<TContext, I>): StepWithContext<TContext, I, O>;
22
+ export declare function withContext<TContext = ContextData, I = unknown, O = unknown>(opts: WithContextOpts<TContext, I, O>): StepWithContext<TContext, I, O>;
@@ -1,6 +1,11 @@
1
1
  import type { ContextConfig, ContextData, ContextLayer } from '@noetic-tools/context';
2
2
  import type { Step, StepReplay, StepSpawn, SubprocessAdapter } from '@noetic-tools/types';
3
- interface SpawnOpts<TContext, I, O> extends StepReplay<TContext, I> {
3
+ /**
4
+ * Options for {@link spawn}.
5
+ *
6
+ * @public
7
+ */
8
+ export interface SpawnOpts<TContext = ContextData, I = unknown, O = unknown> extends StepReplay<TContext, I> {
4
9
  id: string;
5
10
  child: Step<TContext, I, O>;
6
11
  context?: ContextConfig | ContextLayer[];
@@ -28,4 +33,3 @@ interface SpawnOpts<TContext, I, O> extends StepReplay<TContext, I> {
28
33
  * @throws `NoeticConfigError` with code `MISSING_CHILD_STEP` if `child` is not provided.
29
34
  */
30
35
  export declare function spawn<TContext = ContextData, I = unknown, O = unknown>(opts: SpawnOpts<TContext, I, O>): StepSpawn<TContext, I, O>;
31
- export {};
@@ -94,7 +94,7 @@ export declare function runCode<TContext = ContextData, I = unknown, O = unknown
94
94
  * @param opts.instructions - Optional system prompt; eager string or `(ctx) => string | undefined` getter.
95
95
  * @param opts.tools - Optional tools; eager array or `(ctx) => Tool[] | undefined` getter.
96
96
  * @param opts.output - Optional Zod schema enabling structured output parsing.
97
- * @param opts.params - Optional model parameters (temperature, topP, maxTokens, stopSequences).
97
+ * @param opts.params - Optional model parameters (temperature, topP, maxTokens, serviceTier).
98
98
  * @returns A `StepCallModel` that can be composed into larger pipelines. The step
99
99
  * is auto-registered in the shared step registry.
100
100
  * @throws `NoeticConfigError` with code `EMPTY_STEP_ID` if `id` is empty.
@@ -78,7 +78,7 @@ export function runCode(opts) {
78
78
  * @param opts.instructions - Optional system prompt; eager string or `(ctx) => string | undefined` getter.
79
79
  * @param opts.tools - Optional tools; eager array or `(ctx) => Tool[] | undefined` getter.
80
80
  * @param opts.output - Optional Zod schema enabling structured output parsing.
81
- * @param opts.params - Optional model parameters (temperature, topP, maxTokens, stopSequences).
81
+ * @param opts.params - Optional model parameters (temperature, topP, maxTokens, serviceTier).
82
82
  * @returns A `StepCallModel` that can be composed into larger pipelines. The step
83
83
  * is auto-registered in the shared step registry.
84
84
  * @throws `NoeticConfigError` with code `EMPTY_STEP_ID` if `id` is empty.
@@ -199,15 +199,18 @@ function prepareModelRequest(request, agentName) {
199
199
  .filter(Boolean)
200
200
  .join('\n\n') || undefined;
201
201
  const broadcaster = getBroadcaster(request.ctx);
202
- const filteredTools = filterAllowedTools(request);
202
+ const allowedTools = filterAllowedTools(request) ?? [];
203
+ // Every request carries the full tool list, so the prompt-cache prefix is the
204
+ // same for every step in the tree; `toolChoice` does the narrowing. A call
205
+ // that may use no client tool sends none.
203
206
  // Client (function) tools convert to SDK tool definitions; OpenRouter server
204
207
  // tools (web_search/web_fetch) are wrapped via the SDK's `serverTool()` so
205
208
  // its convertToolsToAPIFormat accepts them — a raw `{type}` entry crashes it.
206
209
  // `parameters` keys stay camelCase: the SDK's outbound zod schema strips
207
210
  // unknown keys, so snake_case would be silently dropped.
208
- const clientSdkTools = filteredTools && filteredTools.length > 0
211
+ const clientSdkTools = request.tools && allowedTools.length > 0
209
212
  ? convertTools({
210
- tools: filteredTools,
213
+ tools: request.tools,
211
214
  })
212
215
  : [];
213
216
  const serverSdkTools = (request._serverTools ?? []).map((s) => serverTool(frameworkCast({
@@ -223,6 +226,8 @@ function prepareModelRequest(request, agentName) {
223
226
  remaining,
224
227
  broadcaster,
225
228
  sdkTools: sdkTools.length > 0 ? sdkTools : undefined,
229
+ toolChoice: clientSdkTools.length > 0 ? allowedToolsChoice(request, allowedTools) : undefined,
230
+ allowedTools,
226
231
  emitIfAllowed(eventType, data) {
227
232
  if (!shouldEmit(request.emit, eventType, data)) {
228
233
  return;
@@ -236,6 +241,33 @@ function prepareModelRequest(request, agentName) {
236
241
  },
237
242
  };
238
243
  }
244
+ /**
245
+ * Restrict the model to `allowedTools` (plus the step's server tools) with an
246
+ * `allowed_tools` choice. Unrestricted calls send none, leaving the provider
247
+ * default (`auto`).
248
+ */
249
+ function allowedToolsChoice(request, allowedTools) {
250
+ if (!request.allowedToolNames) {
251
+ return undefined;
252
+ }
253
+ return {
254
+ type: 'allowed_tools',
255
+ mode: 'auto',
256
+ tools: [
257
+ ...allowedTools.map((tool) => ({
258
+ type: 'function',
259
+ name: sanitizeToolNameForWire(tool.name),
260
+ })),
261
+ ...(request._serverTools ?? []).map((spec) => ({
262
+ type: spec.type,
263
+ })),
264
+ ],
265
+ };
266
+ }
267
+ /** Match a wire tool name against both the original and the sanitised name. */
268
+ function findTool(tools, wireName) {
269
+ return tools.find((tool) => tool.name === wireName || sanitizeToolNameForWire(tool.name) === wireName);
270
+ }
239
271
  function filterAllowedTools(request) {
240
272
  if (!request.tools) {
241
273
  return undefined;
@@ -257,12 +289,16 @@ class CallSpanCollector {
257
289
  exporter;
258
290
  parent;
259
291
  nodeId;
292
+ firstSpanAttributes;
260
293
  spans = [];
261
- constructor(harness, exporter, parent, nodeId) {
294
+ constructor(harness, exporter, parent, nodeId,
295
+ /** Stamped on the first model span only, then dropped. */
296
+ firstSpanAttributes) {
262
297
  this.harness = harness;
263
298
  this.exporter = exporter;
264
299
  this.parent = parent;
265
300
  this.nodeId = nodeId;
301
+ this.firstSpanAttributes = firstSpanAttributes;
266
302
  }
267
303
  /** Link a span back to its declared workflow node, when the call carries one. */
268
304
  stampNode(span) {
@@ -276,6 +312,10 @@ class CallSpanCollector {
276
312
  span.setAttribute(GenAI.SYSTEM, 'openrouter');
277
313
  span.setAttribute(GenAI.REQUEST_MODEL, model);
278
314
  this.stampNode(span);
315
+ for (const [key, value] of Object.entries(this.firstSpanAttributes ?? {})) {
316
+ span.setAttribute(key, value);
317
+ }
318
+ this.firstSpanAttributes = undefined;
279
319
  this.spans.push(span);
280
320
  return span;
281
321
  }
@@ -317,7 +357,7 @@ export class AgentHarnessModelCaller {
317
357
  this.opts = opts;
318
358
  }
319
359
  newSpanCollector(request) {
320
- return new CallSpanCollector(this.opts.harness, this.opts.traceExporter, request.parentSpan ?? request.ctx?.span ?? null, request.nodeId);
360
+ return new CallSpanCollector(this.opts.harness, this.opts.traceExporter, request.parentSpan ?? request.ctx?.span ?? null, request.nodeId, request.spanAttributes);
321
361
  }
322
362
  /**
323
363
  * Broadcast a framework-authored item so `getItemStream` carries it — tool
@@ -436,6 +476,7 @@ export class AgentHarnessModelCaller {
436
476
  input: modelInput,
437
477
  instructions: prepared.instructions,
438
478
  tools: prepared.sdkTools,
479
+ toolChoice: prepared.toolChoice,
439
480
  temperature: request.params?.temperature,
440
481
  maxOutputTokens: request.params?.maxTokens,
441
482
  topP: request.params?.topP,
@@ -541,6 +582,7 @@ export class AgentHarnessModelCaller {
541
582
  await this.executeToolRound({
542
583
  functionCalls,
543
584
  request,
585
+ allowedTools: prepared.allowedTools,
544
586
  allItems,
545
587
  conversationInput,
546
588
  round,
@@ -674,7 +716,7 @@ export class AgentHarnessModelCaller {
674
716
  };
675
717
  }
676
718
  async executeToolRound(params) {
677
- const { functionCalls, request, allItems, conversationInput, spans, modelSpan } = params;
719
+ const { functionCalls, request, allowedTools, allItems, conversationInput, spans, modelSpan } = params;
678
720
  params.emitIfAllowed('tool_round_started', {
679
721
  round: params.round,
680
722
  toolCount: functionCalls.length,
@@ -692,11 +734,12 @@ export class AgentHarnessModelCaller {
692
734
  if (request.signal?.aborted) {
693
735
  break;
694
736
  }
695
- const toolForCall = request.tools?.find((tool) => tool.name === fc.name || sanitizeToolNameForWire(tool.name) === fc.name);
737
+ const toolForCall = findTool(allowedTools, fc.name);
696
738
  spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false);
697
739
  await this.executeFunctionCall({
698
740
  fc,
699
741
  request,
742
+ allowedTools,
700
743
  allItems,
701
744
  conversationInput,
702
745
  emitIfAllowed: params.emitIfAllowed,
@@ -708,7 +751,7 @@ export class AgentHarnessModelCaller {
708
751
  });
709
752
  }
710
753
  async executeFunctionCall(params) {
711
- const { fc, request, allItems, conversationInput } = params;
754
+ const { fc, request, allowedTools, allItems, conversationInput } = params;
712
755
  params.emitIfAllowed('tool_call_started', {
713
756
  name: fc.name,
714
757
  callId: fc.callId,
@@ -721,6 +764,7 @@ export class AgentHarnessModelCaller {
721
764
  this.recordMalformedToolCall({
722
765
  fc,
723
766
  request,
767
+ allowedTools,
724
768
  allItems,
725
769
  conversationInput,
726
770
  emitIfAllowed: params.emitIfAllowed,
@@ -730,11 +774,11 @@ export class AgentHarnessModelCaller {
730
774
  if (!request.tools) {
731
775
  throw new Error(`executeFunctionCall invoked without tools on CallModelRequest (tool name: ${fc.name}).`);
732
776
  }
733
- const toolForCall = request.tools.find((tool) => tool.name === fc.name || sanitizeToolNameForWire(tool.name) === fc.name);
777
+ const toolForCall = findTool(allowedTools, fc.name);
734
778
  const toolResult = await executeToolCall({
735
779
  toolName: fc.name,
736
780
  args: parsedArgs,
737
- tools: request.tools,
781
+ tools: allowedTools,
738
782
  context: request.ctx,
739
783
  harness: this.opts.harness,
740
784
  layers: request.layers,
@@ -768,9 +812,9 @@ export class AgentHarnessModelCaller {
768
812
  });
769
813
  }
770
814
  recordMalformedToolCall(params) {
771
- const { fc, request, allItems, conversationInput } = params;
815
+ const { fc, request, allowedTools, allItems, conversationInput } = params;
772
816
  const errorOutput = `Error: malformed JSON in tool arguments: ${fc.arguments}`;
773
- const toolForCall = request.tools?.find((tool) => tool.name === fc.name || sanitizeToolNameForWire(tool.name) === fc.name);
817
+ const toolForCall = findTool(allowedTools, fc.name);
774
818
  // Owner-scoped result validation (see executeFunctionCall).
775
819
  const outputItem = createToolResultItem({
776
820
  output: errorOutput,
package/dist/index.d.ts CHANGED
@@ -31,8 +31,12 @@ export type { LoopConfig } from './builders/loop-builder.js';
31
31
  /** @public */
32
32
  export { loop } from './builders/loop-builder.js';
33
33
  /** @public */
34
+ export type { WithContextOpts } from './builders/provide-builder.js';
35
+ /** @public */
34
36
  export { withContext } from './builders/provide-builder.js';
35
37
  /** @public */
38
+ export type { SpawnOpts } from './builders/spawn-builder.js';
39
+ /** @public */
36
40
  export { spawn } from './builders/spawn-builder.js';
37
41
  /** @public */
38
42
  export type { CallModelOpts, InvokeToolOpts, RunCodeOpts } from './builders/step-builders.js';
@@ -1,5 +1,5 @@
1
1
  export type { LayerServeInfo, LayerStateStore } from '@noetic-tools/context';
2
- export { allocateBudgets, assembleView, churnFor, churnRate, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DECISION_PROJECTION, DEFAULT_PROJECTION, lineageKey, noteCacheOutcome, openEpoch, pin, pinKey, reanchorReason, resolveCacheConfig, resolveLayerTools, returnLayers, spawnLayers, } from '@noetic-tools/context';
2
+ export { allocateBudgets, assembleView, churnFor, churnRate, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DECISION_PROJECTION, DEFAULT_PROJECTION, disposeLayers, initLayers, lineageKey, noteCacheOutcome, openEpoch, pin, pinKey, reanchorReason, resolveCacheConfig, resolveLayerTools, returnLayers, spawnLayers, unpinLayers, } from '@noetic-tools/context';
3
3
  export type { ItemSchemaRegistry } from '@noetic-tools/types';
4
4
  export { defaultItemSchemaRegistry } from '@noetic-tools/types';
5
5
  export { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
@@ -1,4 +1,4 @@
1
- export { allocateBudgets, assembleView, churnFor, churnRate, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DECISION_PROJECTION, DEFAULT_PROJECTION, lineageKey, noteCacheOutcome, openEpoch, pin, pinKey, reanchorReason, resolveCacheConfig, resolveLayerTools, returnLayers, spawnLayers, } from '@noetic-tools/context';
1
+ export { allocateBudgets, assembleView, churnFor, churnRate, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DECISION_PROJECTION, DEFAULT_PROJECTION, disposeLayers, initLayers, lineageKey, noteCacheOutcome, openEpoch, pin, pinKey, reanchorReason, resolveCacheConfig, resolveLayerTools, returnLayers, spawnLayers, unpinLayers, } from '@noetic-tools/context';
2
2
  export { defaultItemSchemaRegistry } from '@noetic-tools/types';
3
3
  export { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
4
4
  export { ContextImpl, laneBase } from '../runtime/context-impl.js';
@@ -1,3 +1,3 @@
1
1
  export type { ContextConfig, ContextData, ContextLayer, ExecutionContext, } from '@noetic-tools/context';
2
- export type { AgentHarnessContract, CallModelRequest, Context, ContextRerenderRequest, ExecuteStepFn, FunctionCallItem, InputMessageItem, Item, LLMResponse, ProjectionPolicy, RecallLayerOutput, RetryPolicy, ServerToolSpec, StepCallModel, StepDecide, StepInvokeTool, StepMeta, StepRunCode, StepSpawn, StepWithContext, Tool, } from '@noetic-tools/types';
2
+ export type { AgentHarnessContract, CallModelRequest, Context, ContextRerenderRequest, ExecuteStepFn, FunctionCallItem, InputMessageItem, Item, LLMResponse, ProjectionPolicy, RecallLayerOutput, RetryPolicy, ServerToolSpec, StepCallModel, StepDecide, StepInvokeTool, StepMeta, StepRunCode, StepSpawn, StepWithContext, StorageAdapter, Tool, } from '@noetic-tools/types';
3
3
  export { isServerToolSpec, SteeringAction } from '@noetic-tools/types';
@@ -1,8 +1,9 @@
1
1
  /**
2
- * Spans for child contexts (`spawn` children and `inParallel` paths). A child
3
- * context carries its own span, so events its steps add to `ctx.span` (e.g.
4
- * `loop.verdict`) and the model/tool spans they open nest under the child
5
- * rather than being lost to a no-op span.
2
+ * Spans that steps open under `ctx.span`: child contexts (`spawn` children and
3
+ * `inParallel` paths) and direct `invokeTool` calls. A child context carries
4
+ * its own span, so events its steps add to `ctx.span` (e.g. `loop.verdict`)
5
+ * and the model/tool spans they open nest under the child rather than being
6
+ * lost to a no-op span.
6
7
  */
7
8
  import type { Context, Span } from '@noetic-tools/types';
8
9
  /** Opens a span named `name` under `parent.span`, stamped with the owning step id. */
@@ -1,8 +1,9 @@
1
1
  /**
2
- * Spans for child contexts (`spawn` children and `inParallel` paths). A child
3
- * context carries its own span, so events its steps add to `ctx.span` (e.g.
4
- * `loop.verdict`) and the model/tool spans they open nest under the child
5
- * rather than being lost to a no-op span.
2
+ * Spans that steps open under `ctx.span`: child contexts (`spawn` children and
3
+ * `inParallel` paths) and direct `invokeTool` calls. A child context carries
4
+ * its own span, so events its steps add to `ctx.span` (e.g. `loop.verdict`)
5
+ * and the model/tool spans they open nest under the child rather than being
6
+ * lost to a no-op span.
6
7
  */
7
8
  import { isNoeticError } from '@noetic-tools/types';
8
9
  import { NoeticAttr } from '../observability/genai-attributes.js';
@@ -1,4 +1,4 @@
1
- import type { ContextCacheConfig, ContextCacheStore, ContextLayer, EpochUsage, ExecutionContext, Item, ProjectionPolicy, RecallLayerOutput, Span } from '@noetic-tools/types';
1
+ import type { ContextCacheConfig, ContextCacheStore, ContextLayer, EpochUsage, ExecutionContext, Item, ProjectionPolicy, RecallLayerOutput } from '@noetic-tools/types';
2
2
  import type { LayerServeInfo } from './action-deps.js';
3
3
  /** What the layer bands contributed to one assembly, and how the epoch fared. */
4
4
  export interface BandedView {
@@ -41,10 +41,11 @@ interface PrepareBandedViewParams {
41
41
  */
42
42
  export declare function prepareBandedView(params: PrepareBandedViewParams): Promise<BandedView>;
43
43
  /**
44
- * Record how the view was banded on the step's span, so a slow or expensive run
45
- * can be traced back to the layer that keeps invalidating the prefix.
44
+ * How the view was banded, as span attributes for the step's first `llm.call`
45
+ * span, so a slow or expensive run can be traced back to the layer that keeps
46
+ * invalidating the prefix. `undefined` when anchoring is off.
46
47
  */
47
- export declare function stampAnchoringAttributes(span: Span | undefined, view: BandedView): void;
48
+ export declare function anchoringAttributes(view: BandedView): Record<string, string | number | boolean> | undefined;
48
49
  /** Tokens the prompt prefix was expected to have cached — what `noteCacheOutcome` judges against. */
49
50
  export declare function expectedCachedTokens(systemPromptItems: ReadonlyArray<Item>, view: BandedView): number;
50
51
  export {};
@@ -76,24 +76,27 @@ export async function prepareBandedView(params) {
76
76
  };
77
77
  }
78
78
  /**
79
- * Record how the view was banded on the step's span, so a slow or expensive run
80
- * can be traced back to the layer that keeps invalidating the prefix.
79
+ * How the view was banded, as span attributes for the step's first `llm.call`
80
+ * span, so a slow or expensive run can be traced back to the layer that keeps
81
+ * invalidating the prefix. `undefined` when anchoring is off.
81
82
  */
82
- export function stampAnchoringAttributes(span, view) {
83
- if (!span || !view.epoch) {
84
- return;
83
+ export function anchoringAttributes(view) {
84
+ if (!view.epoch) {
85
+ return undefined;
85
86
  }
86
87
  const { epoch } = view;
87
- span.setAttribute(NoeticAttr.CONTEXT_EPOCH_ID, epoch.id);
88
- span.setAttribute(NoeticAttr.CONTEXT_EPOCH_AGE, epoch.age);
89
- span.setAttribute(NoeticAttr.CONTEXT_ANCHOR_TOKENS, epoch.anchorTokens);
90
- span.setAttribute(NoeticAttr.CONTEXT_LIVE_TOKENS, epoch.liveTokens);
91
- span.setAttribute(NoeticAttr.CONTEXT_DELTA_TOKENS, epoch.deltaTokens);
88
+ const attributes = {
89
+ [NoeticAttr.CONTEXT_EPOCH_ID]: epoch.id,
90
+ [NoeticAttr.CONTEXT_EPOCH_AGE]: epoch.age,
91
+ [NoeticAttr.CONTEXT_ANCHOR_TOKENS]: epoch.anchorTokens,
92
+ [NoeticAttr.CONTEXT_LIVE_TOKENS]: epoch.liveTokens,
93
+ [NoeticAttr.CONTEXT_DELTA_TOKENS]: epoch.deltaTokens,
94
+ };
92
95
  if (epoch.reanchorReason) {
93
- span.setAttribute(NoeticAttr.CONTEXT_REANCHOR_REASON, epoch.reanchorReason);
96
+ attributes[NoeticAttr.CONTEXT_REANCHOR_REASON] = epoch.reanchorReason;
94
97
  }
95
98
  if (view.serveInfo.size === 0) {
96
- return;
99
+ return attributes;
97
100
  }
98
101
  const placements = [];
99
102
  const churn = [];
@@ -111,8 +114,9 @@ export function stampAnchoringAttributes(span, view) {
111
114
  });
112
115
  }
113
116
  // Span attributes hold only scalars, so structured values travel as JSON.
114
- span.setAttribute(NoeticAttr.CONTEXT_LAYER_PLACEMENTS, JSON.stringify(placements));
115
- span.setAttribute(NoeticAttr.CONTEXT_LAYER_CHURN, JSON.stringify(churn));
117
+ attributes[NoeticAttr.CONTEXT_LAYER_PLACEMENTS] = JSON.stringify(placements);
118
+ attributes[NoeticAttr.CONTEXT_LAYER_CHURN] = JSON.stringify(churn);
119
+ return attributes;
116
120
  }
117
121
  /** Tokens the prompt prefix was expected to have cached — what `noteCacheOutcome` judges against. */
118
122
  export function expectedCachedTokens(systemPromptItems, view) {
@@ -2,7 +2,7 @@
2
2
  * Action step handlers: run, llm, spawn, provide, tool.
3
3
  */
4
4
  import type { ItemSchemaRegistry, LayerStateStore } from './action-deps.js';
5
- import type { AgentHarnessContract, Context, ContextLayer, ExecuteStepFn, StepCallModel, StepInvokeTool, StepRunCode, StepSpawn, StepWithContext } from './action-types.js';
5
+ import type { AgentHarnessContract, Context, ContextLayer, ExecuteStepFn, StepCallModel, StepInvokeTool, StepRunCode, StepSpawn, StepWithContext, StorageAdapter } from './action-types.js';
6
6
  export declare function executeRunCode<TContext, I, O>(step: StepRunCode<TContext, I, O>, input: I, ctx: Context<TContext>): Promise<O>;
7
7
  /**
8
8
  * Resolves a `Lazy<T>` step field. If the value is a function, it is invoked
@@ -19,14 +19,34 @@ export interface ExecuteSpawnOpts {
19
19
  layerStore?: LayerStateStore;
20
20
  parentLayers?: ContextLayer[];
21
21
  itemSchemas?: ItemSchemaRegistry;
22
+ /** Id for the child context; generated when absent. */
23
+ childId?: string;
22
24
  }
23
25
  export declare function executeSpawn<TContext, I, O>(step: StepSpawn<TContext, I, O>, input: I, ctx: Context<TContext>, executeStep: ExecuteStepFn, opts?: ExecuteSpawnOpts): Promise<O>;
26
+ export interface ExecuteWithContextOpts {
27
+ /** Store holding layer state; without it the provided layers are not initialized or disposed. */
28
+ layerStore?: LayerStateStore;
29
+ /** Backing storage for layer `init`; without it `init` is skipped, as at the harness root. */
30
+ storage?: StorageAdapter;
31
+ }
24
32
  /**
25
- * Executes a provide step by attaching context layers to the current context
26
- * without creating an isolated child context.
33
+ * Executes a withContext step by attaching context layers to the current
34
+ * context without creating an isolated child context.
27
35
  *
28
- * Unlike spawn, provide does not create a new itemLog or clone state.
36
+ * Unlike spawn, withContext does not create a new itemLog or clone state.
29
37
  * Events flow through to the parent in real-time.
38
+ *
39
+ * Layers whose ids the parent does not already have are scoped to the
40
+ * boundary: their `init` runs on entry, and on exit their `dispose` runs,
41
+ * their state is dropped, and their prompt-cache pins are removed so their
42
+ * output does not replay into later model calls. A provided layer that
43
+ * overrides a parent layer of the same id shares that id's state slot, so it
44
+ * is neither initialized nor disposed here.
45
+ */
46
+ export declare function executeWithContext<TContext, I, O>(step: StepWithContext<TContext, I, O>, input: I, ctx: Context<TContext>, executeStep: ExecuteStepFn, opts?: ExecuteWithContextOpts): Promise<O>;
47
+ /**
48
+ * Runs an `invokeTool` step inside a `tool.call` span under `ctx.span`. The span
49
+ * covers validation, the steering gate, and execution, so a denied or failing
50
+ * call is traced with its error.
30
51
  */
31
- export declare function executeWithContext<TContext, I, O>(step: StepWithContext<TContext, I, O>, input: I, ctx: Context<TContext>, executeStep: ExecuteStepFn): Promise<O>;
32
52
  export declare function executeInvokeTool<TContext, I, O>(step: StepInvokeTool<TContext, I, O>, input: I, ctx: Context<TContext>, harness: AgentHarnessContract, layers?: ContextLayer[]): Promise<O>;
@@ -2,13 +2,14 @@
2
2
  * Action step handlers: run, llm, spawn, provide, tool.
3
3
  */
4
4
  import { createMessage, estimateTokens, extractAssistantText, frameworkCast, isNoeticError, isOutputCodec, NoeticConfigError, NoeticErrorImpl, validateSchema, } from '@noetic-tools/types';
5
+ import { ToolAttr } from '../observability/genai-attributes.js';
5
6
  import { emitToolUi } from '../runtime/tool-ui.js';
6
- import { allocateBudgets, assembleView, buildToolExecutionContext, ContextImpl, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DEFAULT_PROJECTION, defaultItemSchemaRegistry, emitFrameworkEvent, getBroadcaster, lineageKey, noteCacheOutcome, resolveCacheConfig, resolveLayerTools, returnLayers, shouldEmit, snapshotCwdState, spawnLayers, } from './action-deps.js';
7
+ import { allocateBudgets, assembleView, buildToolExecutionContext, ContextImpl, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DEFAULT_PROJECTION, defaultItemSchemaRegistry, disposeLayers, emitFrameworkEvent, getBroadcaster, initLayers, lineageKey, noteCacheOutcome, resolveCacheConfig, resolveLayerTools, returnLayers, shouldEmit, snapshotCwdState, spawnLayers, unpinLayers, } from './action-deps.js';
7
8
  import { isServerToolSpec, SteeringAction } from './action-types.js';
8
9
  import { openChildSpan, traceChild } from './child-span.js';
9
10
  import { cloneWithGuard } from './clone-guard.js';
10
11
  import { collectAllTools, deduplicateTools } from './collect-tools.js';
11
- import { prepareBandedView, stampAnchoringAttributes } from './context-assembly.js';
12
+ import { anchoringAttributes, prepareBandedView } from './context-assembly.js';
12
13
  import { trackUsage } from './message-helpers.js';
13
14
  import { wrapModelError } from './model-error.js';
14
15
  import { parseStructuredOutput } from './structured-output.js';
@@ -405,6 +406,7 @@ function buildModelRequest(params) {
405
406
  layers,
406
407
  nodeId: step.id,
407
408
  parentSpan: ctx.span,
409
+ spanAttributes: params.spanAttributes,
408
410
  signal,
409
411
  };
410
412
  if (params.resolvedTools) {
@@ -523,7 +525,9 @@ export async function executeCallModel(step, input, ctx, layers) {
523
525
  systemPromptItems: [],
524
526
  budgets: budgetMap,
525
527
  });
526
- stampAnchoringAttributes(baseCtx.span, banded);
528
+ // Stamped once per assembly, like the cache judgement below: a steering
529
+ // retry re-sends the same view, so only the first attempt carries them.
530
+ let spanAttributes = anchoringAttributes(banded);
527
531
  let retries = 0;
528
532
  // Guidance from a steering retry rides at the very end of the view, after the
529
533
  // live band and the supersedes, rather than wherever history happens to put it.
@@ -548,7 +552,9 @@ export async function executeCallModel(step, input, ctx, layers) {
548
552
  outputSchema,
549
553
  serverToolSpecs,
550
554
  assembledItems,
555
+ spanAttributes,
551
556
  });
557
+ spanAttributes = undefined;
552
558
  const response = await baseCtx.harness.callModel(request).catch((e) => {
553
559
  throw wrapModelError(e, step.id, baseCtx);
554
560
  });
@@ -664,7 +670,7 @@ async function collectSpawnItems({ layers, parentExecutionCtx, childExecutionCtx
664
670
  export async function executeSpawn(step, input, ctx, executeStep, opts) {
665
671
  const baseCtx = frameworkCast(ctx);
666
672
  const layers = resolveLayersForSpawn(step, opts?.parentLayers);
667
- const childId = crypto.randomUUID();
673
+ const childId = opts?.childId ?? crypto.randomUUID();
668
674
  const childExecutionCtx = contextToExecCtx(baseCtx, {
669
675
  executionId: childId,
670
676
  depth: baseCtx.depth + 1,
@@ -787,18 +793,27 @@ function mergeLayers(existing, provided) {
787
793
  ];
788
794
  }
789
795
  /**
790
- * Executes a provide step by attaching context layers to the current context
791
- * without creating an isolated child context.
796
+ * Executes a withContext step by attaching context layers to the current
797
+ * context without creating an isolated child context.
792
798
  *
793
- * Unlike spawn, provide does not create a new itemLog or clone state.
799
+ * Unlike spawn, withContext does not create a new itemLog or clone state.
794
800
  * Events flow through to the parent in real-time.
801
+ *
802
+ * Layers whose ids the parent does not already have are scoped to the
803
+ * boundary: their `init` runs on entry, and on exit their `dispose` runs,
804
+ * their state is dropped, and their prompt-cache pins are removed so their
805
+ * output does not replay into later model calls. A provided layer that
806
+ * overrides a parent layer of the same id shares that id's state slot, so it
807
+ * is neither initialized nor disposed here.
795
808
  */
796
- export async function executeWithContext(step, input, ctx, executeStep) {
809
+ export async function executeWithContext(step, input, ctx, executeStep, opts) {
797
810
  const baseCtx = frameworkCast(ctx);
798
811
  const previousLayers = baseCtx.layers;
799
812
  const previousUnifiedTools = baseCtx.unifiedTools;
800
813
  const newLayers = resolveLayers(step);
801
814
  const mergedLayers = mergeLayers(previousLayers, newLayers);
815
+ const parentIds = new Set((previousLayers ?? []).map((l) => l.id));
816
+ const scopedLayers = newLayers.filter((l) => !parentIds.has(l.id));
802
817
  // Attach layers to the current context (no isolation)
803
818
  baseCtx.layers = mergedLayers;
804
819
  // Merge new layer-provided tools into the unified tool set
@@ -811,13 +826,36 @@ export async function executeWithContext(step, input, ctx, executeStep) {
811
826
  ]);
812
827
  }
813
828
  }
829
+ const layerStore = opts?.layerStore;
830
+ const execCtx = contextToExecCtx(baseCtx);
814
831
  try {
832
+ if (layerStore && opts?.storage && scopedLayers.length > 0) {
833
+ await initLayers({
834
+ layers: scopedLayers,
835
+ ctx: execCtx,
836
+ storage: opts.storage,
837
+ store: layerStore,
838
+ });
839
+ }
815
840
  return await executeStep(step.child, input, ctx);
816
841
  }
817
842
  finally {
818
843
  // Restore previous layers and unified tools so siblings are not affected
819
844
  baseCtx.layers = previousLayers;
820
845
  baseCtx.unifiedTools = previousUnifiedTools;
846
+ if (scopedLayers.length > 0) {
847
+ if (layerStore) {
848
+ await disposeLayers({
849
+ layers: scopedLayers,
850
+ ctx: execCtx,
851
+ store: layerStore,
852
+ scoped: true,
853
+ });
854
+ }
855
+ if (baseCtx.harness.contextCache) {
856
+ unpinLayers(baseCtx.harness.contextCache, lineageKey(execCtx), scopedLayers);
857
+ }
858
+ }
821
859
  }
822
860
  }
823
861
  //#endregion
@@ -859,8 +897,19 @@ async function consumeToolGenerator(params) {
859
897
  });
860
898
  }
861
899
  }
900
+ /**
901
+ * Runs an `invokeTool` step inside a `tool.call` span under `ctx.span`. The span
902
+ * covers validation, the steering gate, and execution, so a denied or failing
903
+ * call is traced with its error.
904
+ */
862
905
  export async function executeInvokeTool(step, input, ctx, harness, layers) {
863
906
  const baseCtx = frameworkCast(ctx);
907
+ const span = openChildSpan(baseCtx, 'tool.call', step.id);
908
+ span.setAttribute(ToolAttr.NAME, step.tool.name);
909
+ span.setAttribute(ToolAttr.NEEDS_APPROVAL, step.tool.needsApproval ?? false);
910
+ return traceChild(baseCtx, span, () => runInvokeTool(step, input, baseCtx, harness, layers));
911
+ }
912
+ async function runInvokeTool(step, input, baseCtx, harness, layers) {
864
913
  const args = step.args ? Object.assign({}, input, step.args) : input;
865
914
  const parseResult = await validateSchema(step.tool.input, args);
866
915
  if (!parseResult.success) {
@@ -62,14 +62,19 @@ function resolveStepAdapter(step, ctx) {
62
62
  * dispatch semantics including parent-context inheritance, layer lifecycle,
63
63
  * and synchronous error propagation. Out-of-process adapters ignore
64
64
  * `_localExecutor` and run the step in a child runtime.
65
+ *
66
+ * `executionId` names the context the step body runs in: `ctx.id` for a
67
+ * `runCode`, the pre-allocated child id for a `spawn` (whose request then
68
+ * also names `ctx` as the parent).
65
69
  */
66
- async function dispatchViaAdapter(step, input, ctx, executor) {
70
+ async function dispatchViaAdapter(step, input, ctx, executionId, executor) {
67
71
  const adapter = resolveStepAdapter(step, ctx);
68
72
  const request = {
69
73
  kind: 'step',
70
74
  stepId: step.id,
71
75
  serializedInput: input,
72
- executionId: ctx.id,
76
+ executionId,
77
+ parentExecutionId: executionId === ctx.id ? undefined : ctx.id,
73
78
  overrides: {
74
79
  threadId: ctx.threadId,
75
80
  resourceId: ctx.resourceId,
@@ -78,7 +83,7 @@ async function dispatchViaAdapter(step, input, ctx, executor) {
78
83
  };
79
84
  const spawnPromise = adapter.spawn(request);
80
85
  const handle = new DetachedHandleImpl({
81
- id: ctx.id,
86
+ id: executionId,
82
87
  stepId: step.id,
83
88
  adapter,
84
89
  spawnPromise,
@@ -276,7 +281,7 @@ export async function execute(step, input, ctx) {
276
281
  try {
277
282
  switch (step.kind) {
278
283
  case 'runCode':
279
- result = await dispatchViaAdapter(step, input, stepCtx, () => executeRunCode(step, input, stepCtx));
284
+ result = await dispatchViaAdapter(step, input, stepCtx, stepCtx.id, () => executeRunCode(step, input, stepCtx));
280
285
  break;
281
286
  case 'callModel':
282
287
  result = await executeCallModel(step, input, stepCtx, baseCtx.layers);
@@ -301,11 +306,20 @@ export async function execute(step, input, ctx) {
301
306
  itemSchemas: baseCtx.itemSchemas,
302
307
  });
303
308
  break;
304
- case 'spawn':
305
- result = await dispatchViaAdapter(step, input, stepCtx, () => executeSpawn(step, input, stepCtx, (s, i, c) => execute(s, i, c), buildSpawnOpts(stepCtx)));
309
+ case 'spawn': {
310
+ // Allocated here so the adapter request names the child it runs.
311
+ const childId = crypto.randomUUID();
312
+ result = await dispatchViaAdapter(step, input, stepCtx, childId, () => executeSpawn(step, input, stepCtx, (s, i, c) => execute(s, i, c), {
313
+ ...buildSpawnOpts(stepCtx),
314
+ childId,
315
+ }));
306
316
  break;
317
+ }
307
318
  case 'withContext':
308
- result = await executeWithContext(step, input, stepCtx, (s, i, c) => execute(s, i, c));
319
+ result = await executeWithContext(step, input, stepCtx, (s, i, c) => execute(s, i, c), {
320
+ layerStore: harnessWithLayerStore(baseCtx).layerStateStore,
321
+ storage: harnessWithLayerStore(baseCtx).config?.storage,
322
+ });
309
323
  break;
310
324
  case 'loop':
311
325
  result = await executeLoop(step, input, stepCtx, (s, i, c) => execute(s, i, c));
@@ -49,6 +49,7 @@ export function dispatchStepThroughAdapter(h, s, input, parentCtx, overrides) {
49
49
  stepId: s.id,
50
50
  serializedInput: input,
51
51
  executionId: childCtx.id,
52
+ parentExecutionId: parentCtx.id,
52
53
  overrides: {
53
54
  threadId: overrides?.threadId ?? parentCtx.threadId,
54
55
  resourceId: overrides?.resourceId ?? parentCtx.resourceId,
@@ -25,8 +25,8 @@ export declare const NoeticAttr: {
25
25
  /** JSON array of `{ from, to }` parent→child edges between declared nodes. */
26
26
  readonly WORKFLOW_EDGES: "noetic.workflow.edges";
27
27
  /**
28
- * Id of the step a span belongs to: the declared workflow node of an
29
- * `llm.call`/`tool.call`, the `decide` step of a `decide.call`, the `spawn`
28
+ * Id of the step a span belongs to: the `callModel` step of an
29
+ * `llm.call`/`tool.call` (or the `invokeTool` step of its `tool.call`), the `decide` step of a `decide.call`, the `spawn`
30
30
  * step of a `spawn` span, the path step of an `inParallel.path` span.
31
31
  */
32
32
  readonly NODE_ID: "noetic.node.id";
@@ -56,7 +56,7 @@ export declare const NoeticAttr: {
56
56
  readonly CONTEXT_LIVE_TOKENS: "noetic.context.live_tokens";
57
57
  /** Tokens spent superseding stale anchors. */
58
58
  readonly CONTEXT_DELTA_TOKENS: "noetic.context.delta_tokens";
59
- /** JSON array of `{ id, placement, served }` per contributing layer. */
59
+ /** JSON array of `{ id, placement, served, changed }` per contributing layer. */
60
60
  readonly CONTEXT_LAYER_PLACEMENTS: "noetic.context.layer_placements";
61
61
  /** JSON array of `{ id, rate, rebillTokens }` per contributing layer. */
62
62
  readonly CONTEXT_LAYER_CHURN: "noetic.context.layer_churn";
@@ -79,4 +79,12 @@ export declare const NoeticEvent: {
79
79
  * emits it and cannot import core.
80
80
  */
81
81
  readonly SPAWN_SUMMARY_FAILED: "spawn.summary_failed";
82
+ /**
83
+ * One per call of a traced layer hook (`init`, `recall`, `store`, `onSpawn`,
84
+ * `onReturn`, `onComplete`, `dispose`), on the span of the context the hook
85
+ * runs in: `{ layerId, hook, duration, status, itemCount?, budget.allocated?,
86
+ * budget.used?, budget.yielded?, error.message? }`. Defined in
87
+ * `@noetic-tools/context`, whose lifecycle emits it.
88
+ */
89
+ readonly LAYER_HOOK: "layer.hook";
82
90
  };
@@ -1,4 +1,4 @@
1
- import { SPAWN_SUMMARY_FAILED_EVENT } from '@noetic-tools/context';
1
+ import { LAYER_HOOK_EVENT, SPAWN_SUMMARY_FAILED_EVENT } from '@noetic-tools/context';
2
2
  // GenAI Semantic Convention attributes
3
3
  export const GenAI = {
4
4
  SYSTEM: 'gen_ai.system',
@@ -29,8 +29,8 @@ export const NoeticAttr = {
29
29
  /** JSON array of `{ from, to }` parent→child edges between declared nodes. */
30
30
  WORKFLOW_EDGES: 'noetic.workflow.edges',
31
31
  /**
32
- * Id of the step a span belongs to: the declared workflow node of an
33
- * `llm.call`/`tool.call`, the `decide` step of a `decide.call`, the `spawn`
32
+ * Id of the step a span belongs to: the `callModel` step of an
33
+ * `llm.call`/`tool.call` (or the `invokeTool` step of its `tool.call`), the `decide` step of a `decide.call`, the `spawn`
34
34
  * step of a `spawn` span, the path step of an `inParallel.path` span.
35
35
  */
36
36
  NODE_ID: 'noetic.node.id',
@@ -60,7 +60,7 @@ export const NoeticAttr = {
60
60
  CONTEXT_LIVE_TOKENS: 'noetic.context.live_tokens',
61
61
  /** Tokens spent superseding stale anchors. */
62
62
  CONTEXT_DELTA_TOKENS: 'noetic.context.delta_tokens',
63
- /** JSON array of `{ id, placement, served }` per contributing layer. */
63
+ /** JSON array of `{ id, placement, served, changed }` per contributing layer. */
64
64
  CONTEXT_LAYER_PLACEMENTS: 'noetic.context.layer_placements',
65
65
  /** JSON array of `{ id, rate, rebillTokens }` per contributing layer. */
66
66
  CONTEXT_LAYER_CHURN: 'noetic.context.layer_churn',
@@ -85,4 +85,12 @@ export const NoeticEvent = {
85
85
  * emits it and cannot import core.
86
86
  */
87
87
  SPAWN_SUMMARY_FAILED: SPAWN_SUMMARY_FAILED_EVENT,
88
+ /**
89
+ * One per call of a traced layer hook (`init`, `recall`, `store`, `onSpawn`,
90
+ * `onReturn`, `onComplete`, `dispose`), on the span of the context the hook
91
+ * runs in: `{ layerId, hook, duration, status, itemCount?, budget.allocated?,
92
+ * budget.used?, budget.yielded?, error.message? }`. Defined in
93
+ * `@noetic-tools/context`, whose lifecycle emits it.
94
+ */
95
+ LAYER_HOOK: LAYER_HOOK_EVENT,
88
96
  };
@@ -20,7 +20,9 @@ interface DetachedHandleOpts {
20
20
  * @public
21
21
  * Thin wrapper over a `SubprocessHandle` that implements the `DetachedHandle`
22
22
  * contract. Polls the adapter until the handle reaches a terminal status,
23
- * then reads the result (or error) off `handle.metadata`.
23
+ * then reads the result (or error) off `handle.metadata`. Polling starts in
24
+ * the constructor, so `status`, `result`, and `error` settle whether or not
25
+ * the caller ever invokes `.await()`.
24
26
  *
25
27
  * The polling cadence starts at 10ms and ramps to 100ms after the first
26
28
  * second — responsive for short-lived in-memory steps without burning cycles
@@ -35,7 +37,7 @@ export declare class DetachedHandleImpl<O> implements DetachedHandle<O> {
35
37
  private _status;
36
38
  private _result;
37
39
  private _error;
38
- private _settlementPromise;
40
+ private readonly _settlement;
39
41
  constructor(opts: DetachedHandleOpts);
40
42
  get status(): DetachedStatus;
41
43
  get result(): O | undefined;
@@ -47,14 +49,6 @@ export declare class DetachedHandleImpl<O> implements DetachedHandle<O> {
47
49
  * observes the final value.
48
50
  */
49
51
  await(timeout?: number): Promise<O>;
50
- /**
51
- * Start (or return the cached) polling promise that resolves on the first
52
- * terminal status the adapter reports for this handle.
53
- *
54
- * A single settlement promise is shared across all `.await()` callers so
55
- * repeated calls don't spawn parallel polling loops.
56
- */
57
- private getOrStartSettlement;
58
52
  private pollUntilSettled;
59
53
  private finalise;
60
54
  }
@@ -92,7 +92,9 @@ function extractError(metadata) {
92
92
  * @public
93
93
  * Thin wrapper over a `SubprocessHandle` that implements the `DetachedHandle`
94
94
  * contract. Polls the adapter until the handle reaches a terminal status,
95
- * then reads the result (or error) off `handle.metadata`.
95
+ * then reads the result (or error) off `handle.metadata`. Polling starts in
96
+ * the constructor, so `status`, `result`, and `error` settle whether or not
97
+ * the caller ever invokes `.await()`.
96
98
  *
97
99
  * The polling cadence starts at 10ms and ramps to 100ms after the first
98
100
  * second — responsive for short-lived in-memory steps without burning cycles
@@ -107,19 +109,22 @@ export class DetachedHandleImpl {
107
109
  _status = DetachedStatus.Running;
108
110
  _result;
109
111
  _error;
110
- _settlementPromise;
112
+ _settlement;
111
113
  constructor(opts) {
112
114
  this.id = opts.id;
113
115
  this._stepId = opts.stepId;
114
116
  this._adapter = opts.adapter;
115
117
  this._spawnPromise = opts.spawnPromise;
116
118
  this._startTime = Date.now();
117
- // Observe spawn failure eagerly so `.error` is populated even if the
118
- // caller never invokes `.await()`. We intentionally swallow the
119
- // rejection here — `.await()` surfaces it to the caller.
120
- this._spawnPromise.catch((err) => {
121
- this._status = DetachedStatus.Failed;
122
- this._error = err instanceof Error ? err.message : String(err);
119
+ // One shared poll for the handle's life, so repeated `.await()` calls
120
+ // don't start parallel loops. The rejection is swallowed here only to
121
+ // record it; `.await()` surfaces it to the caller.
122
+ this._settlement = this.pollUntilSettled();
123
+ this._settlement.catch((err) => {
124
+ if (this._status === DetachedStatus.Running) {
125
+ this._status = DetachedStatus.Failed;
126
+ this._error = err instanceof Error ? err.message : String(err);
127
+ }
123
128
  });
124
129
  }
125
130
  get status() {
@@ -138,7 +143,7 @@ export class DetachedHandleImpl {
138
143
  * observes the final value.
139
144
  */
140
145
  async await(timeout) {
141
- const settlement = this.getOrStartSettlement();
146
+ const settlement = this._settlement;
142
147
  if (timeout === undefined || timeout <= 0) {
143
148
  return settlement;
144
149
  }
@@ -165,20 +170,6 @@ export class DetachedHandleImpl {
165
170
  }
166
171
  }
167
172
  }
168
- /**
169
- * Start (or return the cached) polling promise that resolves on the first
170
- * terminal status the adapter reports for this handle.
171
- *
172
- * A single settlement promise is shared across all `.await()` callers so
173
- * repeated calls don't spawn parallel polling loops.
174
- */
175
- getOrStartSettlement() {
176
- if (this._settlementPromise) {
177
- return this._settlementPromise;
178
- }
179
- this._settlementPromise = this.pollUntilSettled();
180
- return this._settlementPromise;
181
- }
182
173
  async pollUntilSettled() {
183
174
  // Wait for the spawn itself to succeed before we start polling —
184
175
  // otherwise we'd be polling with an undefined handle id.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.9.0",
3
+ "version": "5.10.0",
4
4
  "type": "module",
5
5
  "description": "Step primitives, interpreter, runtime, and context layer contract for Noetic agents.",
6
6
  "license": "Apache-2.0",
@@ -68,8 +68,8 @@
68
68
  }
69
69
  },
70
70
  "dependencies": {
71
- "@noetic-tools/context": "^1.6.0",
72
- "@noetic-tools/types": "^3.7.0",
71
+ "@noetic-tools/context": "^1.7.0",
72
+ "@noetic-tools/types": "^3.8.0",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "zod": "^4.0.0"