@noetic-tools/core 5.9.0 → 5.11.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 (42) 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 +13 -3
  6. package/dist/adapters/openrouter.js +43 -12
  7. package/dist/builders/dynamic-workflow.js +2 -1
  8. package/dist/builders/provide-builder.d.ts +6 -5
  9. package/dist/builders/spawn-builder.d.ts +6 -2
  10. package/dist/builders/step-builders.d.ts +9 -2
  11. package/dist/builders/step-builders.js +30 -2
  12. package/dist/builders/workflow-hydrator.js +1 -0
  13. package/dist/harness/agent-harness.d.ts +7 -1
  14. package/dist/harness/agent-harness.js +1 -0
  15. package/dist/harness/deps/context.d.ts +1 -1
  16. package/dist/harness/deps/context.js +1 -1
  17. package/dist/harness/deps/types.d.ts +1 -1
  18. package/dist/harness/model-call.js +114 -18
  19. package/dist/index.d.ts +9 -5
  20. package/dist/index.js +1 -1
  21. package/dist/interpreter/action-deps.d.ts +1 -1
  22. package/dist/interpreter/action-deps.js +1 -1
  23. package/dist/interpreter/action-types.d.ts +1 -1
  24. package/dist/interpreter/child-span.d.ts +5 -4
  25. package/dist/interpreter/child-span.js +7 -5
  26. package/dist/interpreter/context-assembly.d.ts +5 -4
  27. package/dist/interpreter/context-assembly.js +18 -14
  28. package/dist/interpreter/execute-action.d.ts +25 -5
  29. package/dist/interpreter/execute-action.js +100 -18
  30. package/dist/interpreter/execute-control.js +7 -0
  31. package/dist/interpreter/execute-decide.js +2 -2
  32. package/dist/interpreter/execute.js +22 -8
  33. package/dist/interpreter/step-dispatcher.js +1 -0
  34. package/dist/observability/genai-attributes.d.ts +33 -3
  35. package/dist/observability/genai-attributes.js +34 -4
  36. package/dist/runtime/tool-approval.d.ts +25 -0
  37. package/dist/runtime/tool-approval.js +67 -0
  38. package/dist/unstable.d.ts +1 -1
  39. package/dist/util/detached-handle.d.ts +4 -10
  40. package/dist/util/detached-handle.js +14 -23
  41. package/package.json +3 -3
  42. package/schema/noetic-workflow.schema.json +25 -0
@@ -2,13 +2,15 @@
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';
6
+ import { askApproval } from '../runtime/tool-approval.js';
5
7
  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';
8
+ 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
9
  import { isServerToolSpec, SteeringAction } from './action-types.js';
8
10
  import { openChildSpan, traceChild } from './child-span.js';
9
11
  import { cloneWithGuard } from './clone-guard.js';
10
12
  import { collectAllTools, deduplicateTools } from './collect-tools.js';
11
- import { prepareBandedView, stampAnchoringAttributes } from './context-assembly.js';
13
+ import { anchoringAttributes, prepareBandedView } from './context-assembly.js';
12
14
  import { trackUsage } from './message-helpers.js';
13
15
  import { wrapModelError } from './model-error.js';
14
16
  import { parseStructuredOutput } from './structured-output.js';
@@ -397,6 +399,7 @@ function buildModelRequest(params) {
397
399
  items: params.assembledItems,
398
400
  instructions: params.resolvedInstructions,
399
401
  params: step.params,
402
+ toolChoice: step.toolChoice,
400
403
  outputSchema: params.outputSchema,
401
404
  outputJsonSchema: params.step.outputJsonSchema,
402
405
  emit: step.emit,
@@ -405,6 +408,7 @@ function buildModelRequest(params) {
405
408
  layers,
406
409
  nodeId: step.id,
407
410
  parentSpan: ctx.span,
411
+ spanAttributes: params.spanAttributes,
408
412
  signal,
409
413
  };
410
414
  if (params.resolvedTools) {
@@ -523,7 +527,9 @@ export async function executeCallModel(step, input, ctx, layers) {
523
527
  systemPromptItems: [],
524
528
  budgets: budgetMap,
525
529
  });
526
- stampAnchoringAttributes(baseCtx.span, banded);
530
+ // Stamped once per assembly, like the cache judgement below: a steering
531
+ // retry re-sends the same view, so only the first attempt carries them.
532
+ let spanAttributes = anchoringAttributes(banded);
527
533
  let retries = 0;
528
534
  // Guidance from a steering retry rides at the very end of the view, after the
529
535
  // live band and the supersedes, rather than wherever history happens to put it.
@@ -548,7 +554,9 @@ export async function executeCallModel(step, input, ctx, layers) {
548
554
  outputSchema,
549
555
  serverToolSpecs,
550
556
  assembledItems,
557
+ spanAttributes,
551
558
  });
