@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
@@ -2,14 +2,16 @@
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';
14
+ import { wrapModelError } from './model-error.js';
13
15
  import { parseStructuredOutput } from './structured-output.js';
14
16
  import { getContextChannelStore, isContextImpl, isFunctionCall, isMutableContext, } from './typeguards.js';
15
17
  //#region run
@@ -404,6 +406,7 @@ function buildModelRequest(params) {
404
406
  layers,
405
407
  nodeId: step.id,
406
408
  parentSpan: ctx.span,
409
+ spanAttributes: params.spanAttributes,
407
410
  signal,
408
411
  };
409
412
  if (params.resolvedTools) {
@@ -522,7 +525,9 @@ export async function executeCallModel(step, input, ctx, layers) {
522
525
  systemPromptItems: [],
523
526
  budgets: budgetMap,
524
527
  });
525
- 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);
526
531
  let retries = 0;
527
532
  // Guidance from a steering retry rides at the very end of the view, after the
528
533
  // live band and the supersedes, rather than wherever history happens to put it.
@@ -547,8 +552,12 @@ export async function executeCallModel(step, input, ctx, layers) {
547
552
  outputSchema,
548
553
  serverToolSpecs,
549
554
  assembledItems,
555
+ spanAttributes,
556
+ });
557
+ spanAttributes = undefined;
558
+ const response = await baseCtx.harness.callModel(request).catch((e) => {
559
+ throw wrapModelError(e, step.id, baseCtx);
550
560
  });
551
- const response = await baseCtx.harness.callModel(request);
552
561
  // Track tokens/cost for EVERY model call, including responses steering
553
562
  // subsequently rejects (Deny throw / Guide retry below) — the spend is
554
563
  // real, and until.maxCost / HarnessResponse.usage must see it (spec 07:
@@ -661,7 +670,7 @@ async function collectSpawnItems({ layers, parentExecutionCtx, childExecutionCtx
661
670
  export async function executeSpawn(step, input, ctx, executeStep, opts) {
662
671
  const baseCtx = frameworkCast(ctx);
663
672
  const layers = resolveLayersForSpawn(step, opts?.parentLayers);
664
- const childId = crypto.randomUUID();
673
+ const childId = opts?.childId ?? crypto.randomUUID();
665
674
  const childExecutionCtx = contextToExecCtx(baseCtx, {
666
675
  executionId: childId,
667
676
  depth: baseCtx.depth + 1,
@@ -738,8 +747,13 @@ export async function executeSpawn(step, input, ctx, executeStep, opts) {
738
747
  }
739
748
  return returnLayers({
740
749
  layers,
750
+ stepId: step.id,
741
751
  parentCtx: parentExecutionCtx,
742
- childCtx: childExecutionCtx,
752
+ // `childExecutionCtx` predates the spawn span; trace onto that span.
753
+ childCtx: {
754
+ ...childExecutionCtx,
755
+ trace: span,
756
+ },
743
757
  childLog: childCtx.itemLog,
744
758
  result: childOutput,
745
759
  store: layerStore,
@@ -779,18 +793,27 @@ function mergeLayers(existing, provided) {
779
793
  ];
780
794
  }
781
795
  /**
782
- * Executes a provide step by attaching context layers to the current context
783
- * 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.
784
798
  *
785
- * 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.
786
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.
787
808
  */
788
- export async function executeWithContext(step, input, ctx, executeStep) {
809
+ export async function executeWithContext(step, input, ctx, executeStep, opts) {
789
810
  const baseCtx = frameworkCast(ctx);
790
811
  const previousLayers = baseCtx.layers;
791
812
  const previousUnifiedTools = baseCtx.unifiedTools;
792
813
  const newLayers = resolveLayers(step);
793
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));
794
817
  // Attach layers to the current context (no isolation)
795
818
  baseCtx.layers = mergedLayers;
796
819
  // Merge new layer-provided tools into the unified tool set
@@ -803,13 +826,36 @@ export async function executeWithContext(step, input, ctx, executeStep) {
803
826
  ]);
804
827
  }
805
828
  }
829
+ const layerStore = opts?.layerStore;
830
+ const execCtx = contextToExecCtx(baseCtx);
806
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
+ }
807
840
  return await executeStep(step.child, input, ctx);
808
841
  }
809
842
  finally {
810
843
  // Restore previous layers and unified tools so siblings are not affected
811
844
  baseCtx.layers = previousLayers;
812
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
+ }
813
859
  }
814
860
  }
815
861
  //#endregion
@@ -851,8 +897,19 @@ async function consumeToolGenerator(params) {
851
897
  });
852
898
  }
