@noetic-tools/core 5.8.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.
Files changed (55) hide show
  1. package/dist/adapters/in-memory-subprocess/manifest-persistence.js +5 -1
  2. package/dist/adapters/in-memory-subprocess/metadata.js +1 -0
  3. package/dist/adapters/in-memory-subprocess/types.d.ts +4 -0
  4. package/dist/adapters/in-memory-subprocess-adapter.js +2 -0
  5. package/dist/adapters/openrouter.d.ts +1 -0
  6. package/dist/adapters/openrouter.js +1 -0
  7. package/dist/builders/provide-builder.d.ts +7 -5
  8. package/dist/builders/provide-builder.js +1 -0
  9. package/dist/builders/spawn-builder.d.ts +6 -3
  10. package/dist/builders/spawn-builder.js +0 -1
  11. package/dist/builders/step-builders.d.ts +1 -2
  12. package/dist/builders/step-builders.js +1 -2
  13. package/dist/builders/tool-builder.d.ts +2 -0
  14. package/dist/builders/tool-builder.js +2 -0
  15. package/dist/builders/workflow-hydrator.js +15 -13
  16. package/dist/builders/workflow-replay-key.d.ts +15 -0
  17. package/dist/builders/workflow-replay-key.js +46 -0
  18. package/dist/harness/agent-harness.d.ts +25 -6
  19. package/dist/harness/agent-harness.js +72 -26
  20. package/dist/harness/deps/interpreter.d.ts +1 -0
  21. package/dist/harness/deps/interpreter.js +1 -0
  22. package/dist/harness/model-call.d.ts +3 -0
  23. package/dist/harness/model-call.js +65 -17
  24. package/dist/index.d.ts +4 -0
  25. package/dist/interpreter/action-deps.d.ts +2 -2
  26. package/dist/interpreter/action-deps.js +2 -2
  27. package/dist/interpreter/action-types.d.ts +1 -1
  28. package/dist/interpreter/child-span.d.ts +5 -4
  29. package/dist/interpreter/child-span.js +5 -4
  30. package/dist/interpreter/collect-tools.js +19 -54
  31. package/dist/interpreter/context-assembly.d.ts +5 -4
  32. package/dist/interpreter/context-assembly.js +18 -14
  33. package/dist/interpreter/execute-action.d.ts +25 -5
  34. package/dist/interpreter/execute-action.js +67 -10
  35. package/dist/interpreter/execute-control.js +3 -1
  36. package/dist/interpreter/execute-decide.js +9 -27
  37. package/dist/interpreter/execute.js +48 -40
  38. package/dist/interpreter/model-error.d.ts +9 -0
  39. package/dist/interpreter/model-error.js +32 -0
  40. package/dist/interpreter/step-dispatcher.js +1 -0
  41. package/dist/interpreter/step-walk.d.ts +11 -0
  42. package/dist/interpreter/step-walk.js +41 -0
  43. package/dist/observability/genai-attributes.d.ts +18 -3
  44. package/dist/observability/genai-attributes.js +19 -3
  45. package/dist/runtime/context-impl.d.ts +29 -31
  46. package/dist/runtime/context-impl.js +65 -45
  47. package/dist/runtime/durable/harness-checkpoints.d.ts +31 -18
  48. package/dist/runtime/durable/harness-checkpoints.js +70 -54
  49. package/dist/runtime/durable/step-ledger.d.ts +1 -1
  50. package/dist/runtime/durable/step-ledger.js +1 -1
  51. package/dist/schemas/workflow.d.ts +1 -1
  52. package/dist/util/detached-handle.d.ts +4 -10
  53. package/dist/util/detached-handle.js +14 -23
  54. package/package.json +3 -3
  55. package/schema/noetic-workflow.schema.json +375 -0
@@ -3,4 +3,5 @@ export { prepareBandedView } from '../../interpreter/context-assembly.js';
3
3
  export { execute } from '../../interpreter/execute.js';
4
4
  export type { DetachedSpawnOverrides } from '../../interpreter/step-dispatcher.js';
5
5
  export { dispatchStepThroughAdapter } from '../../interpreter/step-dispatcher.js';
6
+ export { someStep } from '../../interpreter/step-walk.js';
6
7
  export { isFunctionCall } from '../../interpreter/typeguards.js';
@@ -2,4 +2,5 @@ export { collectAllTools, deduplicateTools } from '../../interpreter/collect-too
2
2
  export { prepareBandedView } from '../../interpreter/context-assembly.js';
3
3
  export { execute } from '../../interpreter/execute.js';
4
4
  export { dispatchStepThroughAdapter } from '../../interpreter/step-dispatcher.js';
5
+ export { someStep } from '../../interpreter/step-walk.js';
5
6
  export { isFunctionCall } from '../../interpreter/typeguards.js';