559
+ spanAttributes = undefined;
552
560
  const response = await baseCtx.harness.callModel(request).catch((e) => {
553
561
  throw wrapModelError(e, step.id, baseCtx);
554
562
  });
@@ -664,7 +672,7 @@ async function collectSpawnItems({ layers, parentExecutionCtx, childExecutionCtx
664
672
  export async function executeSpawn(step, input, ctx, executeStep, opts) {
665
673
  const baseCtx = frameworkCast(ctx);
666
674
  const layers = resolveLayersForSpawn(step, opts?.parentLayers);
667
- const childId = crypto.randomUUID();
675
+ const childId = opts?.childId ?? crypto.randomUUID();
668
676
  const childExecutionCtx = contextToExecCtx(baseCtx, {
669
677
  executionId: childId,
670
678
  depth: baseCtx.depth + 1,
@@ -729,6 +737,20 @@ export async function executeSpawn(step, input, ctx, executeStep, opts) {
729
737
  pathPrefix: baseCtx instanceof ContextImpl ? baseCtx.currentPath() : '',
730
738
  ledger: baseCtx instanceof ContextImpl ? baseCtx.ledger : undefined,
731
739
  });
740
+ // `childExecutionCtx` predates the spawn span; the child's hooks trace onto that span.
741
+ const childTracedCtx = {
742
+ ...childExecutionCtx,
743
+ trace: contextToExecCtx(childCtx).trace,
744
+ };
745
+ if (hasLayers && parentExecutionCtx) {
746
+ layerStore.adopt?.({
747
+ parentExecutionId: parentExecutionCtx.executionId,
748
+ ctx: childTracedCtx,
749
+ layers,
750
+ log: childCtx.itemLog,
751
+ itemSchemas: opts?.itemSchemas,
752
+ });
753
+ }
732
754
  try {
733
755
  return await traceChild(baseCtx, span, async () => {
734
756
  // Execute the child step. Its token/cost usage needs no merge here: every
@@ -743,11 +765,7 @@ export async function executeSpawn(step, input, ctx, executeStep, opts) {
743
765
  layers,
744
766
  stepId: step.id,
745
767
  parentCtx: parentExecutionCtx,
746
- // `childExecutionCtx` predates the spawn span; trace onto that span.
747
- childCtx: {
748
- ...childExecutionCtx,
749
- trace: span,
750
- },
768
+ childCtx: childTracedCtx,
751
769
  childLog: childCtx.itemLog,
752
770
  result: childOutput,
753
771
  store: layerStore,
@@ -787,18 +805,27 @@ function mergeLayers(existing, provided) {
787
805
  ];
788
806
  }
789
807
  /**
790
- * Executes a provide step by attaching context layers to the current context
791
- * without creating an isolated child context.
808
+ * Executes a withContext step by attaching context layers to the current
809
+ * context without creating an isolated child context.
792
810
  *
793
- * Unlike spawn, provide does not create a new itemLog or clone state.
811
+ * Unlike spawn, withContext does not create a new itemLog or clone state.
794
812
  * Events flow through to the parent in real-time.
813
+ *
814
+ * Layers whose ids the parent does not already have are scoped to the
815
+ * boundary: their `init` runs on entry, and on exit their `dispose` runs,
816
+ * their state is dropped, and their prompt-cache pins are removed so their
817
+ * output does not replay into later model calls. A provided layer that
818
+ * overrides a parent layer of the same id shares that id's state slot, so it
819
+ * is neither initialized nor disposed here.
795
820
  */
796
- export async function executeWithContext(step, input, ctx, executeStep) {
821
+ export async function executeWithContext(step, input, ctx, executeStep, opts) {
797
822
  const baseCtx = frameworkCast(ctx);
798
823
  const previousLayers = baseCtx.layers;
799
824
  const previousUnifiedTools = baseCtx.unifiedTools;
800
825
  const newLayers = resolveLayers(step);
801
826
  const mergedLayers = mergeLayers(previousLayers, newLayers);
827
+ const parentIds = new Set((previousLayers ?? []).map((l) => l.id));
828
+ const scopedLayers = newLayers.filter((l) => !parentIds.has(l.id));
802
829
  // Attach layers to the current context (no isolation)
803
830
  baseCtx.layers = mergedLayers;
804
831
  // Merge new layer-provided tools into the unified tool set
@@ -811,13 +838,36 @@ export async function executeWithContext(step, input, ctx, executeStep) {
811
838
  ]);
812
839
  }
813
840
  }
841
+ const layerStore = opts?.layerStore;
842
+ const execCtx = contextToExecCtx(baseCtx);
814
843
  try {
844
+ if (layerStore && opts?.storage && scopedLayers.length > 0) {
845
+ await initLayers({
846
+ layers: scopedLayers,
847
+ ctx: execCtx,
848
+ storage: opts.storage,
849
+ store: layerStore,
850
+ });
851
+ }
815
852
  return await executeStep(step.child, input, ctx);
816
853
  }
817
854
  finally {
818
855
  // Restore previous layers and unified tools so siblings are not affected
819
856
  baseCtx.layers = previousLayers;
820
857
  baseCtx.unifiedTools = previousUnifiedTools;
858
+ if (scopedLayers.length > 0) {
859
+ if (layerStore) {
860
+ await disposeLayers({
861
+ layers: scopedLayers,
862
+ ctx: execCtx,
863
+ store: layerStore,
864
+ scoped: true,
865
+ });
866
+ }
867
+ if (baseCtx.harness.contextCache) {
868
+ unpinLayers(baseCtx.harness.contextCache, lineageKey(execCtx), scopedLayers);
869
+ }
870
+ }
821
871
  }
822
872
  }
823
873
  //#endregion
@@ -859,8 +909,24 @@ async function consumeToolGenerator(params) {
859
909
  });
860
910
  }
861
911
  }
912
+ /**
913
+ * Runs an `invokeTool` step inside a `tool.call` span under `ctx.span`. The span
914
+ * covers validation, the steering gate, and execution, so a denied or failing
915
+ * call is traced with its error.
916
+ */
862
917
  export async function executeInvokeTool(step, input, ctx, harness, layers) {
863
918
  const baseCtx = frameworkCast(ctx);
919
+ const span = openChildSpan(baseCtx, 'tool.call', step.id);
920
+ span.setAttribute(ToolAttr.NAME, step.tool.name);
921
+ span.setAttribute(ToolAttr.NEEDS_APPROVAL, step.tool.needsApproval ?? false);
922
+ return traceChild(baseCtx, span, () => runInvokeTool(step, input, baseCtx, harness, layers, span));
923
+ }
924
+ /**
925
+ * Gates run in order — input validation, the `beforeToolCall` layers, then the
926
+ * harness approver for a tool that declares `needsApproval` — and a refusal at
927
+ * any gate throws `steering_denied` before the tool runs.
928
+ */
929
+ async function runInvokeTool(step, input, baseCtx, harness, layers, span) {
864
930
  const args = step.args ? Object.assign({}, input, step.args) : input;
865
931
  const parseResult = await validateSchema(step.tool.input, args);
866
932
  if (!parseResult.success) {
@@ -899,14 +965,30 @@ export async function executeInvokeTool(step, input, ctx, harness, layers) {
899
965
  },
900
966
  });
901
967
  };
968
+ const refuse = (decision) => {
969
+ emitCompleted(true, `Tool call denied: ${decision.guidance ?? 'steering rule violation'}`);
970
+ throw new NoeticErrorImpl({
971
+ kind: 'steering_denied',
972
+ guidance: decision.guidance,
973
+ });
974
+ };
902
975
  if (layers && layers.length > 0) {
903
976
  const decision = await harness.beforeToolCall(layers, step.tool.name, parsedArgs, baseCtx, step.id);
904
977
  if (decision.action !== SteeringAction.Allow) {
905
- emitCompleted(true, `Tool call denied: ${decision.guidance ?? 'steering rule violation'}`);
906
- throw new NoeticErrorImpl({
907
- kind: 'steering_denied',
908
- guidance: decision.guidance,
909
- });
978
+ refuse(decision);
979
+ }
980
+ }
981
+ if (step.tool.needsApproval) {
982
+ const approval = await askApproval({
983
+ harness,
984
+ toolName: step.tool.name,
985
+ toolArgs: parsedArgs,
986
+ callId: step.id,
987
+ ctx: baseCtx,
988
+ });
989
+ span.setAttribute(ToolAttr.APPROVAL, approval.outcome);
990
+ if (approval.decision.action !== SteeringAction.Allow) {
991
+ refuse(approval.decision);
910
992
  }
911
993
  }
912
994
  emitToolUi({
@@ -109,6 +109,13 @@ function createForkLayerBridge({ stepId, ctx, childContexts, opts, }) {
109
109
  store: layerStore,
110
110
  itemSchemas: opts?.itemSchemas,
111
111
  });
112
+ layerStore.adopt?.({
113
+ parentExecutionId: parentExecCtx.executionId,
114
+ ctx: childExecCtxs[index],
115
+ layers: layers ?? [],
116
+ log: childContexts[index].itemLog,
117
+ itemSchemas: opts?.itemSchemas,
118
+ });
112
119
  },
113
120
  settle(index, result) {
114
121
  return serialize(() => returnLayers({
@@ -1,7 +1,7 @@
1
1
  import { choiceValues, DecideOutputError, frameworkCast, hashString, NoeticConfigError, NoeticErrorImpl, scoreLevels, } from '@noetic-tools/types';
2
2
  import { z } from 'zod';
3
3
  import { GenAI, NoeticAttr } from '../observability/genai-attributes.js';
4
- import { allocateBudgets, assembleView, DECISION_PROJECTION, laneBase } from './action-deps.js';
4
+ import { allocateBudgets, assembleView, DECISION_PROJECTION, exportSpans, laneBase, } from './action-deps.js';
5
5
  import { resolveLazy } from './execute-action.js';
6
6
  import { trackUsage } from './message-helpers.js';
7
7
  import { wrapModelError } from './model-error.js';
@@ -61,7 +61,7 @@ export async function executeDecide(step, input, ctx, layers) {
61
61
  }
62
62
  finally {
63
63
  span.end();
64
- await baseCtx.harness.traceExporter.export([
64
+ await exportSpans(baseCtx.harness.traceExporter, [
65
65
  span,
66
66
  ]);
67
67
  }
@@ -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);
@@ -285,7 +290,7 @@ export async function execute(step, input, ctx) {
285
290
  result = await executeAcpAgent(step, input, stepCtx, baseCtx.layers);
286
291
  break;
287
292
  case 'invokeTool':
288
- result = await executeInvokeTool(step, input, stepCtx, baseCtx.harness);
293
+ result = await executeInvokeTool(step, input, stepCtx, baseCtx.harness, baseCtx.layers);
289
294
  break;
290
295
  case 'decide':
291
296
  result = await executeDecide(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,
@@ -12,6 +12,13 @@ export declare const GenAI: {
12
12
  export declare const ToolAttr: {
13
13
  readonly NAME: "tool.name";
14
14
  readonly NEEDS_APPROVAL: "tool.needs_approval";
15
+ /**
16
+ * How the approver settled a call to a tool that declares `needsApproval`:
17
+ * `approved`, `denied`, or `none_configured` (the harness has no approver,
18
+ * so the call ran unapproved). Absent when the call never reached the
19
+ * approval stage.
20
+ */
21
+ readonly APPROVAL: "tool.approval";
15
22
  };
16
23
  export declare const NoeticAttr: {
17
24
  /** Full JSON-serialised `WorkflowDocument` (the DAG, lossless). */
@@ -25,8 +32,8 @@ export declare const NoeticAttr: {
25
32
  /** JSON array of `{ from, to }` parent→child edges between declared nodes. */
26
33
  readonly WORKFLOW_EDGES: "noetic.workflow.edges";
27
34
  /**
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`
35
+ * Id of the step a span belongs to: the `callModel` step of an
36
+ * `llm.call`/`tool.call` (or the `invokeTool` step of its `tool.call`), the `decide` step of a `decide.call`, the `spawn`
30
37
  * step of a `spawn` span, the path step of an `inParallel.path` span.
31
38
  */
32
39
  readonly NODE_ID: "noetic.node.id";
@@ -56,7 +63,7 @@ export declare const NoeticAttr: {
56
63
  readonly CONTEXT_LIVE_TOKENS: "noetic.context.live_tokens";
57
64
  /** Tokens spent superseding stale anchors. */
58
65
  readonly CONTEXT_DELTA_TOKENS: "noetic.context.delta_tokens";
59
- /** JSON array of `{ id, placement, served }` per contributing layer. */
66
+ /** JSON array of `{ id, placement, served, changed }` per contributing layer. */
60
67
  readonly CONTEXT_LAYER_PLACEMENTS: "noetic.context.layer_placements";
61
68
  /** JSON array of `{ id, rate, rebillTokens }` per contributing layer. */
62
69
  readonly CONTEXT_LAYER_CHURN: "noetic.context.layer_churn";
@@ -66,6 +73,20 @@ export declare const NoeticAttr: {
66
73
  readonly DECISION_REFUSED: "noetic.decision.refused";
67
74
  /** Prefix for per-question attributes: `noetic.decision.<id>.value` etc. */
68
75
  readonly DECISION_PREFIX: "noetic.decision.";
76
+ /** Layer a `layer.hook` span belongs to. */
77
+ readonly LAYER_ID: "noetic.layer.id";
78
+ /** Hook a `layer.hook` span records (`init`, `recall`, `beforeToolCall`, …). */
79
+ readonly LAYER_HOOK: "noetic.layer.hook";
80
+ /** How the hook call ended: `ok`, `error`, `timeout`, or `skipped`. */
81
+ readonly LAYER_STATUS: "noetic.layer.status";
82
+ /** `recall` only: items the layer injected. */
83
+ readonly LAYER_ITEM_COUNT: "noetic.layer.item_count";
84
+ /** `recall` only: the layer's token budget. */
85
+ readonly LAYER_BUDGET_ALLOCATED: "noetic.layer.budget.allocated";
86
+ /** `recall` only: tokens the layer's output costs. */
87
+ readonly LAYER_BUDGET_USED: "noetic.layer.budget.used";
88
+ /** `recall` only: budget the layer left unspent. */
89
+ readonly LAYER_BUDGET_YIELDED: "noetic.layer.budget.yielded";
69
90
  };
70
91
  export declare const NoeticEvent: {
71
92
  /** One per loop iteration: `{ loop, iteration, stop, reason? }`. */
@@ -79,4 +100,13 @@ export declare const NoeticEvent: {
79
100
  * emits it and cannot import core.
80
101
  */
81
102
  readonly SPAWN_SUMMARY_FAILED: "spawn.summary_failed";
103
+ /**
104
+ * One per layer hook call, on the span of the context the hook runs in, when
105
+ * that context cannot open a `layer.hook` child span (`ExecutionContext.trace`
106
+ * has no `createSpan`): `{ layerId, hook, duration, status, itemCount?,
107
+ * budget.allocated?, budget.used?, budget.yielded?, error.message? }`. Also
108
+ * the name of that span. Defined in `@noetic-tools/context`, whose lifecycle
109
+ * emits it.
110
+ */
111
+ readonly LAYER_HOOK: "layer.hook";
82
112
  };
@@ -1,4 +1,4 @@
1
- import { SPAWN_SUMMARY_FAILED_EVENT } from '@noetic-tools/context';
1
+ import { LAYER_HOOK_EVENT, LayerHookAttr, 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',
@@ -14,6 +14,13 @@ export const GenAI = {
14
14
  export const ToolAttr = {
15
15
  NAME: 'tool.name',
16
16
  NEEDS_APPROVAL: 'tool.needs_approval',
17
+ /**
18
+ * How the approver settled a call to a tool that declares `needsApproval`:
19
+ * `approved`, `denied`, or `none_configured` (the harness has no approver,
20
+ * so the call ran unapproved). Absent when the call never reached the
21
+ * approval stage.
22
+ */
23
+ APPROVAL: 'tool.approval',
17
24
  };
18
25
  // Noetic-specific span attributes describing the static workflow graph (the
19
26
  // "potential paths" of the DAG) carried on the root `workflow.run` span.
@@ -29,8 +36,8 @@ export const NoeticAttr = {
29
36
  /** JSON array of `{ from, to }` parent→child edges between declared nodes. */
30
37
  WORKFLOW_EDGES: 'noetic.workflow.edges',
31
38
  /**
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`
39
+ * Id of the step a span belongs to: the `callModel` step of an
40
+ * `llm.call`/`tool.call` (or the `invokeTool` step of its `tool.call`), the `decide` step of a `decide.call`, the `spawn`
34
41
  * step of a `spawn` span, the path step of an `inParallel.path` span.
35
42
  */
36
43
  NODE_ID: 'noetic.node.id',
@@ -60,7 +67,7 @@ export const NoeticAttr = {
60
67
  CONTEXT_LIVE_TOKENS: 'noetic.context.live_tokens',
61
68
  /** Tokens spent superseding stale anchors. */
62
69
  CONTEXT_DELTA_TOKENS: 'noetic.context.delta_tokens',
63
- /** JSON array of `{ id, placement, served }` per contributing layer. */
70
+ /** JSON array of `{ id, placement, served, changed }` per contributing layer. */
64
71
  CONTEXT_LAYER_PLACEMENTS: 'noetic.context.layer_placements',
65
72
  /** JSON array of `{ id, rate, rebillTokens }` per contributing layer. */
66
73
  CONTEXT_LAYER_CHURN: 'noetic.context.layer_churn',
@@ -70,6 +77,20 @@ export const NoeticAttr = {
70
77
  DECISION_REFUSED: 'noetic.decision.refused',
71
78
  /** Prefix for per-question attributes: `noetic.decision.<id>.value` etc. */
72
79
  DECISION_PREFIX: 'noetic.decision.',
80
+ /** Layer a `layer.hook` span belongs to. */
81
+ LAYER_ID: LayerHookAttr.LAYER_ID,
82
+ /** Hook a `layer.hook` span records (`init`, `recall`, `beforeToolCall`, …). */
83
+ LAYER_HOOK: LayerHookAttr.HOOK,
84
+ /** How the hook call ended: `ok`, `error`, `timeout`, or `skipped`. */
85
+ LAYER_STATUS: LayerHookAttr.STATUS,
86
+ /** `recall` only: items the layer injected. */
87
+ LAYER_ITEM_COUNT: LayerHookAttr.ITEM_COUNT,
88
+ /** `recall` only: the layer's token budget. */
89
+ LAYER_BUDGET_ALLOCATED: LayerHookAttr.BUDGET_ALLOCATED,
90
+ /** `recall` only: tokens the layer's output costs. */
91
+ LAYER_BUDGET_USED: LayerHookAttr.BUDGET_USED,
92
+ /** `recall` only: budget the layer left unspent. */
93
+ LAYER_BUDGET_YIELDED: LayerHookAttr.BUDGET_YIELDED,
73
94
  };
74
95
  // Span event names. Steps that open no span of their own (e.g. `loop`) add
75
96
  // these to the enclosing `ctx.span`.
@@ -85,4 +106,13 @@ export const NoeticEvent = {
85
106
  * emits it and cannot import core.
86
107
  */
87
108
  SPAWN_SUMMARY_FAILED: SPAWN_SUMMARY_FAILED_EVENT,
109
+ /**
110
+ * One per layer hook call, on the span of the context the hook runs in, when
111
+ * that context cannot open a `layer.hook` child span (`ExecutionContext.trace`
112
+ * has no `createSpan`): `{ layerId, hook, duration, status, itemCount?,
113
+ * budget.allocated?, budget.used?, budget.yielded?, error.message? }`. Also
114
+ * the name of that span. Defined in `@noetic-tools/context`, whose lifecycle
115
+ * emits it.
116
+ */
117
+ LAYER_HOOK: LAYER_HOOK_EVENT,
88
118
  };
@@ -0,0 +1,25 @@
1
+ import type { AgentHarnessContract, Context, SteeringDecision } from '@noetic-tools/types';
2
+ /** How the approval stage settled a call, as recorded on its `tool.call` span. */
3
+ export declare const ApprovalOutcome: {
4
+ readonly Approved: "approved";
5
+ readonly Denied: "denied";
6
+ /** The harness has no approver, so the call ran unapproved. */
7
+ readonly NoneConfigured: "none_configured";
8
+ };
9
+ export type ApprovalOutcome = (typeof ApprovalOutcome)[keyof typeof ApprovalOutcome];
10
+ export interface ToolApproval {
11
+ outcome: ApprovalOutcome;
12
+ decision: SteeringDecision;
13
+ }
14
+ /**
15
+ * Ask the harness approver whether a call to a tool that declares
16
+ * `needsApproval` may run. With no approver configured the call runs, and the
17
+ * harness warns once per tool name. An approver that throws denies the call.
18
+ */
19
+ export declare function askApproval(params: {
20
+ harness: AgentHarnessContract;
21
+ toolName: string;
22
+ toolArgs: unknown;
23
+ callId?: string;
24
+ ctx: Context;
25
+ }): Promise<ToolApproval>;
@@ -0,0 +1,67 @@
1
+ import { SteeringAction } from '@noetic-tools/types';
2
+ //#region Types
3
+ /** How the approval stage settled a call, as recorded on its `tool.call` span. */
4
+ export const ApprovalOutcome = {
5
+ Approved: 'approved',
6
+ Denied: 'denied',
7
+ /** The harness has no approver, so the call ran unapproved. */
8
+ NoneConfigured: 'none_configured',
9
+ };
10
+ //#endregion
11
+ //#region Public API
12
+ /**
13
+ * Ask the harness approver whether a call to a tool that declares
14
+ * `needsApproval` may run. With no approver configured the call runs, and the
15
+ * harness warns once per tool name. An approver that throws denies the call.
16
+ */
17
+ export async function askApproval(params) {
18
+ const approver = params.harness.config.approveToolCall;
19
+ if (!approver) {
20
+ warnOnce(params.harness, params.toolName);
21
+ return {
22
+ outcome: ApprovalOutcome.NoneConfigured,
23
+ decision: {
24
+ action: SteeringAction.Allow,
25
+ },
26
+ };
27
+ }
28
+ try {
29
+ const decision = await approver({
30
+ toolName: params.toolName,
31
+ toolArgs: params.toolArgs,
32
+ callId: params.callId,
33
+ ctx: params.ctx,
34
+ });
35
+ return {
36
+ outcome: decision.action === SteeringAction.Allow
37
+ ? ApprovalOutcome.Approved
38
+ : ApprovalOutcome.Denied,
39
+ decision,
40
+ };
41
+ }
42
+ catch (e) {
43
+ return {
44
+ outcome: ApprovalOutcome.Denied,
45
+ decision: {
46
+ action: SteeringAction.Deny,
47
+ guidance: `approval for tool '${params.toolName}' failed: ${e instanceof Error ? e.message : String(e)}`,
48
+ },
49
+ };
50
+ }
51
+ }
52
+ //#endregion
53
+ //#region Helpers
54
+ const warned = new WeakMap();
55
+ function warnOnce(harness, toolName) {
56
+ let names = warned.get(harness);
57
+ if (!names) {
58
+ names = new Set();
59
+ warned.set(harness, names);
60
+ }
61
+ if (names.has(toolName)) {
62
+ return;
63
+ }
64
+ names.add(toolName);
65
+ console.warn(`[noetic] tool '${toolName}' needs approval, but harness '${harness.config.name}' has no approver, so its calls run unapproved. Set AgentHarness({ approveToolCall }) to approve or refuse them.`);
66
+ }
67
+ //#endregion
@@ -8,7 +8,7 @@
8
8
  */
9
9
  /** @unstable Budget allocation algorithm for context layer token budgets. */
10
10
  /** @unstable Layer state store type for managing per-layer state during execution. */
11
- export type { BudgetAllocation, BudgetLimits, LayerStateStore } from '@noetic-tools/context';
11
+ export type { BudgetAllocation, BudgetLimits, LayerStateStore, LiveChild, } from '@noetic-tools/context';
12
12
  /** @unstable Budget allocation and checking utilities. */
13
13
  /** @unstable Factory for creating layer state stores. */
14
14
  /** @unstable View assembly algorithm that converges context layer outputs into the LLM context. */
@@ -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
  }