853
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
+ */
854
905
  export async function executeInvokeTool(step, input, ctx, harness, layers) {
855
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) {
856
913
  const args = step.args ? Object.assign({}, input, step.args) : input;
857
914
  const parseResult = await validateSchema(step.tool.input, args);
858
915
  if (!parseResult.success) {
@@ -86,7 +86,7 @@ function tracePaths(ctx, executeStep, childContexts) {
86
86
  },
87
87
  };
88
88
  }
89
- function createForkLayerBridge({ ctx, childContexts, opts, }) {
89
+ function createForkLayerBridge({ stepId, ctx, childContexts, opts, }) {
90
90
  const layers = ctx.layers;
91
91
  const layerStore = opts?.layerStore;
92
92
  if (!layers || layers.length === 0 || !layerStore) {
@@ -113,6 +113,7 @@ function createForkLayerBridge({ ctx, childContexts, opts, }) {
113
113
  settle(index, result) {
114
114
  return serialize(() => returnLayers({
115
115
  layers: layers ?? [],
116
+ stepId,
116
117
  parentCtx: parentExecCtx,
117
118
  childCtx: childExecCtxs[index],
118
119
  childLog: childContexts[index].itemLog,
@@ -173,6 +174,7 @@ export async function executeInParallel(step, input, ctx, rawExecuteStep, opts)
173
174
  const childContexts = createChildContexts(baseCtx, paths, step.id);
174
175
  const concurrency = step.concurrency ?? paths.length;
175
176
  const traced = tracePaths(baseCtx, withForkLayers(rawExecuteStep, childContexts, createForkLayerBridge({
177
+ stepId: step.id,
176
178
  ctx: baseCtx,
177
179
  childContexts,
178
180
  opts,
@@ -1,10 +1,10 @@
1
- import { choiceValues, DecideOutputError, frameworkCast, hashString, isNoeticError, NoeticConfigError, NoeticErrorImpl, scoreLevels, } from '@noetic-tools/types';
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 { statusOf } from '../util/status-code.js';
5
- import { allocateBudgets, assembleView, DECISION_PROJECTION } from './action-deps.js';
4
+ import { allocateBudgets, assembleView, DECISION_PROJECTION, laneBase } from './action-deps.js';
6
5
  import { resolveLazy } from './execute-action.js';
7
6
  import { trackUsage } from './message-helpers.js';
7
+ import { wrapModelError } from './model-error.js';
8
8
  import { isContextImpl, isMutableContext } from './typeguards.js';
9
9
  //#region Public API
10
10
  /**
@@ -110,10 +110,12 @@ export async function executeDecide(step, input, ctx, layers) {
110
110
  */
111
111
  const ANSWERED = new WeakMap();
112
112
  function answered(ctx) {
113
- let map = ANSWERED.get(ctx);
113
+ // Every step runs on its own lane of the context; the answers belong to the context.
114
+ const key = laneBase(ctx);
115
+ let map = ANSWERED.get(key);
114
116
  if (!map) {
115
117
  map = new Map();
116
- ANSWERED.set(ctx, map);
118
+ ANSWERED.set(key, map);
117
119
  }
118
120
  return map;
119
121
  }
@@ -150,16 +152,7 @@ async function askHarness(step, ctx, request) {
150
152
  return await ctx.harness.decide(request);
151
153
  }
152
154
  catch (e) {
153
- if (isNoeticError(e) || e instanceof NoeticConfigError) {
154
- throw e;
155
- }
156
- if (ctx.aborted) {
157
- throw new NoeticErrorImpl({
158
- kind: 'cancelled',
159
- reason: ctx.abortReason ?? 'context aborted',
160
- });
161
- }
162
- if (e instanceof DecideOutputError) {
155
+ if (e instanceof DecideOutputError && !ctx.aborted) {
163
156
  if (e.usage) {
164
157
  trackUsage(ctx, {
165
158
  items: [],
@@ -175,18 +168,7 @@ async function askHarness(step, ctx, request) {
175
168
  zodError: e.zodError,
176
169
  });
177
170
  }
178
- if (statusOf(e) === 429) {
179
- throw new NoeticErrorImpl({
180
- kind: 'model_rate_limit',
181
- stepId: step.id,
182
- });
183
- }
184
- throw new NoeticErrorImpl({
185
- kind: 'step_failed',
186
- stepId: step.id,
187
- cause: e instanceof Error ? e : new Error(String(e)),
188
- retriesExhausted: false,
189
- });
171
+ throw wrapModelError(e, step.id, ctx);
190
172
  }
191
173
  }
192
174
  //#endregion
@@ -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,
@@ -142,14 +147,12 @@ export function resolveLedgerKey(step, input, ctx) {
142
147
  }
143
148
  /**
144
149
  * Resume path: when a previous run recorded this exact step at `ledgerKey`,
145
- * replay its output instead of re-running. Held as a helper (rather than inline
146
- * in `execute`) so the resume branch stays flat: it pops the frontier itself —
147
- * the caller returns before the normal `leaveStep` runs — and emits
148
- * `step_replayed`. Returns `{ hit: false }` when there is nothing to replay so
149
- * the caller dispatches the step normally.
150
+ * replay its output instead of re-running, and emit `step_replayed`. Returns
151
+ * `{ hit: false }` when there is nothing to replay so the caller dispatches the
152
+ * step normally.
150
153
  */
151
154
  function replayFromLedger(opts) {
152
- const { ledger, ledgerKey, impl, step, broadcaster, agentName } = opts;
155
+ const { ledger, ledgerKey, step, broadcaster, agentName } = opts;
153
156
  if (!ledger || ledgerKey === undefined || ledger.isEmpty) {
154
157
  return {
155
158
  hit: false,
@@ -164,9 +167,6 @@ function replayFromLedger(opts) {
164
167
  hit: false,
165
168
  };
166
169
  }
167
- if (impl && step.id.length > 0) {
168
- impl.leaveStep(step.id);
169
- }
170
170
  emitFrameworkEvent({
171
171
  broadcaster,
172
172
  agentName,
@@ -249,73 +249,83 @@ export async function execute(step, input, ctx) {
249
249
  data: startedData,
250
250
  });
251
251
  }
252
- // Push onto the durable frontier so checkpoints can record exactly which
253
- // step was in flight when the snapshot fired. Steps with empty ids are
254
- // skipped — they are not reattachable by id and would pollute the stack.
252
+ /* Register the step as in flight, so a checkpoint records it in the frontier, and
253
+ * run it on its own lane: a view of the context that carries this dispatch's path.
254
+ * Steps this step dispatches hang under that path, so concurrent dispatches on one
255
+ * context cannot interleave each other's paths. Steps with empty ids stay on the
256
+ * caller's lane — they are not reattachable by id and add no path segment. */
255
257
  const impl = asContextImpl(baseCtx);
256
- if (impl && step.id.length > 0) {
257
- impl.enterStep({
258
- stepId: step.id,
259
- input,
260
- });
261
- }
258
+ const frame = {
259
+ stepId: step.id,
260
+ input,
261
+ };
262
+ const lane = impl && step.id.length > 0 ? impl.enterStep(frame) : null;
263
+ const stepCtx = lane ? frameworkCast(lane) : ctx;
262
264
  /* Resume: a previous run that completed this exact step replays its recorded
263
265
  * output instead of re-running it. `ledgerKey`/`ledger` are captured before
264
- * dispatch and reused by the record below, because `leaveStep` pops the path
265
- * on the way out. */
266
- const ledgerKey = resolveLedgerKey(step, input, ctx);
266
+ * dispatch and reused by the record below. */
267
+ const ledgerKey = resolveLedgerKey(step, input, stepCtx);
267
268
  const ledger = impl?.ledger;
268
269
  const replay = replayFromLedger({
269
270
  ledger,
270
271
  ledgerKey,
271
- impl,
272
272
  step,
273
273
  broadcaster,
274
274
  agentName,
275
275
  });
276
276
  if (replay.hit) {
277
+ lane?.leaveStep(frame);
277
278
  return replay.output;
278
279
  }
279
280
  let result;
280
281
  try {
281
282
  switch (step.kind) {
282
283
  case 'runCode':
283
- result = await dispatchViaAdapter(step, input, ctx, () => executeRunCode(step, input, ctx));
284
+ result = await dispatchViaAdapter(step, input, stepCtx, stepCtx.id, () => executeRunCode(step, input, stepCtx));
284
285
  break;
285
286
  case 'callModel':
286
- result = await executeCallModel(step, input, ctx, baseCtx.layers);
287
+ result = await executeCallModel(step, input, stepCtx, baseCtx.layers);
287
288
  break;
288
289
  case 'acp-agent':
289
- result = await executeAcpAgent(step, input, ctx, baseCtx.layers);
290
+ result = await executeAcpAgent(step, input, stepCtx, baseCtx.layers);
290
291
  break;
291
292
  case 'invokeTool':
292
- result = await executeInvokeTool(step, input, ctx, baseCtx.harness);
293
+ result = await executeInvokeTool(step, input, stepCtx, baseCtx.harness);
293
294
  break;
294
295
  case 'decide':
295
- result = await executeDecide(step, input, ctx, baseCtx.layers);
296
+ result = await executeDecide(step, input, stepCtx, baseCtx.layers);
296
297
  break;
297
298
  case 'conditional':
298
- result = await executeConditional(step, input, ctx, (s, i, c) => execute(s, i, c));
299
+ result = await executeConditional(step, input, stepCtx, (s, i, c) => execute(s, i, c));
299
300
  break;
300
301
  case 'inParallel':
301
- result = await executeInParallel(step, input, ctx, (s, i, c) => execute(s, i, c), {
302
+ result = await executeInParallel(step, input, stepCtx, (s, i, c) => execute(s, i, c), {
302
303
  // Fork paths are child executions: the layer store lets their
303
304
  // `onSpawn`/`onReturn` boundary run (see `createForkLayerBridge`).
304
305
  layerStore: harnessWithLayerStore(baseCtx).layerStateStore,
305
306
  itemSchemas: baseCtx.itemSchemas,
306
307
  });
307
308
  break;
308
- case 'spawn':
309
- result = await dispatchViaAdapter(step, input, ctx, () => executeSpawn(step, input, ctx, (s, i, c) => execute(s, i, c), buildSpawnOpts(ctx)));
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
+ }));
310
316
  break;
317
+ }
311
318
  case 'withContext':
312
- result = await executeWithContext(step, input, ctx, (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
+ });
313
323
  break;
314
324
  case 'loop':
315
- result = await executeLoop(step, input, ctx, (s, i, c) => execute(s, i, c));
325
+ result = await executeLoop(step, input, stepCtx, (s, i, c) => execute(s, i, c));
316
326
  break;
317
327
  case 'schedule':
318
- result = await executeSchedule(step, input, ctx, (s, i, c) => execute(s, i, c));
328
+ result = await executeSchedule(step, input, stepCtx, (s, i, c) => execute(s, i, c));
319
329
  break;
320
330
  default: {
321
331
  const _exhaustive = step;
@@ -330,9 +340,7 @@ export async function execute(step, input, ctx) {
330
340
  }
331
341
  }
332
342
  finally {
333
- if (impl && step.id.length > 0) {
334
- impl.leaveStep(step.id);
335
- }
343
+ lane?.leaveStep(frame);
336
344
  }
337
345
  // Emit step_completed framework event (respects step.emit option)
338
346
  const completedData = {
@@ -0,0 +1,9 @@
1
+ import type { Context } from './action-types.js';
2
+ /**
3
+ * Give an error from a model provider call the step's id and a Noetic kind.
4
+ *
5
+ * Noetic errors pass through untouched. A failure on an aborted context is
6
+ * `cancelled` (the abort is what broke the call), a 429 is `model_rate_limit`,
7
+ * and anything else is `step_failed` with the provider error as its cause.
8
+ */
9
+ export declare function wrapModelError(e: unknown, stepId: string, ctx: Pick<Context, 'aborted' | 'abortReason'>): Error;
@@ -0,0 +1,32 @@
1
+ import { isNoeticError, NoeticConfigError, NoeticErrorImpl } from '@noetic-tools/types';
2
+ import { statusOf } from '../util/status-code.js';
3
+ /**
4
+ * Give an error from a model provider call the step's id and a Noetic kind.
5
+ *
6
+ * Noetic errors pass through untouched. A failure on an aborted context is
7
+ * `cancelled` (the abort is what broke the call), a 429 is `model_rate_limit`,
8
+ * and anything else is `step_failed` with the provider error as its cause.
9
+ */
10
+ export function wrapModelError(e, stepId, ctx) {
11
+ if (isNoeticError(e) || e instanceof NoeticConfigError) {
12
+ return e;
13
+ }
14
+ if (ctx.aborted) {
15
+ return new NoeticErrorImpl({
16
+ kind: 'cancelled',
17
+ reason: ctx.abortReason ?? 'context aborted',
18
+ });
19
+ }
20
+ if (statusOf(e) === 429) {
21
+ return new NoeticErrorImpl({
22
+ kind: 'model_rate_limit',
23
+ stepId,
24
+ });
25
+ }
26
+ return new NoeticErrorImpl({
27
+ kind: 'step_failed',
28
+ stepId,
29
+ cause: e instanceof Error ? e : new Error(String(e)),
30
+ retriesExhausted: false,
31
+ });
32
+ }
@@ -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,
@@ -0,0 +1,11 @@
1
+ import type { Step } from '@noetic-tools/types';
2
+ /**
3
+ * Whether `step` or any step nested in it satisfies `test`.
4
+ *
5
+ * Only statically declared children are visited: a `conditional` or
6
+ * `inParallel` built from functions exposes its children through
7
+ * `_optimizable` only when the builder could enumerate them.
8
+ */
9
+ export declare function someStep(step: Step, test: (step: Step) => boolean): boolean;
10
+ /** The steps nested directly inside `step`, as far as they are statically known. */
11
+ export declare function stepChildren(step: Step): ReadonlyArray<Step>;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Whether `step` or any step nested in it satisfies `test`.
3
+ *
4
+ * Only statically declared children are visited: a `conditional` or
5
+ * `inParallel` built from functions exposes its children through
6
+ * `_optimizable` only when the builder could enumerate them.
7
+ */
8
+ export function someStep(step, test) {
9
+ if (test(step)) {
10
+ return true;
11
+ }
12
+ return stepChildren(step).some((child) => someStep(child, test));
13
+ }
14
+ /** The steps nested directly inside `step`, as far as they are statically known. */
15
+ export function stepChildren(step) {
16
+ switch (step.kind) {
17
+ case 'callModel':
18
+ case 'runCode':
19
+ case 'invokeTool':
20
+ case 'decide':
21
+ case 'acp-agent':
22
+ return [];
23
+ case 'conditional':
24
+ case 'inParallel':
25
+ return step._optimizable ?? [];
26
+ case 'withContext':
27
+ case 'spawn':
28
+ return [
29
+ step.child,
30
+ ];
31
+ case 'loop':
32
+ return step.steps;
33
+ case 'schedule':
34
+ return [
35
+ step.step,
36
+ ];
37
+ default:
38
+ step;
39
+ return [];
40
+ }
41
+ }
@@ -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";
@@ -72,4 +72,19 @@ export declare const NoeticEvent: {
72
72
  readonly LOOP_VERDICT: "loop.verdict";
73
73
  /** A channel dropped data or is waiting with no timeout: `{ kind, channelName, message, capacity?, operation? }`. */
74
74
  readonly CHANNEL_WARNING: "channel.warning";
75
+ /**
76
+ * A layer's `onReturn` hook failed, so a spawn or inParallel path returned
77
+ * its result unchanged. Added to the child's span: `{ stepId, layerId,
78
+ * message }`. Defined in `@noetic-tools/context`, whose `returnLayers`
79
+ * emits it and cannot import core.
80
+ */
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";
75
90
  };
@@ -1,3 +1,4 @@
1
+ import { LAYER_HOOK_EVENT, SPAWN_SUMMARY_FAILED_EVENT } from '@noetic-tools/context';
1
2
  // GenAI Semantic Convention attributes
2
3
  export const GenAI = {
3
4
  SYSTEM: 'gen_ai.system',
@@ -28,8 +29,8 @@ export const NoeticAttr = {
28
29
  /** JSON array of `{ from, to }` parent→child edges between declared nodes. */
29
30
  WORKFLOW_EDGES: 'noetic.workflow.edges',
30
31
  /**
31
- * Id of the step a span belongs to: the declared workflow node of an
32
- * `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`
33
34
  * step of a `spawn` span, the path step of an `inParallel.path` span.
34
35
  */
35
36
  NODE_ID: 'noetic.node.id',
@@ -59,7 +60,7 @@ export const NoeticAttr = {
59
60
  CONTEXT_LIVE_TOKENS: 'noetic.context.live_tokens',
60
61
  /** Tokens spent superseding stale anchors. */
61
62
  CONTEXT_DELTA_TOKENS: 'noetic.context.delta_tokens',
62
- /** JSON array of `{ id, placement, served }` per contributing layer. */
63
+ /** JSON array of `{ id, placement, served, changed }` per contributing layer. */
63
64
  CONTEXT_LAYER_PLACEMENTS: 'noetic.context.layer_placements',
64
65
  /** JSON array of `{ id, rate, rebillTokens }` per contributing layer. */
65
66
  CONTEXT_LAYER_CHURN: 'noetic.context.layer_churn',
@@ -77,4 +78,19 @@ export const NoeticEvent = {
77
78
  LOOP_VERDICT: 'loop.verdict',
78
79
  /** A channel dropped data or is waiting with no timeout: `{ kind, channelName, message, capacity?, operation? }`. */
79
80
  CHANNEL_WARNING: 'channel.warning',
81
+ /**
82
+ * A layer's `onReturn` hook failed, so a spawn or inParallel path returned
83
+ * its result unchanged. Added to the child's span: `{ stepId, layerId,
84
+ * message }`. Defined in `@noetic-tools/context`, whose `returnLayers`
85
+ * emits it and cannot import core.
86
+ */
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,
80
96
  };