@@ -1,4 +1,5 @@
1
1
  import type { AgentHarnessContract, CallModelRequest, ItemSchemaRegistry, LLMResponse, TraceExporter } from '@noetic-tools/types';
2
+ import { NoeticConfigError } from '@noetic-tools/types';
2
3
  import type { OpenRouter } from '@openrouter/agent';
3
4
  import type { MessageQueue } from '../runtime/message-queue.js';
4
5
  interface StreamIdleWatchdog {
@@ -7,6 +8,8 @@ interface StreamIdleWatchdog {
7
8
  /** Clear the pending timer. Safe to call multiple times. */
8
9
  stop: () => void;
9
10
  }
11
+ /** @internal The error for a model call on a harness with no LLM credentials. */
12
+ export declare function noLlmProviderError(): NoeticConfigError;
10
13
  /** @internal Create a watchdog that aborts `controller` when no
11
14
  * {@link StreamIdleWatchdog.reset reset} is called within `timeoutMs`. When
12
15
  * `timeoutMs <= 0`, returns an inert no-op so callers can always call `.reset()`
@@ -133,6 +133,14 @@ async function pipeStreamEventsToBroadcaster(opts) {
133
133
  throw err;
134
134
  }
135
135
  }
136
+ /** @internal The error for a model call on a harness with no LLM credentials. */
137
+ export function noLlmProviderError() {
138
+ return new NoeticConfigError({
139
+ code: 'NO_LLM_PROVIDER',
140
+ message: 'No LLM provider configured on this harness.',
141
+ hint: 'Pass `callModelDefaults: { apiKey: "..." }` (defaults to the Noetic platform) or set NOETIC_API_KEY. For direct OpenRouter, use `callModelDefaults: { provider: "openrouter", apiKey: "..." }` or set OPENROUTER_API_KEY.',
142
+ });
143
+ }
136
144
  /** @internal Create a watchdog that aborts `controller` when no
137
145
  * {@link StreamIdleWatchdog.reset reset} is called within `timeoutMs`. When
138
146
  * `timeoutMs <= 0`, returns an inert no-op so callers can always call `.reset()`
@@ -191,15 +199,18 @@ function prepareModelRequest(request, agentName) {
191
199
  .filter(Boolean)
192
200
  .join('\n\n') || undefined;
193
201
  const broadcaster = getBroadcaster(request.ctx);
194
- 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.
195
206
  // Client (function) tools convert to SDK tool definitions; OpenRouter server
196
207
  // tools (web_search/web_fetch) are wrapped via the SDK's `serverTool()` so
197
208
  // its convertToolsToAPIFormat accepts them — a raw `{type}` entry crashes it.
198
209
  // `parameters` keys stay camelCase: the SDK's outbound zod schema strips
199
210
  // unknown keys, so snake_case would be silently dropped.
200
- const clientSdkTools = filteredTools && filteredTools.length > 0
211
+ const clientSdkTools = request.tools && allowedTools.length > 0
201
212
  ? convertTools({
202
- tools: filteredTools,
213
+ tools: request.tools,
203
214
  })
204
215
  : [];
205
216
  const serverSdkTools = (request._serverTools ?? []).map((s) => serverTool(frameworkCast({
@@ -215,6 +226,8 @@ function prepareModelRequest(request, agentName) {
215
226
  remaining,
216
227
  broadcaster,
217
228
  sdkTools: sdkTools.length > 0 ? sdkTools : undefined,
229
+ toolChoice: clientSdkTools.length > 0 ? allowedToolsChoice(request, allowedTools) : undefined,
230
+ allowedTools,
218
231
  emitIfAllowed(eventType, data) {
219
232
  if (!shouldEmit(request.emit, eventType, data)) {
220
233
  return;
@@ -228,6 +241,33 @@ function prepareModelRequest(request, agentName) {
228
241
  },
229
242
  };
230
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
+ }
231
271
  function filterAllowedTools(request) {
232
272
  if (!request.tools) {
233
273
  return undefined;
@@ -249,12 +289,16 @@ class CallSpanCollector {
249
289
  exporter;
250
290
  parent;
251
291
  nodeId;
292
+ firstSpanAttributes;
252
293
  spans = [];
253
- constructor(harness, exporter, parent, nodeId) {
294
+ constructor(harness, exporter, parent, nodeId,
295
+ /** Stamped on the first model span only, then dropped. */
296
+ firstSpanAttributes) {
254
297
  this.harness = harness;
255
298
  this.exporter = exporter;
256
299
  this.parent = parent;
257
300
  this.nodeId = nodeId;
301
+ this.firstSpanAttributes = firstSpanAttributes;
258
302
  }
259
303
  /** Link a span back to its declared workflow node, when the call carries one. */
