@noetic-tools/core 5.10.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.
@@ -1,6 +1,7 @@
1
1
  import type { ContextLayer } from '@noetic-tools/context';
2
2
  import type { AgentHarnessContract, Context, Item, LLMResponse, StandardSchemaV1, Tool } from '@noetic-tools/types';
3
3
  import type * as OpenRouterAgent from '@openrouter/agent';
4
+ import type { ApprovalOutcome } from '../runtime/tool-approval.js';
4
5
  import type { EmbedFn } from '../types/embed.js';
5
6
  type ProviderOutputItem = OpenRouterAgent.OpenResponsesResult['output'][number];
6
7
  type OpenRouterInputItem = OpenRouterAgent.EasyInputMessage | OpenRouterAgent.FunctionCallItem | OpenRouterAgent.FunctionCallOutputItem | ProviderOutputItem;
@@ -64,12 +65,21 @@ export interface ExecuteToolCallParams {
64
65
  /** The model's `function_call` id — keys this call's tool-UI region. */
65
66
  callId?: string;
66
67
  }
67
- /** @internal Execute a single tool call with steering checks. */
68
- export declare function executeToolCall(params: ExecuteToolCallParams): Promise<{
68
+ /** @internal What one model-requested tool call produced. */
69
+ export interface ToolCallResult {
69
70
  output: string;
70
71
  result?: unknown;
71
72
  error?: boolean;
72
- }>;
73
+ /** Set when the tool declares `needsApproval` and the call reached the approver. */
74
+ approval?: ApprovalOutcome;
75
+ }
76
+ /**
77
+ * @internal Execute a single tool call. Gates run in order: the
78
+ * `beforeToolCall` layers, input validation, then — for a tool that declares
79
+ * `needsApproval` — the harness approver. A refusal at any gate becomes an
80
+ * error tool result; the tool never runs.
81
+ */
82
+ export declare function executeToolCall(params: ExecuteToolCallParams): Promise<ToolCallResult>;
73
83
  /**
74
84
  * Creates an `EmbedFn` that calls the OpenRouter embeddings API.
75
85
  *
@@ -1,5 +1,6 @@
1
1
  import { frameworkCast, isAssistantMessage, isStandardJsonSchema, isZodSchema, NoeticConfigError, SteeringAction, validateSchema, } from '@noetic-tools/types';
2
2
  import { z } from 'zod';
3
+ import { askApproval } from '../runtime/tool-approval.js';
3
4
  import { buildToolExecutionContext } from '../runtime/tool-context.js';
4
5
  import { emitToolUi } from '../runtime/tool-ui.js';
5
6
  const EmbeddingsResponseSchema = z.object({
@@ -293,7 +294,12 @@ function isAsyncGenerator(value) {
293
294
  }
294
295
  return Symbol.asyncIterator in value;
295
296
  }
296
- /** @internal Execute a single tool call with steering checks. */
297
+ /**
298
+ * @internal Execute a single tool call. Gates run in order: the
299
+ * `beforeToolCall` layers, input validation, then — for a tool that declares
300
+ * `needsApproval` — the harness approver. A refusal at any gate becomes an
301
+ * error tool result; the tool never runs.
302
+ */
297
303
  export async function executeToolCall(params) {
298
304
  // Model sees sanitised tool names (see `sanitizeToolNameForWire`). Match
299
305
  // against both the original and sanitised name so internal identity (e.g.
@@ -309,17 +315,8 @@ export async function executeToolCall(params) {
309
315
  }
310
316
  if (params.layers && params.layers.length > 0) {
311
317
  const decision = await params.harness.beforeToolCall(params.layers, params.toolName, params.args, params.context, params.callId);
312
- if (decision.action === SteeringAction.Deny) {
313
- return {
314
- output: `Tool call denied: ${decision.guidance ?? 'steering rule violation'}`,
315
- error: true,
316
- };
317
- }
318
- if (decision.action === SteeringAction.Guide) {
319
- return {
320
- output: `Tool call redirected: ${decision.guidance}`,
321
- error: true,
322
- };
318
+ if (decision.action !== SteeringAction.Allow) {
319
+ return refusedResult(decision);
323
320
  }
324
321
  }
325
322
  const validated = await validateSchema(matchedTool.input, params.args);
@@ -330,6 +327,40 @@ export async function executeToolCall(params) {
330
327
  };
331
328
  }
332
329
  const parsedArgs = validated.value;
330
+ const approval = matchedTool.needsApproval
331
+ ? await askApproval({
332
+ harness: params.harness,
333
+ toolName: matchedTool.name,
334
+ toolArgs: parsedArgs,
335
+ callId: params.callId,
336
+ ctx: params.context,
337
+ })
338
+ : undefined;
339
+ if (approval && approval.decision.action !== SteeringAction.Allow) {
340
+ return {
341
+ ...refusedResult(approval.decision),
342
+ approval: approval.outcome,
343
+ };
344
+ }
345
+ const executed = await runMatchedTool(params, matchedTool, parsedArgs);
346
+ return {
347
+ ...executed,
348
+ approval: approval?.outcome,
349
+ };
350
+ }
351
+ function refusedResult(decision) {
352
+ if (decision.action === SteeringAction.Guide) {
353
+ return {
354
+ output: `Tool call redirected: ${decision.guidance}`,
355
+ error: true,
356
+ };
357
+ }
358
+ return {
359
+ output: `Tool call denied: ${decision.guidance ?? 'steering rule violation'}`,
360
+ error: true,
361
+ };
362
+ }
363
+ async function runMatchedTool(params, matchedTool, parsedArgs) {
333
364
  const toolCtx = buildToolExecutionContext(params.context, params.harness);
334
365
  const callId = params.callId;
335
366
  const uiBase = callId !== undefined
@@ -2,6 +2,7 @@
2
2
  * Pattern that lets an LLM generate a workflow as JSON during execution,
3
3
  * then hydrates and runs it within the same harness session.
4
4
  */
5
+ import { exportSpans } from '@noetic-tools/context';
5
6
  import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
6
7
  import { NoeticAttr } from '../observability/genai-attributes.js';
7
8
  import { WorkflowDocumentSchema, workflowDepth, workflowGraph } from '../schemas/workflow.js';
@@ -161,7 +162,7 @@ export async function parseAndRunWorkflow(opts) {
161
162
  }
162
163
  finally {
163
164
  runSpan.end();
164
- await opts.harness.traceExporter.export([
165
+ await exportSpans(opts.harness.traceExporter, [
165
166
  runSpan,
166
167
  ]);
167
168
  }
@@ -1,5 +1,5 @@
1
1
  import type { ContextData } from '@noetic-tools/context';
2
- import type { AcpAgent, AcpClientCapabilityConfig, AcpContentBlock, AcpMcpServer, AcpPermissionHandler, AcpPermissionPolicy, AcpSessionPolicy, Context, Lazy, ModelParams, OutputCodec, RetryPolicy, ServerToolSpec, StandardSchemaV1, StepAcpAgent, StepCallModel, StepInvokeTool, StepReplay, StepRunCode, SubprocessAdapter, Tool } from '@noetic-tools/types';
2
+ import type { AcpAgent, AcpClientCapabilityConfig, AcpContentBlock, AcpMcpServer, AcpPermissionHandler, AcpPermissionPolicy, AcpSessionPolicy, Context, Lazy, ModelParams, OutputCodec, RetryPolicy, ServerToolSpec, StandardSchemaV1, StepAcpAgent, StepCallModel, StepInvokeTool, StepReplay, StepRunCode, SubprocessAdapter, Tool, ToolChoice } from '@noetic-tools/types';
3
3
  export interface RunCodeOpts<TContext, I, O> extends StepReplay<TContext, I> {
4
4
  id: string;
5
5
  execute: (input: I, ctx: Context<TContext>) => Promise<O>;
@@ -23,6 +23,11 @@ export interface CallModelOpts<TContext, O, I = unknown> extends StepReplay<TCon
23
23
  * server tool the provider executes, e.g. web search/fetch).
24
24
  */
25
25
  tools?: Lazy<(Tool | ServerToolSpec)[] | undefined, TContext>;
26
+ /**
27
+ * How the model may use its tools: `'auto'` (default), `'required'`,
28
+ * `'none'`, or `{ tool: name }` to force one client tool from `tools`.
29
+ */
30
+ toolChoice?: ToolChoice;
26
31
  /** Structured output: a Standard Schema (Zod, Valibot, …) or a streaming `OutputCodec` (e.g. OpenUI Lang). */
27
32
  output?: StandardSchemaV1<unknown, O> | OutputCodec<O>;
28
33
  /**
@@ -94,11 +99,13 @@ export declare function runCode<TContext = ContextData, I = unknown, O = unknown
94
99
  * @param opts.instructions - Optional system prompt; eager string or `(ctx) => string | undefined` getter.
95
100
  * @param opts.tools - Optional tools; eager array or `(ctx) => Tool[] | undefined` getter.
96
101
  * @param opts.output - Optional Zod schema enabling structured output parsing.
102
+ * @param opts.toolChoice - Optional tool choice: `'auto'` (default), `'required'`, `'none'`, or `{ tool: name }`.
97
103
  * @param opts.params - Optional model parameters (temperature, topP, maxTokens, serviceTier).
98
104
  * @returns A `StepCallModel` that can be composed into larger pipelines. The step
99
105
  * is auto-registered in the shared step registry.
100
106
  * @throws `NoeticConfigError` with code `EMPTY_STEP_ID` if `id` is empty.
101
107
  * @throws `NoeticConfigError` with code `MISSING_MODEL` if an eager `model` string is empty. Function-form models are validated at step execution.
108
+ * @throws `NoeticConfigError` with code `UNKNOWN_TOOL_CHOICE` if `toolChoice` forces a tool missing from an eager `tools` array.
102
109
  */
103
110
  export declare function callModel<TContext = ContextData, I = unknown, O = unknown>(opts: CallModelOpts<TContext, O, I>): StepCallModel<TContext, I, O>;
104
111
  /**
@@ -1,4 +1,4 @@
1
- import { NoeticConfigError } from '@noetic-tools/types';
1
+ import { isServerToolSpec, NoeticConfigError } from '@noetic-tools/types';
2
2
  import { getDefaultRegistrar } from '../types/step-registrar.js';
3
3
  //#endregion
4
4
  //#region ACP agent builder helper
@@ -31,6 +31,31 @@ function validateAcpAgentOpts(opts) {
31
31
  });
32
32
  }
33
33
  }
34
+ /**
35
+ * A forced tool must be one the step offers. Only an eager `tools` array can be
36
+ * checked here; a getter's tools are checked when the request is built.
37
+ */
38
+ function validateToolChoice(opts) {
39
+ const choice = opts.toolChoice;
40
+ if (typeof choice !== 'object' || !Array.isArray(opts.tools)) {
41
+ return;
42
+ }
43
+ const names = opts.tools.flatMap((entry) => isServerToolSpec(entry)
44
+ ? []
45
+ : [
46
+ entry.name,
47
+ ]);
48
+ if (names.includes(choice.tool)) {
49
+ return;
50
+ }
51
+ throw new NoeticConfigError({
52
+ code: 'UNKNOWN_TOOL_CHOICE',
53
+ message: `callModel(${JSON.stringify(opts.id)}) forces tool ${JSON.stringify(choice.tool)}, which is not in its tools.`,
54
+ hint: names.length > 0
55
+ ? `Force one of the step's tools (${names.join(', ')}), or add '${choice.tool}' to \`tools\`.`
56
+ : `Add '${choice.tool}' to \`tools\`, or drop \`toolChoice\`.`,
57
+ });
58
+ }
34
59
  //#endregion
35
60
  //#region Builders
36
61
  /**
@@ -78,11 +103,13 @@ export function runCode(opts) {
78
103
  * @param opts.instructions - Optional system prompt; eager string or `(ctx) => string | undefined` getter.
79
104
  * @param opts.tools - Optional tools; eager array or `(ctx) => Tool[] | undefined` getter.
80
105
  * @param opts.output - Optional Zod schema enabling structured output parsing.
106
+ * @param opts.toolChoice - Optional tool choice: `'auto'` (default), `'required'`, `'none'`, or `{ tool: name }`.
81
107
  * @param opts.params - Optional model parameters (temperature, topP, maxTokens, serviceTier).
82
108
  * @returns A `StepCallModel` that can be composed into larger pipelines. The step
83
109
  * is auto-registered in the shared step registry.
84
110
  * @throws `NoeticConfigError` with code `EMPTY_STEP_ID` if `id` is empty.
85
111
  * @throws `NoeticConfigError` with code `MISSING_MODEL` if an eager `model` string is empty. Function-form models are validated at step execution.
112
+ * @throws `NoeticConfigError` with code `UNKNOWN_TOOL_CHOICE` if `toolChoice` forces a tool missing from an eager `tools` array.
86
113
  */
87
114
  export function callModel(opts) {
88
115
  if (!opts.id || opts.id.trim() === '') {
@@ -102,6 +129,7 @@ export function callModel(opts) {
102
129
  hint: "Pass a model identifier, e.g. model: 'anthropic/claude-sonnet-4-20250514'.",
103
130
  });
104
131
  }
132
+ validateToolChoice(opts);
105
133
  const built = {
106
134
  kind: 'callModel',
107
135
  ...opts,
@@ -88,6 +88,7 @@ function hydrateCallModelNode(node, ctx) {
88
88
  model: node.model ?? 'openai/gpt-4o',
89
89
  instructions: node.instructions,
90
90
  tools: combined.length > 0 ? combined : undefined,
91
+ toolChoice: node.toolChoice,
91
92
  params: node.params,
92
93
  output: resolveOutputCodec(node.output, node.id, ctx),
93
94
  });
@@ -4,7 +4,7 @@ import type { LayerStateStore, RecallCache } from './deps/context.js';
4
4
  import type { DetachedSpawnOverrides } from './deps/interpreter.js';
5
5
  import type { CheckpointStore, EventBroadcaster, RestoreCheckpointOptions, StepLedgerRetention, StepLedgerStore } from './deps/runtime.js';
6
6
  import { ChannelStore } from './deps/runtime.js';
7
- import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, Channel, ChannelHandle, Context, ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, LLMResponse, LlmProviderConfig, ProjectionPolicy, RecallLayerOutput, RecallOptions, SessionScope, SessionUsage, ShellAdapter, Span, SteeringDecision, Step, StorageAdapter, StreamEvent, StreamingItem, SubprocessAdapter, Tool, TraceExporter, ZodType } from './deps/types.js';
7
+ import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, Channel, ChannelHandle, Context, ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, LLMResponse, LlmProviderConfig, ProjectionPolicy, RecallLayerOutput, RecallOptions, SessionScope, SessionUsage, ShellAdapter, Span, SteeringDecision, Step, StorageAdapter, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, ZodType } from './deps/types.js';
8
8
  export { createStreamIdleWatchdog } from './model-call.js';
9
9
  /**
10
10
  * Storage-scoped environment configuration for `AgentHarness`.
@@ -90,6 +90,12 @@ interface AgentHarnessOpts<TParams extends Record<string, unknown> = Record<stri
90
90
  initialCwd?: string;
91
91
  /** Default model for `decide` steps. */
92
92
  decisionModel?: string;
93
+ /**
94
+ * Approves or refuses calls to tools that declare `needsApproval`, after the
95
+ * `beforeToolCall` layers allow them. Without one, those calls run
96
+ * unapproved and the harness warns once per tool name.
97
+ */
98
+ approveToolCall?: ToolApprover;
93
99
  /** @internal Test-only escape hatch to inject a mock callModel implementation. */
94
100
  _testCallModel?: (request: CallModelRequest) => Promise<LLMResponse>;
95
101
  /** @internal Test-only escape hatch to inject a mock decide implementation. */
@@ -306,6 +306,7 @@ export class AgentHarness {
306
306
  forceAtomicRecall: opts.forceAtomicRecall,
307
307
  contextCache: opts.contextCache,
308
308
  decisionModel: opts.decisionModel,
309
+ approveToolCall: opts.approveToolCall,
309
310
  };
310
311
  this.fs = environment?.fs ?? createInMemoryFsAdapter();
311
312
  this.shell = environment?.shell ?? createInMemoryShellAdapter();
@@ -1,2 +1,2 @@
1
1
  export type { LayerStateStore, RecallCache } from '@noetic-tools/context';
2
- export { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, initLayers, notifyDecision, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from '@noetic-tools/context';
2
+ export { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, exportSpans, initLayers, notifyDecision, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from '@noetic-tools/context';
@@ -1 +1 @@
1
- export { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, initLayers, notifyDecision, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from '@noetic-tools/context';
1
+ export { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, exportSpans, initLayers, notifyDecision, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from '@noetic-tools/context';
@@ -1,4 +1,4 @@
1
1
  export type { ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, ExecutionContext, ProjectionPolicy, StorageAdapter, } from '@noetic-tools/context';
2
- export type { AcpKeepAlive, AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, Channel, ChannelHandle, Context, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, ItemSchemaExtensions, LLMResponse, LlmProviderConfig, RecallLayerOutput, RecallOptions, SessionScope, SessionUsage, ShellAdapter, Span, SteeringDecision, Step, StreamEvent, StreamingItem, SubprocessAdapter, Tool, TraceExporter, } from '@noetic-tools/types';
2
+ export type { AcpKeepAlive, AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, Channel, ChannelHandle, Context, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, ItemSchemaExtensions, LLMResponse, LlmProviderConfig, RecallLayerOutput, RecallOptions, SessionScope, SessionUsage, ShellAdapter, Span, SteeringDecision, Step, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, } from '@noetic-tools/types';
3
3
  export { SteeringAction } from '@noetic-tools/types';
4
4
  export type { ZodType } from 'zod';
@@ -1,9 +1,10 @@
1
- import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
1
+ import { frameworkCast, NoeticConfigError, ToolChoiceMode } from '@noetic-tools/types';
2
2
  import { serverTool } from '@openrouter/agent';
3
3
  import { convertTools, executeToolCall, extractOutputItems, extractSystemInstruction, extractUsage, itemsToInput, resolveWireJsonSchema, sanitizeToolNameForWire, } from '../adapters/openrouter.js';
4
4
  import { isFunctionCall } from '../interpreter/typeguards.js';
5
5
  import { GenAI, NoeticAttr, ToolAttr } from '../observability/genai-attributes.js';
6
6
  import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
7
+ import { exportSpans } from './deps/context.js';
7
8
  import { buildItemSchemaRegistry, createToolResultItem } from './model-schema.js';
8
9
  const MAX_TOOL_ROUNDS = 32;
9
10
  const MAX_RECOVERY_CONTINUATIONS = 3;
@@ -226,7 +227,12 @@ function prepareModelRequest(request, agentName) {
226
227
  remaining,
227
228
  broadcaster,
228
229
  sdkTools: sdkTools.length > 0 ? sdkTools : undefined,
229
- toolChoice: clientSdkTools.length > 0 ? allowedToolsChoice(request, allowedTools) : undefined,
230
+ toolChoice: roundToolChoices({
231
+ request,
232
+ allowedTools,
233
+ sendsClientTools: clientSdkTools.length > 0,
234
+ sendsTools: sdkTools.length > 0,
235
+ }),
230
236
  allowedTools,
231
237
  emitIfAllowed(eventType, data) {
232
238
  if (!shouldEmit(request.emit, eventType, data)) {
@@ -241,18 +247,60 @@ function prepareModelRequest(request, agentName) {
241
247
  },
242
248
  };
243
249
  }
250
+ function roundToolChoices(scope) {
251
+ const choice = scope.request.toolChoice ?? ToolChoiceMode.Auto;
252
+ return {
253
+ first: wireToolChoice(scope, choice),
254
+ rest: wireToolChoice(scope, choice === ToolChoiceMode.None ? choice : ToolChoiceMode.Auto),
255
+ };
256
+ }
244
257
  /**
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`).
258
+ * Map a `toolChoice` onto the wire, inside the step's restriction.
259
+ * A restricted call narrows with an `allowed_tools` choice (plus the step's
260
+ * server tools) rather than by trimming `tools`, so the request keeps the
261
+ * shared cache prefix. `none` keeps the tools too, for the same reason. A call
262
+ * that sends no tools sends no choice.
263
+ *
264
+ * @throws NoeticConfigError `UNKNOWN_TOOL_CHOICE` when `{ tool }` names a tool
265
+ * this call cannot run.
248
266
  */
249
- function allowedToolsChoice(request, allowedTools) {
250
- if (!request.allowedToolNames) {
267
+ function wireToolChoice(scope, choice) {
268
+ const { request, allowedTools } = scope;
269
+ if (typeof choice === 'object') {
270
+ return forcedToolChoice(choice.tool, allowedTools);
271
+ }
272
+ if (!scope.sendsTools) {
251
273
  return undefined;
252
274
  }
275
+ if (choice === ToolChoiceMode.None) {
276
+ return 'none';
277
+ }
278
+ if (request.allowedToolNames && scope.sendsClientTools) {
279
+ return allowedToolsChoice(request, allowedTools, choice);
280
+ }
281
+ return choice === ToolChoiceMode.Required ? 'required' : undefined;
282
+ }
283
+ /** Force one function tool. It must be one the call may run. */
284
+ function forcedToolChoice(name, allowedTools) {
285
+ const tool = allowedTools.find((candidate) => candidate.name === name);
286
+ if (!tool) {
287
+ const offered = allowedTools.map((t) => t.name).join(', ') || 'none';
288
+ throw new NoeticConfigError({
289
+ code: 'UNKNOWN_TOOL_CHOICE',
290
+ message: `toolChoice forces tool ${JSON.stringify(name)}, which this model call cannot run.`,
291
+ hint: `Force a tool the call offers (offered: ${offered}), or give '${name}' to the step or a context layer.`,
292
+ });
293
+ }
294
+ return {
295
+ type: 'function',
296
+ name: sanitizeToolNameForWire(tool.name),
297
+ };
298
+ }
299
+ /** Restrict the model to `allowedTools` (plus the step's server tools). */
300
+ function allowedToolsChoice(request, allowedTools, mode) {
253
301
  return {
254
302
  type: 'allowed_tools',
255
- mode: 'auto',
303
+ mode,
256
304
  tools: [
257
305
  ...allowedTools.map((tool) => ({
258
306
  type: 'function',
@@ -335,10 +383,13 @@ class CallSpanCollector {
335
383
  span.end();
336
384
  }
337
385
  /** Open and immediately close a tool-call span under the given model span. */
338
- recordToolSpan(parent, toolName, needsApproval) {
386
+ recordToolSpan(parent, toolName, needsApproval, approval) {
339
387
  const span = this.harness.createSpan('tool.call', parent);
340
388
  span.setAttribute(ToolAttr.NAME, toolName);
341
389
  span.setAttribute(ToolAttr.NEEDS_APPROVAL, needsApproval);
390
+ if (approval !== undefined) {
391
+ span.setAttribute(ToolAttr.APPROVAL, approval);
392
+ }
342
393
  this.stampNode(span);
343
394
  span.end();
344
395
  this.spans.push(span);
@@ -348,7 +399,7 @@ class CallSpanCollector {
348
399
  if (this.spans.length === 0) {
349
400
  return;
350
401
  }
351
- await this.exporter.export(this.spans);
402
+ await exportSpans(this.exporter, this.spans);
352
403
  }
353
404
  }
354
405
  export class AgentHarnessModelCaller {
@@ -476,7 +527,7 @@ export class AgentHarnessModelCaller {
476
527
  input: modelInput,
477
528
  instructions: prepared.instructions,
478
529
  tools: prepared.sdkTools,
479
- toolChoice: prepared.toolChoice,
530
+ toolChoice: round === 0 ? prepared.toolChoice.first : prepared.toolChoice.rest,
480
531
  temperature: request.params?.temperature,
481
532
  maxOutputTokens: request.params?.maxTokens,
482
533
  topP: request.params?.topP,
@@ -735,8 +786,7 @@ export class AgentHarnessModelCaller {
735
786
  break;
736
787
  }
737
788
  const toolForCall = findTool(allowedTools, fc.name);
738
- spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false);
739
- await this.executeFunctionCall({
789
+ const approval = await this.executeFunctionCall({
740
790
  fc,
741
791
  request,
742
792
  allowedTools,
@@ -744,6 +794,7 @@ export class AgentHarnessModelCaller {
744
794
  conversationInput,
745
795
  emitIfAllowed: params.emitIfAllowed,
746
796
  });
797
+ spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false, approval);
747
798
  }
748
799
  params.emitIfAllowed('tool_round_completed', {
749
800
  round: params.round,
@@ -769,7 +820,7 @@ export class AgentHarnessModelCaller {
769
820
  conversationInput,
770
821
  emitIfAllowed: params.emitIfAllowed,
771
822
  });
772
- return;
823
+ return undefined;
773
824
  }
774
825
  if (!request.tools) {
775
826
  throw new Error(`executeFunctionCall invoked without tools on CallModelRequest (tool name: ${fc.name}).`);
@@ -810,6 +861,7 @@ export class AgentHarnessModelCaller {
810
861
  error: toolResult.error === true,
811
862
  output: toolResult.output,
812
863
  });
864
+ return toolResult.approval;
813
865
  }
814
866
  recordMalformedToolCall(params) {
815
867
  const { fc, request, allowedTools, allItems, conversationInput } = params;
package/dist/index.d.ts CHANGED
@@ -119,9 +119,9 @@ export { MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDo
119
119
  export type { Channel, ChannelHandle, ExternalChannel } from '@noetic-tools/types';
120
120
  /** @public */
121
121
  /** @public */
122
- export type { InferSchemaInput, InferSchemaOutput, InputSchemaConfig, LLMResponse, LlmProviderConfig, ModelParams, RetryPolicy, RoundUsage, SchemaValidationFailure, SchemaValidationResult, SchemaValidationSuccess, ServerToolSpec, StandardJSONSchemaV1, StandardSchemaV1, StepMeta, TokenUsage, Tool, ToolContextDeclaration, UsageCharge, } from '@noetic-tools/types';
122
+ export type { InferSchemaInput, InferSchemaOutput, InputSchemaConfig, LLMResponse, LlmProviderConfig, ModelParams, RetryPolicy, RoundUsage, SchemaValidationFailure, SchemaValidationResult, SchemaValidationSuccess, ServerToolSpec, StandardJSONSchemaV1, StandardSchemaV1, StepMeta, TokenUsage, Tool, ToolChoice, ToolContextDeclaration, UsageCharge, } from '@noetic-tools/types';
123
123
  /** @public */
124
- export { isServerToolSpec, isStandardJsonSchema, isZodSchema, ServiceTier, standardIssuesToZodError, validateSchema, } from '@noetic-tools/types';
124
+ export { isServerToolSpec, isStandardJsonSchema, isZodSchema, ServiceTier, standardIssuesToZodError, ToolChoiceMode, validateSchema, } from '@noetic-tools/types';
125
125
  /** @public */
126
126
  /** @public */
127
127
  /** @public */
@@ -143,11 +143,11 @@ export type { NoeticError } from '@noetic-tools/types';
143
143
  /** @public */
144
144
  export type { ContentPart, DeveloperMessageExtensionItem, ExecuteInput, ExtendedItem, ExtensionItem, FileSearchItem, FunctionCallItem, FunctionCallOutputItem, ImageGenerationItem, InferExtendedItem, InputContentPart, InputFilePart, InputImagePart, InputMessageItem, InputTextPart, Item, ItemBase, ItemSchemaExtensions, MessageItem, OutputItem, OutputTextPart, ReasoningItem, ReasoningTextPart, RefusalPart, ServerToolItem, SummaryTextPart, WebSearchItem, } from '@noetic-tools/types';
145
145
  /** @public */
146
- export type { BudgetConfig, CompleteParams, ContextConfig, ContextData, ContextLayer, ContextLayerHooks, DisposeParams, InferContext, InferContextShape, InitParams, InitResult, LayerDataDecl, LayerFunctionDecl, LayerPlacement, LayerProvides, LayerTimeouts, ProjectionPolicy, RecallParams, RecallResult, RenderDeltaParams, ReturnParams, ReturnResult, ScopedStorage, SpawnParams, SpawnResult, StorageAdapter, StoreParams, StoreResult, } from '@noetic-tools/context';
146
+ export type { BudgetConfig, CompleteParams, ContextConfig, ContextData, ContextLayer, ContextLayerHooks, DisposeParams, InferContext, InferContextShape, InitParams, InitResult, LayerDataDecl, LayerFunctionDecl, LayerPlacement, LayerProvides, LayerTimeouts, ParentUpdateParams, ParentUpdateResult, ProjectionPolicy, RecallParams, RecallResult, RenderDeltaParams, ReturnParams, ReturnResult, ScopedStorage, SpawnParams, SpawnResult, StorageAdapter, StoreParams, StoreResult, } from '@noetic-tools/context';
147
147
  /** @public */
148
148
  export { Slot } from '@noetic-tools/context';
149
149
  /** @public */
150
- export type { ContextScope, ExecutionContext, ExecutionOutcome, LayerCallModelRequest, } from '@noetic-tools/types';
150
+ export type { ContextScope, ExecutionContext, ExecutionOutcome, ExecutionSpan, LayerCallModelRequest, } from '@noetic-tools/types';
151
151
  /** @public */
152
152
  export type { LayerTraceSpan, Span, TraceExporter } from '@noetic-tools/types';
153
153
  /** @public */
@@ -155,7 +155,7 @@ export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent
155
155
  /** @public */
156
156
  export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, ExecuteOptions, HarnessJudgmentContract, HarnessStatus, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, SessionScope, SessionUsage, } from '@noetic-tools/types';
157
157
  /** @public */
158
- export type { AfterModelCallParams, AfterModelCallResult, BeforeToolCallParams, BeforeToolCallResult, LedgerEntry, SteeringConfig, SteeringDecision, SteeringRule, SteeringState, } from '@noetic-tools/types';
158
+ export type { AfterModelCallParams, AfterModelCallResult, ApproveToolCallParams, BeforeToolCallParams, BeforeToolCallResult, LedgerEntry, SteeringConfig, SteeringDecision, SteeringRule, SteeringState, ToolApprover, } from '@noetic-tools/types';
159
159
  /** @public */
160
160
  export { LedgerEntryKind, SteeringAction } from '@noetic-tools/types';
161
161
  /** @public */
package/dist/index.js CHANGED
@@ -90,7 +90,7 @@ export { defaultItemSchemaRegistry, ItemSchema, ItemSchemaRegistry } from '@noet
90
90
  /** @public */
91
91
  export { MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDocumentSchema, WorkflowNodeSchema, walkWorkflow, workflowDepth, } from './schemas/workflow.js';
92
92
  /** @public */
93
- export { isServerToolSpec, isStandardJsonSchema, isZodSchema, ServiceTier, standardIssuesToZodError, validateSchema, } from '@noetic-tools/types';
93
+ export { isServerToolSpec, isStandardJsonSchema, isZodSchema, ServiceTier, standardIssuesToZodError, ToolChoiceMode, validateSchema, } from '@noetic-tools/types';
94
94
  /** @public */
95
95
  export { getToolCwd, setToolCwd, snapshotCwdState } from './runtime/cwd-helpers.js';
96
96
  /** @public */
@@ -1,5 +1,5 @@
1
1
  export type { LayerServeInfo, LayerStateStore } from '@noetic-tools/context';
2
- export { allocateBudgets, assembleView, churnFor, churnRate, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DECISION_PROJECTION, DEFAULT_PROJECTION, disposeLayers, initLayers, lineageKey, noteCacheOutcome, openEpoch, pin, pinKey, reanchorReason, resolveCacheConfig, resolveLayerTools, returnLayers, spawnLayers, unpinLayers, } from '@noetic-tools/context';
2
+ export { allocateBudgets, assembleView, churnFor, churnRate, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DECISION_PROJECTION, DEFAULT_PROJECTION, disposeLayers, exportSpans, initLayers, lineageKey, noteCacheOutcome, openEpoch, pin, pinKey, reanchorReason, resolveCacheConfig, resolveLayerTools, returnLayers, spawnLayers, unpinLayers, } from '@noetic-tools/context';
3
3
  export type { ItemSchemaRegistry } from '@noetic-tools/types';
4
4
  export { defaultItemSchemaRegistry } from '@noetic-tools/types';
5
5
  export { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
@@ -1,4 +1,4 @@
1
- export { allocateBudgets, assembleView, churnFor, churnRate, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DECISION_PROJECTION, DEFAULT_PROJECTION, disposeLayers, initLayers, lineageKey, noteCacheOutcome, openEpoch, pin, pinKey, reanchorReason, resolveCacheConfig, resolveLayerTools, returnLayers, spawnLayers, unpinLayers, } from '@noetic-tools/context';
1
+ export { allocateBudgets, assembleView, churnFor, churnRate, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DECISION_PROJECTION, DEFAULT_PROJECTION, disposeLayers, exportSpans, initLayers, lineageKey, noteCacheOutcome, openEpoch, pin, pinKey, reanchorReason, resolveCacheConfig, resolveLayerTools, returnLayers, spawnLayers, unpinLayers, } from '@noetic-tools/context';
2
2
  export { defaultItemSchemaRegistry } from '@noetic-tools/types';
3
3
  export { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
4
4
  export { ContextImpl, laneBase } from '../runtime/context-impl.js';
@@ -5,6 +5,7 @@
5
5
  * and the model/tool spans they open nest under the child rather than being
6
6
  * lost to a no-op span.
7
7
  */
8
+ import { exportSpans } from '@noetic-tools/context';
8
9
  import { isNoeticError } from '@noetic-tools/types';
9
10
  import { NoeticAttr } from '../observability/genai-attributes.js';
10
11
  /** Opens a span named `name` under `parent.span`, stamped with the owning step id. */
@@ -46,7 +47,7 @@ function markFailed(span, error) {
46
47
  }
47
48
  async function closeChildSpan(parent, span) {
48
49
  span.end();
49
- await parent.harness.traceExporter.export([
50
+ await exportSpans(parent.harness.traceExporter, [
50
51
  span,
51
52
  ]);
52
53
  }
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import { createMessage, estimateTokens, extractAssistantText, frameworkCast, isNoeticError, isOutputCodec, NoeticConfigError, NoeticErrorImpl, validateSchema, } from '@noetic-tools/types';
5
5
  import { ToolAttr } from '../observability/genai-attributes.js';
6
+ import { askApproval } from '../runtime/tool-approval.js';
6
7
  import { emitToolUi } from '../runtime/tool-ui.js';
7
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';
8
9
  import { isServerToolSpec, SteeringAction } from './action-types.js';
@@ -398,6 +399,7 @@ function buildModelRequest(params) {
398
399
  items: params.assembledItems,
399
400
  instructions: params.resolvedInstructions,
400
401
  params: step.params,
402
+ toolChoice: step.toolChoice,
401
403
  outputSchema: params.outputSchema,
402
404
  outputJsonSchema: params.step.outputJsonSchema,
403
405
  emit: step.emit,
@@ -735,6 +737,20 @@ export async function executeSpawn(step, input, ctx, executeStep, opts) {
735
737
  pathPrefix: baseCtx instanceof ContextImpl ? baseCtx.currentPath() : '',
736
738
  ledger: baseCtx instanceof ContextImpl ? baseCtx.ledger : undefined,
737
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
+ }
738
754
  try {
739
755
  return await traceChild(baseCtx, span, async () => {
740
756
  // Execute the child step. Its token/cost usage needs no merge here: every
@@ -749,11 +765,7 @@ export async function executeSpawn(step, input, ctx, executeStep, opts) {
749
765
  layers,
750
766
  stepId: step.id,
751
767
  parentCtx: parentExecutionCtx,
752
- // `childExecutionCtx` predates the spawn span; trace onto that span.
753
- childCtx: {
754
- ...childExecutionCtx,
755
- trace: span,
756
- },
768
+ childCtx: childTracedCtx,
757
769
  childLog: childCtx.itemLog,
758
770
  result: childOutput,
759
771
  store: layerStore,
@@ -907,9 +919,14 @@ export async function executeInvokeTool(step, input, ctx, harness, layers) {
907
919
  const span = openChildSpan(baseCtx, 'tool.call', step.id);
908
920
  span.setAttribute(ToolAttr.NAME, step.tool.name);
909
921
  span.setAttribute(ToolAttr.NEEDS_APPROVAL, step.tool.needsApproval ?? false);
910
- return traceChild(baseCtx, span, () => runInvokeTool(step, input, baseCtx, harness, layers));
922
+ return traceChild(baseCtx, span, () => runInvokeTool(step, input, baseCtx, harness, layers, span));
911
923
  }
912
- async function runInvokeTool(step, input, baseCtx, harness, layers) {
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) {
913
930
  const args = step.args ? Object.assign({}, input, step.args) : input;
914
931
  const parseResult = await validateSchema(step.tool.input, args);
915
932
  if (!parseResult.success) {
@@ -948,14 +965,30 @@ async function runInvokeTool(step, input, baseCtx, harness, layers) {
948
965
  },
949
966
  });
950
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
+ };
951
975
  if (layers && layers.length > 0) {
952
976
  const decision = await harness.beforeToolCall(layers, step.tool.name, parsedArgs, baseCtx, step.id);
953
977
  if (decision.action !== SteeringAction.Allow) {
954
- emitCompleted(true, `Tool call denied: ${decision.guidance ?? 'steering rule violation'}`);
955
- throw new NoeticErrorImpl({
956
- kind: 'steering_denied',
957
- guidance: decision.guidance,
958
- });
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);
959
992
  }
960
993
  }
961
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
  }
@@ -290,7 +290,7 @@ export async function execute(step, input, ctx) {
290
290
  result = await executeAcpAgent(step, input, stepCtx, baseCtx.layers);
291
291
  break;
292
292
  case 'invokeTool':
293
- result = await executeInvokeTool(step, input, stepCtx, baseCtx.harness);
293
+ result = await executeInvokeTool(step, input, stepCtx, baseCtx.harness, baseCtx.layers);
294
294
  break;
295
295
  case 'decide':
296
296
  result = await executeDecide(step, input, stepCtx, baseCtx.layers);
@@ -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). */
@@ -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? }`. */
@@ -80,11 +101,12 @@ export declare const NoeticEvent: {
80
101
  */
81
102
  readonly SPAWN_SUMMARY_FAILED: "spawn.summary_failed";
82
103
  /**
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.
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.
88
110
  */
89
111
  readonly LAYER_HOOK: "layer.hook";
90
112
  };
@@ -1,4 +1,4 @@
1
- import { LAYER_HOOK_EVENT, 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.
@@ -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`.
@@ -86,11 +107,12 @@ export const NoeticEvent = {
86
107
  */
87
108
  SPAWN_SUMMARY_FAILED: SPAWN_SUMMARY_FAILED_EVENT,
88
109
  /**
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.
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.
94
116
  */
95
117
  LAYER_HOOK: LAYER_HOOK_EVENT,
96
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. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.10.0",
3
+ "version": "5.11.0",
4
4
  "type": "module",
5
5
  "description": "Step primitives, interpreter, runtime, and context layer contract for Noetic agents.",
6
6
  "license": "Apache-2.0",
@@ -68,8 +68,8 @@
68
68
  }
69
69
  },
70
70
  "dependencies": {
71
- "@noetic-tools/context": "^1.7.0",
72
- "@noetic-tools/types": "^3.8.0",
71
+ "@noetic-tools/context": "^1.8.0",
72
+ "@noetic-tools/types": "^3.9.0",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "zod": "^4.0.0"
@@ -89,6 +89,31 @@
89
89
  "additionalProperties": false
90
90
  }
91
91
  },
92
+ "toolChoice": {
93
+ "anyOf": [
94
+ {
95
+ "type": "string",
96
+ "enum": [
97
+ "auto",
98
+ "required",
99
+ "none"
100
+ ]
101
+ },
102
+ {
103
+ "type": "object",
104
+ "properties": {
105
+ "tool": {
106
+ "type": "string",
107
+ "minLength": 1
108
+ }
109
+ },
110
+ "required": [
111
+ "tool"
112
+ ],
113
+ "additionalProperties": false
114
+ }
115
+ ]
116
+ },
92
117
  "params": {
93
118
  "type": "object",
94
119
  "properties": {