260
304
  stampNode(span) {
@@ -268,6 +312,10 @@ class CallSpanCollector {
268
312
  span.setAttribute(GenAI.SYSTEM, 'openrouter');
269
313
  span.setAttribute(GenAI.REQUEST_MODEL, model);
270
314
  this.stampNode(span);
315
+ for (const [key, value] of Object.entries(this.firstSpanAttributes ?? {})) {
316
+ span.setAttribute(key, value);
317
+ }
318
+ this.firstSpanAttributes = undefined;
271
319
  this.spans.push(span);
272
320
  return span;
273
321
  }
@@ -309,7 +357,7 @@ export class AgentHarnessModelCaller {
309
357
  this.opts = opts;
310
358
  }
311
359
  newSpanCollector(request) {
312
- 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);
313
361
  }
314
362
  /**
315
363
  * Broadcast a framework-authored item so `getItemStream` carries it — tool
@@ -354,11 +402,7 @@ export class AgentHarnessModelCaller {
354
402
  if (this.opts.client) {
355
403
  return this.opts.client;
356
404
  }
357
- throw new NoeticConfigError({
358
- code: 'NO_LLM_PROVIDER',
359
- message: 'No LLM provider configured on this harness.',
360
- hint: 'Pass `callModelDefaults: { apiKey: "..." }` (defaults to the Noetic platform) or set NOETIC_API_KEY. For direct OpenRouter, use `callModelDefaults: { provider: "openrouter", apiKey: "..." }` or set OPENROUTER_API_KEY.',
361
- });
405
+ throw noLlmProviderError();
362
406
  }
363
407
  async callModel(request) {
364
408
  if (this.opts.callModelOverride) {
@@ -432,6 +476,7 @@ export class AgentHarnessModelCaller {
432
476
  input: modelInput,
433
477
  instructions: prepared.instructions,
434
478
  tools: prepared.sdkTools,
479
+ toolChoice: prepared.toolChoice,
435
480
  temperature: request.params?.temperature,
436
481
  maxOutputTokens: request.params?.maxTokens,
437
482
  topP: request.params?.topP,
@@ -537,6 +582,7 @@ export class AgentHarnessModelCaller {
537
582
  await this.executeToolRound({
538
583
  functionCalls,
539
584
  request,
585
+ allowedTools: prepared.allowedTools,
540
586
  allItems,
541
587
  conversationInput,
542
588
  round,
@@ -670,7 +716,7 @@ export class AgentHarnessModelCaller {
670
716
  };
671
717
  }
672
718
  async executeToolRound(params) {
673
- const { functionCalls, request, allItems, conversationInput, spans, modelSpan } = params;
719
+ const { functionCalls, request, allowedTools, allItems, conversationInput, spans, modelSpan } = params;
674
720
  params.emitIfAllowed('tool_round_started', {
675
721
  round: params.round,
676
722
  toolCount: functionCalls.length,
@@ -688,11 +734,12 @@ export class AgentHarnessModelCaller {
688
734
  if (request.signal?.aborted) {
689
735
  break;
690
736
  }
691
- const toolForCall = request.tools?.find((tool) => tool.name === fc.name || sanitizeToolNameForWire(tool.name) === fc.name);
737
+ const toolForCall = findTool(allowedTools, fc.name);
692
738
  spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false);
693
739
  await this.executeFunctionCall({
694
740
  fc,
695
741
  request,
742
+ allowedTools,
696
743
  allItems,
697
744
  conversationInput,
698
745
  emitIfAllowed: params.emitIfAllowed,
@@ -704,7 +751,7 @@ export class AgentHarnessModelCaller {
704
751
  });
705
752
  }
706
753
  async executeFunctionCall(params) {
707
- const { fc, request, allItems, conversationInput } = params;
754
+ const { fc, request, allowedTools, allItems, conversationInput } = params;
708
755
  params.emitIfAllowed('tool_call_started', {
709
756
  name: fc.name,
710
757
  callId: fc.callId,
@@ -717,6 +764,7 @@ export class AgentHarnessModelCaller {
717
764
  this.recordMalformedToolCall({
718
765
  fc,
719
766
  request,
767
+ allowedTools,
720
768
  allItems,
721
769
  conversationInput,
722
770
  emitIfAllowed: params.emitIfAllowed,
@@ -726,11 +774,11 @@ export class AgentHarnessModelCaller {
726
774
  if (!request.tools) {
727
775
  throw new Error(`executeFunctionCall invoked without tools on CallModelRequest (tool name: ${fc.name}).`);
728
776
  }
729
- const toolForCall = request.tools.find((tool) => tool.name === fc.name || sanitizeToolNameForWire(tool.name) === fc.name);
777
+ const toolForCall = findTool(allowedTools, fc.name);
730
778
  const toolResult = await executeToolCall({
731
779
  toolName: fc.name,
732
780
  args: parsedArgs,
733
- tools: request.tools,
781
+ tools: allowedTools,
734
782
  context: request.ctx,
735
783
  harness: this.opts.harness,
736
784
  layers: request.layers,
@@ -764,9 +812,9 @@ export class AgentHarnessModelCaller {
764
812
  });
765
813
  }
766
814
  recordMalformedToolCall(params) {
767
- const { fc, request, allItems, conversationInput } = params;
815
+ const { fc, request, allowedTools, allItems, conversationInput } = params;
768
816
  const errorOutput = `Error: malformed JSON in tool arguments: ${fc.arguments}`;
769
- const toolForCall = request.tools?.find((tool) => tool.name === fc.name || sanitizeToolNameForWire(tool.name) === fc.name);
817
+ const toolForCall = findTool(allowedTools, fc.name);
770
818
  // Owner-scoped result validation (see executeFunctionCall).
771
819
  const outputItem = createToolResultItem({
772
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,8 +1,8 @@
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';
6
- export { ContextImpl } from '../runtime/context-impl.js';
6
+ export { ContextImpl, laneBase } from '../runtime/context-impl.js';
7
7
  export { snapshotCwdState } from '../runtime/cwd-helpers.js';
8
8
  export { buildToolExecutionContext } from '../runtime/tool-context.js';
@@ -1,6 +1,6 @@
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
- export { ContextImpl } from '../runtime/context-impl.js';
4
+ export { ContextImpl, laneBase } from '../runtime/context-impl.js';
5
5
  export { snapshotCwdState } from '../runtime/cwd-helpers.js';
6
6
  export { buildToolExecutionContext } from '../runtime/tool-context.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,5 @@
1
1
  import { frameworkCast, isServerToolSpec } from '@noetic-tools/types';
2
+ import { stepChildren } from './step-walk.js';
2
3
  /**
3
4
  * Recursively walks a step tree and collects all Tool instances
4
5
  * declared on LLM steps. Used to build the unified tool set
@@ -26,59 +27,23 @@ export function deduplicateTools(tools) {
26
27
  ];
27
28
  }
28
29
  function walkStep(step, out) {
29
- switch (step.kind) {
30
- case 'callModel':
31
- // Skip function-form tools: they're resolved per execution from `ctx`
32
- // and cannot contribute to the pre-computed unified set. Consumers that
33
- // need those tools in the pool should register them via
34
- // `AgentHarness.tools` instead. Inline server-tool specs (web search/
35
- // fetch) are not client `Tool`s — they never enter the unified pool.
36
- if (Array.isArray(step.tools)) {
37
- for (const entry of step.tools) {
38
- if (!isServerToolSpec(entry)) {
39
- out.push(entry);
40
- }
41
- }
42
- }
43
- return;
44
- case 'runCode':
45
- case 'invokeTool':
46
- // Decide steps ask questions; they never call tools.
47
- case 'decide':
48
- // An ACP agent runs its own tools inside the external agent process; it
49
- // contributes nothing to the host unified tool set.
50
- case 'acp-agent':
51
- return;
52
- case 'conditional':
53
- if (step._optimizable) {
54
- for (const child of step._optimizable) {
55
- walkStep(child, out);
56
- }
57
- }
58
- return;
59
- case 'inParallel':
60
- if (step._optimizable) {
61
- for (const child of step._optimizable) {
62
- walkStep(child, out);
63
- }
64
- }
65
- return;
66
- case 'withContext':
67
- walkStep(step.child, out);
68
- return;
69
- case 'spawn':
70
- walkStep(step.child, out);
71
- return;
72
- case 'loop':
73
- for (const child of step.steps) {
74
- walkStep(child, out);
75
- }
76
- return;
77
- case 'schedule':
78
- walkStep(step.step, out);
79
- return;
80
- default:
81
- step;
82
- return;
30
+ if (step.kind !== 'callModel') {
31
+ for (const child of stepChildren(step)) {
32
+ walkStep(child, out);
33
+ }
34
+ return;
35
+ }
36
+ // Skip function-form tools: they're resolved per execution from `ctx`
37
+ // and cannot contribute to the pre-computed unified set. Consumers that
38
+ // need those tools in the pool should register them via
39
+ // `AgentHarness.tools` instead. Inline server-tool specs (web search/
40
+ // fetch) are not client `Tool`s — they never enter the unified pool.
41
+ if (!Array.isArray(step.tools)) {
42
+ return;
43
+ }
44
+ for (const entry of step.tools) {
45
+ if (!isServerToolSpec(entry)) {
46
+ out.push(entry);
47
+ }
83
48
  }
84
49
  }
@@ -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>;