@theoremjs/agents 0.3.5-next.966.g19b460d → 0.3.5-next.970.g11bd0cf

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.
package/README.md CHANGED
@@ -465,7 +465,7 @@ Named exports from the root barrel (same symbols hosts get from `@theoremjs/agen
465
465
  | Schema | `PROFILE_FIELDS`, `PROFILE_GRAPH`, `PROFILE_TYPES`, `PROFILE_ID_MAX_CHARS`, `PROFILE_HANDLE_MAX_CHARS`, `EXTRA_FIELDS`, `REQUEST_FIELDS`, `API_EXPORTS`, `fieldMeta`, `catalogPathFor`, `DYNAMIC_FIELD_PARENTS`, `spineFacetsForProfileType`, `profileGraphFacet`, `ProfileGraphFacet`, `ProfileGraphFacetId`, `ProfileGraphEditor`, `ProfileGraphRole`, `THINKING_LEVELS`, `KEY_SLOT_NAME`, `isKeySlotName`, `MEDIA_INPUT_KINDS`, `MEDIA_INPUT_KIND_VALUES`, `MEDIA_WILDCARDS`, `ATTACHMENT_ACCEPT_MIMES`, `IMAGE_ATTACHMENT_ACCEPT_MIMES`, `VOICE_ACCEPT_MIMES`, `SUMMARY_MODES`, `STREAM_MODES`, `SPEECH_AUDIO_FORMATS`, `COMPACTION_METERS`, `COMPACTION_OUTCOMES`, `COMPACTION_TIMINGS`, `TURN_STAGES`, `TURN_INJECT_STAGES`, `TURN_STOP_KINDS`, `CONTINUE_STOP_KINDS`, `TOOL_GATE_KINDS`, `AWAITING_USER_INPUT_KINDS`, `AWAITING_USER_INPUT_STATUS`, `TOOL_LOAD_TIERS`, `TOOL_ACCESS`, `TOOL_PERMISSION`, `TOOL_TYPES`, `AUTH_UNAUTHENTICATED_POLICIES`, `HTTP_METHODS`, `STUDIO_AUTH_TYPES`, `TOOL_AUTH_TYPES`, `AuthUnauthenticatedPolicy`, `CustomToolType`, `HttpMethod`, `StudioAuthType`, `ToolAccess`, `ToolAuthType`, `ToolPermission`, `ToolType`, `LIVE_ACTIVITY_HANDLINGS`, `LIVE_START_SENSITIVITIES`, `LIVE_END_SENSITIVITIES` |
466
466
  | Scope | `KernelScope`, `createKernelScope`, `defaultKernelScope`, `KernelRegistry`, `createKernelRegistry` |
467
467
  | Profiles | `ProfileDefinition`, `ProfileDefinitionBase`, `TextProfileDefinition`, `ImageProfileDefinition`, `SpeechProfileDefinition`, `TranscriptionProfileDefinition`, `LiveProfileDefinition`, `HostProfileDefinition`, `DecisionProfileDefinition`, `EmbeddingProfileDefinition`, `ProfileRegistry`, `createProfileRegistry`, `clearProfiles`, `defineProfile`, `getProfile`, `hasProfile`, `listProfiles`, `registerProfile`, `registerProfiles`, `projectProfile`, `resolveTurn`, `pickModel`, `resolveTurnSystemPrompt`, `systemLinesProblem` |
468
- | Tools | `ToolContext`, `GateReference`, `gateReferenceSchema`, `ToolRegistry`, `assertToolSettings`, `createToolRegistry`, `registerTool`, `registerTools`, `invokeTool`, `invokeToolStep`, `runTool`, `runToolStep`, `SettledToolCall`, `ToolCallResult`, `ToolStepCallResult`, `GATE_DECISIONS`, `GateDecision`, `askUserTool`, `registerHarnessTools`, `getTool`, `hasTool`, `requireTool`, `listTools`, `resetTools`, `formatToolResult`, `formatToolFailureForModel`, `prepareTurnToolSnapshot`, `buildHttpToolTarget`, `executeHttpTool`, `executeMcpTool`, `parseMcpRpcResponse`, `isUnsupportedMcpProtocolError`, `MCP_PROTOCOL_VERSIONS`, `mcpRequestMeta`, `McpProtocolVersion`, `resolveToolAuth`, `credentialPlacement`, `withCredentialQuery`, `CredentialQuery`, `uncheckedOutput`, `UncheckedOutput`, `ToolFailed`, `StatedToolFailure`, `McpRpcResponse`, `ModelToolResult`, `PageAnswer`, `ToolMediaEntry` (one entry of an HTTP or MCP tool's media hook) |
468
+ | Tools | `ToolContext`, `GateReference`, `gateReferenceSchema`, `ToolRegistry`, `assertToolSettings`, `createToolRegistry`, `registerTool`, `registerTools`, `invokeTool`, `invokeToolStep`, `runTool`, `runToolStep`, `RunToolStepRequest`, `SettledToolCall`, `ToolCallResult`, `ToolStepCallResult`, `GATE_DECISIONS`, `GateDecision`, `askUserTool`, `registerHarnessTools`, `getTool`, `hasTool`, `requireTool`, `listTools`, `resetTools`, `formatToolResult`, `formatToolFailureForModel`, `prepareTurnToolSnapshot`, `buildHttpToolTarget`, `executeHttpTool`, `executeMcpTool`, `parseMcpRpcResponse`, `isUnsupportedMcpProtocolError`, `MCP_PROTOCOL_VERSIONS`, `mcpRequestMeta`, `McpProtocolVersion`, `resolveToolAuth`, `credentialPlacement`, `withCredentialQuery`, `CredentialQuery`, `probeTool`, `ProbeToolOptions`, `ToolProbe`, `ToolProbeAnswer`, `ToolProbeTarget`, `uncheckedOutput`, `UncheckedOutput`, `ToolFailed`, `StatedToolFailure`, `McpRpcResponse`, `ModelToolResult`, `ToolStreamEvent`, `PageAnswer`, `ToolMediaEntry` (one entry of an HTTP or MCP tool's media hook) |
469
469
  | Tool execution | `ToolBackground`, `ToolBackgroundCall`, `ToolBackgroundHandle`, `ToolBackgroundService`, `ToolBackgroundSettled`, `ToolSteerReceipt`, `ToolSteerRefusal`, `ToolOperationReply`, `toolOperationReplySchema`, `BackgroundToolEvent`, `ToolExecutionCoordinator`, `createMemoryToolExecution`, `MemoryToolExecutionOptions`, `authorizeToolReplay`, `BeginToolOperationResult`, `ToolOperationClaim`, `ToolOperationIdentity`, `ToolOperationOutcome`, `ToolOperationUncertainty`, `toolOperationOutcomeSchema`, `SavedToolInvocation`, `savedToolInvocationSchema`, `toolInvocationHash`, `TerminalToolEvent`, `PageToolDispatch`, `PageToolExecution` |
470
470
  | Structured | `SchemaRegistry`, `createSchemaRegistry`, `getStructured`, `registerStructured` |
471
471
  | Stop / resume | `ProfileTurnBehaviourSpec`, `MediaTurnBehaviourSpec`, `ProfileTurnResumptionSpec`, `TurnContinueFrom`, `TurnStop`, `TurnStopKind`, `ContinueStopKind`, `StepLimitMode`, `CONTINUE_STOP_KINDS`, `AUTO_CONTINUE_DELAY_MS`, `DEFAULT_ALLOW_CONTINUE`, `DEFAULT_AUTO_CONTINUE`, `GenerationStopError`, `isContinueStopKind`, `isGenerationStopError`, `isResumeableStop`, `isUserCancelledStop`, `profileAllowsSteering`, `profileAllowsInject`, `profileTurnResumption`, `shouldAutoContinue`, `turnStopFromClientStreamEnd` |
package/esm/mod.d.ts CHANGED
@@ -72,12 +72,12 @@ export { ToolFailed } from './src/kernel/tools/failed.js';
72
72
  export { GATE_DECISIONS, type GateDecision } from './src/kernel/tools/gate-answer.js';
73
73
  export type { MemoryToolExecutionOptions } from './src/kernel/tools/memory-execution.js';
74
74
  export { createMemoryToolExecution } from './src/kernel/tools/memory-execution.js';
75
- export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ToolRegistry, } from './src/kernel/tools/mod.js';
76
- export { askUserTool, assertToolSettings, buildHttpToolTarget, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, formatToolFailureForModel, formatToolResult, isUnsupportedMcpProtocolError, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, registerHarnessTools, resolveToolAuth, toolOutputPartSchema, UncheckedOutput, uncheckedOutput, withCredentialQuery, } from './src/kernel/tools/mod.js';
75
+ export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ProbeToolOptions, ToolProbe, ToolProbeAnswer, ToolProbeTarget, ToolRegistry, } from './src/kernel/tools/mod.js';
76
+ export { askUserTool, assertToolSettings, buildHttpToolTarget, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, formatToolFailureForModel, formatToolResult, isUnsupportedMcpProtocolError, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, probeTool, registerHarnessTools, resolveToolAuth, toolOutputPartSchema, UncheckedOutput, uncheckedOutput, withCredentialQuery, } from './src/kernel/tools/mod.js';
77
77
  export type { BackgroundToolEvent, BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationReply, ToolOperationUncertainty, } from './src/kernel/tools/operation.js';
78
78
  export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, toolOperationReplySchema, } from './src/kernel/tools/operation.js';
79
- export type { SettledToolCall, ToolCallResult, ToolStepCallResult, } from './src/kernel/tools/run.js';
80
- export type { ModelToolResult, PageAnswer, ToolContext, ToolMediaEntry, } from './src/kernel/tools/types.js';
79
+ export type { RunToolStepRequest, SettledToolCall, ToolCallResult, ToolStepCallResult, } from './src/kernel/tools/run.js';
80
+ export type { ModelToolResult, PageAnswer, ToolContext, ToolMediaEntry, ToolStreamEvent, } from './src/kernel/tools/types.js';
81
81
  export { awaitingUserInputSchema, type GateReference, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, type ToolOutputPart, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './src/kernel/turn-events.js';
82
82
  export type * from './src/kernel/types.js';
83
83
  export type { OtlpAnyValue, OtlpKeyValue, OtlpSpan, OtlpTraceRequest, ProfileObservabilitySpec, ResolvedObservabilityPolicy, ResolvedScrubSwitch, ResolvedTraceInclude, ResolvedTraceScrub, ScrubSwitch, SpanHandle, SpanLinkInput, SpanOptions, TraceAttributeGroup, TraceAttributeMeta, TraceAttributes, TraceAttributeValue, TraceBytes, TraceClock, TraceContent, TraceEventMeta, TraceIncludeSpec, TraceJson, TraceOptionMeta, TraceRecord, TraceScrubSpec, TraceSink, TraceSpan, TraceSpanEvent, TraceSpanKind, TraceSpanLink, TraceSpanMeta, TraceSpanStatus, TraceSpanType, TraceTree, TraceValueFormat, TraceWriteContext, } from './src/observability/mod.js';
package/esm/mod.js CHANGED
@@ -45,7 +45,7 @@ export { authorizeToolReplay } from './src/kernel/tools/execute.js';
45
45
  export { ToolFailed } from './src/kernel/tools/failed.js';
46
46
  export { GATE_DECISIONS } from './src/kernel/tools/gate-answer.js';
47
47
  export { createMemoryToolExecution } from './src/kernel/tools/memory-execution.js';
48
- export { askUserTool, assertToolSettings, buildHttpToolTarget, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, formatToolFailureForModel, formatToolResult, isUnsupportedMcpProtocolError, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, registerHarnessTools, resolveToolAuth, toolOutputPartSchema, UncheckedOutput, uncheckedOutput, withCredentialQuery, } from './src/kernel/tools/mod.js';
48
+ export { askUserTool, assertToolSettings, buildHttpToolTarget, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, formatToolFailureForModel, formatToolResult, isUnsupportedMcpProtocolError, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, probeTool, registerHarnessTools, resolveToolAuth, toolOutputPartSchema, UncheckedOutput, uncheckedOutput, withCredentialQuery, } from './src/kernel/tools/mod.js';
49
49
  export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, toolOperationReplySchema, } from './src/kernel/tools/operation.js';
50
50
  export { awaitingUserInputSchema, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './src/kernel/turn-events.js';
51
51
  export { buildRecord, clearTraceDestinations, contentOf, getTraceDestination, inlineContent, isTraceSink, listTraceDestinationIds, memorySink, noopSink, readTraceparent, registerTraceDestination, requireTraceDestination, resolveObservabilityPolicy, resolveTraceWriter, startTrace, TRACE_ATTRIBUTE_GROUPS, TRACE_FIELDS, TRACE_SPAN_TYPES, TRACE_STATUS, toOtlpJson, traceAttributeMeta, traceBytes, traceContent, traceEventAttributeMeta, traceEventMeta, traceJson, traceRecordSchema, traceSpanMeta, writeTrace, } from './src/observability/mod.js';
@@ -12,6 +12,12 @@ export interface ToolCredentialSource {
12
12
  * rotated refresh token lost to a closed stream cannot be recovered.
13
13
  */
14
14
  set(slot: string, credential: ToolCredential): Promise<void>;
15
+ /**
16
+ * Forget the slot's credential, as when the person disconnects the service: once it
17
+ * resolves, `get(slot)` answers `undefined` and the next call that needs it gates.
18
+ * Revoke an OAuth sign-in first with `revokeOAuthToken`; this only forgets.
19
+ */
20
+ delete(slot: string): Promise<void>;
15
21
  /**
16
22
  * The secret of a confidential OAuth client, read when the kernel refreshes a token
17
23
  * issued to `clientId`. Omit it for public clients. The secret is the host's, not
@@ -7,5 +7,9 @@ export function memoryCredentialSource(initial = {}) {
7
7
  slots.set(slot, credential);
8
8
  return Promise.resolve();
9
9
  },
10
+ delete: (slot) => {
11
+ slots.delete(slot);
12
+ return Promise.resolve();
13
+ },
10
14
  };
11
15
  }
@@ -7,7 +7,7 @@ import type { Provider, RegisteredProvider, Registration } from './protocols/pro
7
7
  import type { ProviderHostOptions } from './protocols/runtime.js';
8
8
  import type { ProfileDefinition } from './registry/profiles.js';
9
9
  import { defaultKernelScope as scope } from './scope.js';
10
- import type { ToolCallResult, ToolStepCallResult } from './tools/run.js';
10
+ import type { RunToolStepRequest, ToolCallResult, ToolStepCallResult } from './tools/run.js';
11
11
  import type { InvokeToolRequest, InvokeToolStepRequest, RegisteredTool, ToolDefinitionInput } from './tools/types.js';
12
12
  import type { CompactHistoryRequest, CompactionResult, DecisionRequest, DecisionResult, EmbeddingRequest, EmbeddingResult, LiveSession, Profile, ProjectedProfile, SessionRequest, StructuredSpec, TurnEvent, TurnRequest } from './types.js';
13
13
  /**
@@ -86,8 +86,11 @@ declare function invokeToolStep(request: InvokeToolStepRequest, sinkOverride?: T
86
86
  * emitted.
87
87
  */
88
88
  declare function runTool(request: InvokeToolRequest, sinkOverride?: TraceSink): Promise<ToolCallResult>;
89
- /** Run the host's calls as one step in the default scope, giving each call's end as it settles. */
90
- declare function runToolStep(request: InvokeToolStepRequest, sinkOverride?: TraceSink): AsyncGenerator<ToolStepCallResult>;
89
+ /**
90
+ * Run the host's calls as one step in the default scope, giving each call's end as it settles;
91
+ * `onEvent` hears each event as it arrives.
92
+ */
93
+ declare function runToolStep(request: RunToolStepRequest, sinkOverride?: TraceSink): AsyncGenerator<ToolStepCallResult>;
91
94
  /** Resolve a turn request in the default scope: its profile, model, and generation settings. */
92
95
  declare function resolveTurn(req: TurnRequest): ReturnType<typeof scope.resolveTurn>;
93
96
  /** Each model of profile `id` in the default scope that cannot run a plain turn on its provider, and why. */
@@ -117,7 +117,10 @@ function invokeToolStep(request, sinkOverride) {
117
117
  function runTool(request, sinkOverride) {
118
118
  return scope.runTool(request, sinkOverride);
119
119
  }
120
- /** Run the host's calls as one step in the default scope, giving each call's end as it settles. */
120
+ /**
121
+ * Run the host's calls as one step in the default scope, giving each call's end as it settles;
122
+ * `onEvent` hears each event as it arrives.
123
+ */
121
124
  function runToolStep(request, sinkOverride) {
122
125
  return scope.runToolStep(request, sinkOverride);
123
126
  }
@@ -71,14 +71,15 @@ export { ToolFailed } from './tools/failed.js';
71
71
  export { type AnsweredGate, answerGatedCall, GATE_DECISIONS, type GateAnswerRequest, type GateDecision, gateExpired, type HeldGatedCall, resolveGateTtlMs, sessionPermissionsAfterApproval, type ToolGateAuth, } from './tools/gate-answer.js';
72
72
  export type { MemoryToolExecutionOptions } from './tools/memory-execution.js';
73
73
  export { createMemoryToolExecution } from './tools/memory-execution.js';
74
- export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ToolRegistry, } from './tools/mod.js';
75
- export { askUserTool, assertToolSettings, authorizeToolReplay, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, executeRegisteredTool, formatToolFailureForModel, formatToolResult, isUnsupportedMcpProtocolError, leanToolResultData, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, projectForModel, registerHarnessTools, resolveToolAuth, toolOutputPartSchema, withCredentialQuery, } from './tools/mod.js';
74
+ export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ProbeToolOptions, ToolProbe, ToolProbeAnswer, ToolProbeTarget, ToolRegistry, } from './tools/mod.js';
75
+ export { askUserTool, assertToolSettings, authorizeToolReplay, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, executeRegisteredTool, formatToolFailureForModel, formatToolResult, isUnsupportedMcpProtocolError, leanToolResultData, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, probeTool, projectForModel, registerHarnessTools, resolveToolAuth, toolOutputPartSchema, withCredentialQuery, } from './tools/mod.js';
76
76
  export type { BackgroundToolEvent, BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationReply, ToolOperationUncertainty, } from './tools/operation.js';
77
77
  export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, toolOperationReplySchema, } from './tools/operation.js';
78
78
  export { toolAuthForCall } from './tools/registry.js';
79
+ export type { RunToolStepRequest, SettledToolCall, ToolCallResult, ToolStepCallResult, } from './tools/run.js';
79
80
  export { jsonSchemaFromZod } from './tools/schema.js';
80
81
  export { CredentialRefusedError } from './tools/signed-in-fetch.js';
81
- export type { ModelToolResult, PageAnswer, ToolAuthConfig, ToolAuthFor, ToolContext, ToolLabels, ToolMediaEntry, } from './tools/types.js';
82
+ export type { ModelToolResult, PageAnswer, ToolAuthConfig, ToolAuthFor, ToolContext, ToolLabels, ToolMediaEntry, ToolStreamEvent, } from './tools/types.js';
82
83
  export { awaitingUserInputSchema, type GateReference, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, type ToolOutputPart, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './turn-events.js';
83
84
  export type * from './types.js';
84
85
  export { base64ToBytes, bytesToBase64 } from './util/base64.js';
@@ -43,7 +43,7 @@ export { declaredInputSchema } from './tools/call-order.js';
43
43
  export { ToolFailed } from './tools/failed.js';
44
44
  export { answerGatedCall, GATE_DECISIONS, gateExpired, resolveGateTtlMs, sessionPermissionsAfterApproval, } from './tools/gate-answer.js';
45
45
  export { createMemoryToolExecution } from './tools/memory-execution.js';
46
- export { askUserTool, assertToolSettings, authorizeToolReplay, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, executeRegisteredTool, formatToolFailureForModel, formatToolResult, isUnsupportedMcpProtocolError, leanToolResultData, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, projectForModel, registerHarnessTools, resolveToolAuth, toolOutputPartSchema, withCredentialQuery, } from './tools/mod.js';
46
+ export { askUserTool, assertToolSettings, authorizeToolReplay, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, executeRegisteredTool, formatToolFailureForModel, formatToolResult, isUnsupportedMcpProtocolError, leanToolResultData, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, probeTool, projectForModel, registerHarnessTools, resolveToolAuth, toolOutputPartSchema, withCredentialQuery, } from './tools/mod.js';
47
47
  export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, toolOperationReplySchema, } from './tools/operation.js';
48
48
  export { toolAuthForCall } from './tools/registry.js';
49
49
  export { jsonSchemaFromZod } from './tools/schema.js';
@@ -5,7 +5,7 @@ import { type RunSessionOptions } from './engine/session/mod.js';
5
5
  import type { ProviderHostOptions } from './protocols/runtime.js';
6
6
  import { type KernelRegistry } from './registry/kernel-registry.js';
7
7
  import { resolveTurnInRegistry } from './registry/resolve.js';
8
- import { type ToolCallResult, type ToolStepCallResult } from './tools/run.js';
8
+ import { type RunToolStepRequest, type ToolCallResult, type ToolStepCallResult } from './tools/run.js';
9
9
  import type { InvokeToolRequest, InvokeToolStepRequest } from './tools/types.js';
10
10
  import type { CompactHistoryRequest, CompactionResult, DecisionRequest, DecisionResult, EmbeddingRequest, EmbeddingResult, LiveSession, ProjectedProfile, SessionRequest, TurnEvent, TurnRequest } from './types.js';
11
11
  /** A kernel scope: its registries and the operations that run against them (turns, live sessions, history compaction, tool invocation, turn resolution, profile projection, and decisions). */
@@ -16,7 +16,7 @@ interface KernelScope extends KernelRegistry {
16
16
  invokeTool(request: InvokeToolRequest, sinkOverride?: TraceSink): AsyncGenerator<TurnEvent>;
17
17
  invokeToolStep(request: InvokeToolStepRequest, sinkOverride?: TraceSink): AsyncGenerator<TurnEvent>;
18
18
  runTool(request: InvokeToolRequest, sinkOverride?: TraceSink): Promise<ToolCallResult>;
19
- runToolStep(request: InvokeToolStepRequest, sinkOverride?: TraceSink): AsyncGenerator<ToolStepCallResult>;
19
+ runToolStep(request: RunToolStepRequest, sinkOverride?: TraceSink): AsyncGenerator<ToolStepCallResult>;
20
20
  resolveTurn(req: TurnRequest): ReturnType<typeof resolveTurnInRegistry>;
21
21
  projectProfile(id: string): ProjectedProfile;
22
22
  runDecision(request: DecisionRequest, options: RunDecisionOptions): Promise<DecisionResult>;
@@ -33,7 +33,7 @@ function createKernelScope() {
33
33
  invokeTool: (request, sinkOverride) => invokeTool(registry, request, sinkOverride),
34
34
  invokeToolStep: (request, sinkOverride) => invokeToolStep(registry, request, sinkOverride),
35
35
  runTool: (request, sinkOverride) => settledCall(startInvoke(registry, request, sinkOverride)),
36
- runToolStep: (request, sinkOverride) => settledCalls(startInvokeStep(registry, request, sinkOverride)),
36
+ runToolStep: ({ onEvent, ...request }, sinkOverride) => settledCalls(startInvokeStep(registry, request, sinkOverride), onEvent),
37
37
  resolveTurn: (req) => resolveTurnInRegistry(registry, req),
38
38
  projectProfile: (id) => projectProfileInRegistry(registry, id),
39
39
  runDecision: (request, options) => runDecisionInRegistry(registry, request, options),
@@ -2,6 +2,8 @@ export { authorizeToolReplay, executeRegisteredTool, leanToolResultData, project
2
2
  export { askUserTool, registerHarnessTools } from './harness.js';
3
3
  export { formatToolFailureForModel, formatToolResult } from './model-text.js';
4
4
  export { toolOutputPartSchema } from './output-parts.js';
5
+ export type { ProbeToolOptions, ToolProbe, ToolProbeAnswer, ToolProbeTarget } from './probe.js';
6
+ export { probeTool } from './probe.js';
5
7
  export type { ToolRegistry } from './registry.js';
6
8
  export { assertToolSettings, createToolRegistry } from './registry.js';
7
9
  export type { CredentialQuery, McpProtocolVersion, McpRpcResponse } from './remote.js';
@@ -2,6 +2,7 @@ export { authorizeToolReplay, executeRegisteredTool, leanToolResultData, project
2
2
  export { askUserTool, registerHarnessTools } from './harness.js';
3
3
  export { formatToolFailureForModel, formatToolResult } from './model-text.js';
4
4
  export { toolOutputPartSchema } from './output-parts.js';
5
+ export { probeTool } from './probe.js';
5
6
  export { assertToolSettings, createToolRegistry } from './registry.js';
6
7
  export { buildHttpToolTarget, credentialPlacement, executeHttpTool, executeMcpTool, isUnsupportedMcpProtocolError, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, resolveToolAuth, withCredentialQuery, } from './remote.js';
7
8
  export { cloneTurnToolSnapshot, prepareTurnToolSnapshot } from './resolve.js';
@@ -0,0 +1,108 @@
1
+ import { type ResolveHost } from '../../guardrails/network.js';
2
+ import type { NetworkGuardrailSpec } from '../../guardrails/types.js';
3
+ import type { HttpToolDef, ToolAuthConfig } from './types.js';
4
+ /** The service a probe asks: an HTTP tool's request, or an MCP server's tool list. */
5
+ export type ToolProbeTarget = {
6
+ type: 'http';
7
+ endpoint: string;
8
+ /** Default `GET`. */
9
+ method?: HttpToolDef['method'];
10
+ /** The tool's input for this request: it fills the path, query and body as the tool's mapping says. */
11
+ input?: Record<string, unknown>;
12
+ mapping?: HttpToolDef['mapping'];
13
+ headers?: Record<string, string>;
14
+ } | {
15
+ type: 'mcp';
16
+ serverUrl: string;
17
+ headers?: Record<string, string>;
18
+ };
19
+ /** Options for {@link probeTool}. */
20
+ export interface ProbeToolOptions {
21
+ target: ToolProbeTarget;
22
+ /** Where the credential goes, as the tool declares it. An `api_key` goes as a key; any other type as a bearer token. */
23
+ auth?: Pick<ToolAuthConfig, 'type' | 'headerName' | 'headerPrefix' | 'queryParam'>;
24
+ /** The credential to try. Without it, the request goes without one. */
25
+ credential?: string;
26
+ /** The network guardrail the request keeps to, as a run's. Without it, public addresses only. */
27
+ network?: NetworkGuardrailSpec;
28
+ /** Checks each host name against private addresses, as a run's. */
29
+ resolveHost?: ResolveHost;
30
+ /** How long the whole answer may take, body included. Without it, no limit, as a tool's own call. */
31
+ timeoutMs?: number;
32
+ /** The most of the body that is read. Without it, no limit, as a tool's own call. */
33
+ maxResponseBytes?: number;
34
+ fetch?: typeof fetch;
35
+ signal?: AbortSignal;
36
+ }
37
+ /** What the service answered: its status and body, with the credential replaced wherever it echoed it. */
38
+ export interface ToolProbeAnswer {
39
+ status: number;
40
+ statusText: string;
41
+ contentType: string;
42
+ body: string;
43
+ }
44
+ /**
45
+ * What a probe found.
46
+ *
47
+ * - `accepted`: a 2xx answer; for MCP, a tool list.
48
+ * - `refused`: a 401 or 403 to a request that carried the credential, read as a tool's own call reads it.
49
+ * - `inconclusive`: the service answered, but neither accepted nor refused the credential.
50
+ * - `unanswered`: no answer came back.
51
+ */
52
+ export type ToolProbe = {
53
+ verdict: 'accepted';
54
+ answer: ToolProbeAnswer;
55
+ /** For an MCP server: the protocol version it answered under, and its tools' names. */
56
+ mcp?: {
57
+ protocolVersion: string;
58
+ tools: string[];
59
+ };
60
+ } | {
61
+ verdict: 'refused';
62
+ answer: ToolProbeAnswer;
63
+ } | {
64
+ verdict: 'inconclusive';
65
+ /**
66
+ * - `status`: an answer that is neither 2xx nor a refusal, such as 402, 404 or 500.
67
+ * - `too_large`: the body ran past `maxResponseBytes`.
68
+ * - `not_json`: an MCP server's answer that is not JSON-RPC.
69
+ * - `not_mcp`: JSON-RPC, but no tool list.
70
+ * - `mcp_error`: an MCP error, or no protocol version both sides speak.
71
+ * - `mcp_session`: the server asked for a session and could not open one.
72
+ */
73
+ reason: 'status' | 'too_large' | 'not_json' | 'not_mcp' | 'mcp_error' | 'mcp_session';
74
+ answer?: ToolProbeAnswer;
75
+ /** The MCP error, for `mcp_error`. */
76
+ error?: {
77
+ code: number;
78
+ message: string;
79
+ };
80
+ } | {
81
+ verdict: 'unanswered';
82
+ /**
83
+ * - `blocked`: the network guardrail refused the address.
84
+ * - `invalid_url`: the address is not one a request can go to.
85
+ * - `invalid_mapping`: the endpoint and input make no URL.
86
+ * - `timeout`: no whole answer within `timeoutMs`.
87
+ * - `network`: the request failed on the way.
88
+ */
89
+ reason: 'blocked' | 'invalid_url' | 'invalid_mapping' | 'timeout' | 'network';
90
+ };
91
+ /**
92
+ * Sends one request to an HTTP or MCP tool's service, the way the tool's own calls send it: the
93
+ * credential where `auth` puts it, through the network guardrail, redirects followed with the
94
+ * credential kept to the first origin. An MCP server is asked for its tool list, in a session when
95
+ * it asks for one. Nothing is stored, and the result never holds the credential.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * const probe = await probeTool({
100
+ * target: { type: 'http', endpoint: 'https://api.station.example/v1/devices' },
101
+ * auth: { type: 'api_key', headerName: 'X-Station-Key' },
102
+ * credential: pasted,
103
+ * timeoutMs: 10_000,
104
+ * });
105
+ * if (probe.verdict === 'accepted') await keep(pasted);
106
+ * ```
107
+ */
108
+ export declare function probeTool(options: ProbeToolOptions): Promise<ToolProbe>;
@@ -0,0 +1,191 @@
1
+ /**
2
+ * One request to an HTTP or MCP tool's service, sent the way the tool's own calls send it, so a
3
+ * host can tell whether the service answers, and whether it takes a credential, before a model
4
+ * calls the tool.
5
+ *
6
+ * @module
7
+ */
8
+ import { errorKind } from '../../guardrails/error.js';
9
+ import { fetchGuarded } from '../../guardrails/network.js';
10
+ import { createMcpSessionCache } from './mcp-sessions.js';
11
+ import { buildHttpToolTarget, credentialPlacement, credentialRefusal, httpRequestHeaders, MCP_REQUEST_HEADERS, negotiateInSession, negotiateMcpRpc, omitSecretText, readCappedText, withCredentialQuery, } from './remote.js';
12
+ function placeCredential(auth, credential) {
13
+ if (!credential)
14
+ return { headers: {} };
15
+ const config = auth ?? { type: 'bearer' };
16
+ const sent = config.type === 'api_key'
17
+ ? { type: 'api_key', key: credential }
18
+ : { type: 'bearer', token: credential };
19
+ return { ...credentialPlacement(config, sent), secret: credential };
20
+ }
21
+ function unanswered(err) {
22
+ const kind = errorKind(err);
23
+ if (kind === 'blocked')
24
+ return { verdict: 'unanswered', reason: 'blocked' };
25
+ if (kind === 'request')
26
+ return { verdict: 'unanswered', reason: 'invalid_url' };
27
+ if (kind === 'timeout')
28
+ return { verdict: 'unanswered', reason: 'timeout' };
29
+ return { verdict: 'unanswered', reason: 'network' };
30
+ }
31
+ /** The caller's signal and the probe's timeout, as one. */
32
+ function probeSignal(options) {
33
+ const timedOut = options.timeoutMs === undefined ? undefined : AbortSignal.timeout(options.timeoutMs);
34
+ if (timedOut && options.signal)
35
+ return AbortSignal.any([options.signal, timedOut]);
36
+ return timedOut ?? options.signal;
37
+ }
38
+ function hidden(text, secret) {
39
+ return secret ? omitSecretText(text, secret) : text;
40
+ }
41
+ async function probeHttp(target, placed, options) {
42
+ const method = target.method ?? 'GET';
43
+ let url;
44
+ let body;
45
+ try {
46
+ const built = buildHttpToolTarget(target.endpoint, method, target.input ?? {}, target.mapping);
47
+ url = withCredentialQuery(new URL(built.url), placed.query).href;
48
+ body = built.body;
49
+ }
50
+ catch {
51
+ return { verdict: 'unanswered', reason: 'invalid_mapping' };
52
+ }
53
+ const response = await fetchGuarded(url, {
54
+ method,
55
+ headers: httpRequestHeaders(method),
56
+ ...(method === 'GET' ? {} : { body }),
57
+ signal: probeSignal(options),
58
+ }, {
59
+ policy: options.network,
60
+ followRedirects: true,
61
+ originBoundHeaders: { ...target.headers, ...placed.headers },
62
+ resolveHost: options.resolveHost,
63
+ fetchFn: options.fetch,
64
+ });
65
+ const text = await readCappedText(response, options.maxResponseBytes);
66
+ if (text === undefined)
67
+ return { verdict: 'inconclusive', reason: 'too_large' };
68
+ const answer = {
69
+ status: response.status,
70
+ statusText: response.statusText,
71
+ contentType: response.headers.get('content-type') ?? '',
72
+ body: hidden(text, placed.secret),
73
+ };
74
+ if (response.ok)
75
+ return { verdict: 'accepted', answer };
76
+ if (placed.secret !== undefined && credentialRefusal(response)) {
77
+ return { verdict: 'refused', answer };
78
+ }
79
+ return { verdict: 'inconclusive', reason: 'status', answer };
80
+ }
81
+ function mcpAnswer(status, body) {
82
+ return { status, statusText: '', contentType: '', body };
83
+ }
84
+ /** An MCP server's answer, read as a probe: a tool list, a refusal, or why it is neither. */
85
+ function readMcp(negotiated, placed) {
86
+ const answer = negotiated.answer
87
+ ? mcpAnswer(negotiated.answer.status, hidden(negotiated.answer.body, placed.secret))
88
+ : undefined;
89
+ const withAnswer = answer ? { answer } : {};
90
+ if (negotiated.refusal && placed.secret !== undefined && answer) {
91
+ return { verdict: 'refused', answer };
92
+ }
93
+ const { failure, rpc } = negotiated;
94
+ if (failure?.code === 'response_too_large')
95
+ return { verdict: 'inconclusive', reason: 'too_large' };
96
+ if (failure?.code === 'invalid_response') {
97
+ return { verdict: 'inconclusive', reason: 'not_json', ...withAnswer };
98
+ }
99
+ if (failure?.code.startsWith('mcp_session')) {
100
+ return { verdict: 'inconclusive', reason: 'mcp_session' };
101
+ }
102
+ if (failure)
103
+ return { verdict: 'inconclusive', reason: 'status', ...withAnswer };
104
+ if (!rpc) {
105
+ const error = negotiated.lastProtocolError;
106
+ return {
107
+ verdict: 'inconclusive',
108
+ reason: 'mcp_error',
109
+ ...(error
110
+ ? { error: { code: error.code, message: hidden(error.message, placed.secret) } }
111
+ : {}),
112
+ };
113
+ }
114
+ if (rpc.error) {
115
+ return {
116
+ verdict: 'inconclusive',
117
+ reason: 'mcp_error',
118
+ error: { code: rpc.error.code, message: hidden(rpc.error.message, placed.secret) },
119
+ };
120
+ }
121
+ const listed = rpc.result?.tools;
122
+ const body = hidden(JSON.stringify(rpc.result ?? rpc), placed.secret);
123
+ if (rpc.jsonrpc !== '2.0' || !Array.isArray(listed)) {
124
+ return { verdict: 'inconclusive', reason: 'not_mcp', answer: mcpAnswer(200, body) };
125
+ }
126
+ return {
127
+ verdict: 'accepted',
128
+ answer: { status: 200, statusText: 'OK', contentType: 'application/json', body },
129
+ mcp: {
130
+ protocolVersion: negotiated.protocolVersion ?? '',
131
+ tools: listed.map((tool) => tool.name),
132
+ },
133
+ };
134
+ }
135
+ async function probeMcp(target, placed, options) {
136
+ const serverUrl = URL.parse(target.serverUrl);
137
+ if (!serverUrl)
138
+ return { verdict: 'unanswered', reason: 'invalid_url' };
139
+ const transport = {
140
+ url: withCredentialQuery(serverUrl, placed.query).href,
141
+ headers: { ...MCP_REQUEST_HEADERS },
142
+ originBoundHeaders: { ...target.headers, ...placed.headers },
143
+ policy: options.network,
144
+ resolveHost: options.resolveHost,
145
+ fetch: options.fetch,
146
+ signal: probeSignal(options),
147
+ ...(options.maxResponseBytes === undefined
148
+ ? {}
149
+ : { maxResponseBytes: options.maxResponseBytes }),
150
+ };
151
+ const call = { id: 'probe', method: 'tools/list', params: {} };
152
+ const first = await negotiateMcpRpc(transport, call);
153
+ const negotiated = first.sessionRequired
154
+ ? await negotiateInSession(transport, call, {
155
+ cache: createMcpSessionCache(),
156
+ key: transport.url,
157
+ use: { tool: 'probe' },
158
+ })
159
+ : first;
160
+ return readMcp(negotiated, placed);
161
+ }
162
+ /**
163
+ * Sends one request to an HTTP or MCP tool's service, the way the tool's own calls send it: the
164
+ * credential where `auth` puts it, through the network guardrail, redirects followed with the
165
+ * credential kept to the first origin. An MCP server is asked for its tool list, in a session when
166
+ * it asks for one. Nothing is stored, and the result never holds the credential.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * const probe = await probeTool({
171
+ * target: { type: 'http', endpoint: 'https://api.station.example/v1/devices' },
172
+ * auth: { type: 'api_key', headerName: 'X-Station-Key' },
173
+ * credential: pasted,
174
+ * timeoutMs: 10_000,
175
+ * });
176
+ * if (probe.verdict === 'accepted') await keep(pasted);
177
+ * ```
178
+ */
179
+ export async function probeTool(options) {
180
+ const placed = placeCredential(options.auth, options.credential);
181
+ try {
182
+ return options.target.type === 'http'
183
+ ? await probeHttp(options.target, placed, options)
184
+ : await probeMcp(options.target, placed, options);
185
+ }
186
+ catch (err) {
187
+ if (options.signal?.aborted)
188
+ throw err;
189
+ return unanswered(err);
190
+ }
191
+ }
@@ -1,9 +1,11 @@
1
+ import { type ResolveHost } from '../../guardrails/network.js';
2
+ import type { NetworkGuardrailSpec } from '../../guardrails/types.js';
1
3
  import type { ApiKeyCredential, BearerCredential } from '../auth/types.js';
2
4
  import type { ToolOutputPart } from '../turn-events.js';
3
5
  import type { TurnEvent } from '../types.js';
4
6
  import { type ToolCallBase } from './events.js';
5
7
  import type { HandlerEvents } from './handler-events.js';
6
- import { type McpSessionCache } from './mcp-sessions.js';
8
+ import { type McpSession, type McpSessionCache, type McpSessionUse } from './mcp-sessions.js';
7
9
  import type { ToolOperationClaim } from './operation.js';
8
10
  import { type JsonSchema } from './schema.js';
9
11
  import { type SchemaIssue } from './schema-issues.js';
@@ -105,6 +107,10 @@ export declare function refusedCredentialOutcome(tool: {
105
107
  name: string;
106
108
  auth?: ToolAuthConfig;
107
109
  }, refusal: CredentialRefusal | undefined, carried: boolean, ctx: ToolContext, base: ToolCallBase): Generator<TurnEvent, ToolBodyOutcome | undefined>;
110
+ /** A body, read up to `maxBytes` when set; `undefined` when it runs past, with the rest left unread. */
111
+ export declare function readCappedText(response: Response, maxBytes: number | undefined): Promise<string | undefined>;
112
+ /** The text with the credential replaced. */
113
+ export declare function omitSecretText(text: string, secret: string): string;
108
114
  /** Every string in `value` with the credential replaced. */
109
115
  export declare function omitSecret(value: unknown, secret: string): unknown;
110
116
  /** A failure's message and details with the credential replaced. */
@@ -116,6 +122,10 @@ export declare function audienceMismatch(audience: string | undefined, url: URL)
116
122
  * arrives, as a function tool's drafts.
117
123
  */
118
124
  export declare function executeHttpTool(tool: HttpToolDef, rawInput: unknown, ctx: ToolContext, base: ToolCallBase, stages?: ToolStageSupport, beginBody?: (preparedInput: unknown) => Promise<ToolOperationClaim | undefined>, shown?: HandlerEvents): AsyncGenerator<TurnEvent, ToolBodyOutcome>;
125
+ /** The headers an HTTP tool's request is sent with, before its own and its credential's. */
126
+ export declare function httpRequestHeaders(method: HttpToolDef['method']): Record<string, string>;
127
+ /** The headers every MCP request is sent with, before the tool's own and its credential's. */
128
+ export declare const MCP_REQUEST_HEADERS: Readonly<Record<string, string>>;
119
129
  /** Preferred first. */
120
130
  export declare const MCP_PROTOCOL_VERSIONS: readonly ["2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26"];
121
131
  /**
@@ -150,6 +160,54 @@ export type McpRpcResponse = {
150
160
  export declare function parseMcpRpcResponse(text: string): McpRpcResponse;
151
161
  /** True when an MCP error says the server does not accept the protocol version sent. */
152
162
  export declare function isUnsupportedMcpProtocolError(error: McpRpcResponse['error']): boolean;
163
+ /** What the server answered when it was not a JSON-RPC message: its status and body. */
164
+ export type McpAnswer = {
165
+ status: number;
166
+ body: string;
167
+ };
168
+ /** One JSON-RPC request: a tool call names its tool, a list names none. */
169
+ export type McpRpcCall = {
170
+ id: string | number;
171
+ method: 'tools/call' | 'tools/list';
172
+ params: Record<string, unknown>;
173
+ /** The tool a `tools/call` names, sent as `Mcp-Name`. */
174
+ name?: string;
175
+ };
176
+ export type McpTransport = {
177
+ url: string;
178
+ /** Sent on every hop. */
179
+ headers: Record<string, string>;
180
+ /** Host headers and credentials: sent to the configured origin only. */
181
+ originBoundHeaders: Record<string, string>;
182
+ policy?: NetworkGuardrailSpec;
183
+ resolveHost?: ResolveHost;
184
+ fetch?: typeof fetch;
185
+ signal?: AbortSignal;
186
+ onCheck?: (ms: number) => void;
187
+ maxResponseBytes?: number;
188
+ /** Takes the call's claim before its first `tools/call` is sent; never before a session opens. */
189
+ beforeSend?: () => Promise<void>;
190
+ };
191
+ export type McpNegotiated = {
192
+ rpc?: McpRpcResponse;
193
+ /** The protocol version `rpc` was answered under. */
194
+ protocolVersion?: string;
195
+ failure?: ToolFailure;
196
+ refusal?: CredentialRefusal;
197
+ /** The server's status and body, when it answered with something other than JSON-RPC. */
198
+ answer?: McpAnswer;
199
+ lastProtocolError?: McpRpcResponse['error'];
200
+ /** The server refused a call without a session. */
201
+ sessionRequired?: boolean;
202
+ };
203
+ export declare function negotiateMcpRpc(transport: McpTransport, call: McpRpcCall): Promise<McpNegotiated>;
204
+ /** The call in a session: an expired one is reopened once, so a server can't loop us. */
205
+ export declare function negotiateInSession(transport: McpTransport, call: McpRpcCall, sessions: {
206
+ cache: McpSessionCache;
207
+ key: string;
208
+ use: McpSessionUse;
209
+ cached?: McpSession;
210
+ }): Promise<McpNegotiated>;
153
211
  /** Streamable HTTP, spec revision 2026-07-28. Order: schema → permission → auth → preTool/host stages → body. */
154
212
  export declare function executeMcpTool(tool: McpToolDef, rawInput: unknown, ctx: ToolContext, base: ToolCallBase, stages?: ToolStageSupport,
155
213
  /** The scope's sessions; without them a session lasts one call. */
@@ -460,7 +460,7 @@ async function* cappedPieces(response, maxBytes = Number.POSITIVE_INFINITY) {
460
460
  return true;
461
461
  }
462
462
  /** A body, read up to `maxBytes` when set; `undefined` when it runs past, with the rest left unread. */
463
- async function readCappedText(response, maxBytes) {
463
+ export async function readCappedText(response, maxBytes) {
464
464
  const pieces = cappedPieces(response, maxBytes);
465
465
  let text = '';
466
466
  for (;;) {
@@ -512,7 +512,7 @@ function tooLargeFailure(host, maxBytes) {
512
512
  };
513
513
  }
514
514
  /** The text with the credential replaced. */
515
- function omitSecretText(text, secret) {
515
+ export function omitSecretText(text, secret) {
516
516
  return text.replaceAll(secret, OMIT_CREDENTIAL);
517
517
  }
518
518
  /** Every string in `value` with the credential replaced. */
@@ -605,12 +605,20 @@ async function* readHttpBody(response, shown, secret, maxBytes) {
605
605
  return await readCappedText(response, maxBytes);
606
606
  return yield* readCappedTextShowing(response, shown, secret, maxBytes);
607
607
  }
608
+ /** The headers an HTTP tool's request is sent with, before its own and its credential's. */
609
+ export function httpRequestHeaders(method) {
610
+ return method === 'GET'
611
+ ? { Accept: 'application/json' }
612
+ : { Accept: 'application/json', 'Content-Type': 'application/json' };
613
+ }
614
+ /** The headers every MCP request is sent with, before the tool's own and its credential's. */
615
+ export const MCP_REQUEST_HEADERS = {
616
+ 'Content-Type': 'application/json',
617
+ Accept: 'application/json, text/event-stream',
618
+ };
608
619
  async function* sendHttpRequest(tool, targetUrl, body, { authHeaders, secret }, ctx, base, span, shown, handOff) {
609
620
  const checks = requestChecks(span);
610
- const headers = { Accept: 'application/json' };
611
- if (tool.method !== 'GET') {
612
- headers['Content-Type'] = 'application/json';
613
- }
621
+ const headers = httpRequestHeaders(tool.method);
614
622
  let timedOut;
615
623
  try {
616
624
  const place = tool.limit ? await takeLimitPlace(tool, tool.limit, ctx.signal) : undefined;
@@ -756,24 +764,29 @@ function unsupportedProtocolFromHttpBody(text) {
756
764
  }
757
765
  return undefined;
758
766
  }
759
- async function fetchMcpProtocolAttempt(transport, rpcId, mcpToolName, input, protocolVersion) {
760
- const jsonRpcPayload = {
761
- jsonrpc: '2.0',
767
+ /** A `tools/call` for `mcpToolName` with `input`. */
768
+ function mcpToolCall(rpcId, mcpToolName, input) {
769
+ return {
762
770
  id: rpcId,
763
771
  method: 'tools/call',
764
- params: {
765
- name: mcpToolName,
766
- arguments: input,
767
- _meta: mcpRequestMeta(protocolVersion),
768
- },
772
+ params: { name: mcpToolName, arguments: input },
773
+ name: mcpToolName,
774
+ };
775
+ }
776
+ async function fetchMcpProtocolAttempt(transport, call, protocolVersion) {
777
+ const jsonRpcPayload = {
778
+ jsonrpc: '2.0',
779
+ id: call.id,
780
+ method: call.method,
781
+ params: { ...call.params, _meta: mcpRequestMeta(protocolVersion) },
769
782
  };
770
783
  const response = await fetchGuarded(transport.url, {
771
784
  method: 'POST',
772
785
  headers: {
773
786
  ...transport.headers,
774
787
  'MCP-Protocol-Version': protocolVersion,
775
- 'Mcp-Method': jsonRpcPayload.method,
776
- 'Mcp-Name': mcpToolName,
788
+ 'Mcp-Method': call.method,
789
+ ...(call.name === undefined ? {} : { 'Mcp-Name': call.name }),
777
790
  },
778
791
  body: JSON.stringify(jsonRpcPayload),
779
792
  signal: transport.signal,
@@ -810,6 +823,7 @@ async function fetchMcpProtocolAttempt(transport, rpcId, mcpToolName, input, pro
810
823
  return {
811
824
  kind: 'failure',
812
825
  ...(refusal ? { refusal } : {}),
826
+ answer: { status: response.status, body: text },
813
827
  failure: {
814
828
  code: `mcp_http_${response.status}`,
815
829
  kind: kindOfToolHttpStatus(response.status),
@@ -827,6 +841,7 @@ async function fetchMcpProtocolAttempt(transport, rpcId, mcpToolName, input, pro
827
841
  catch {
828
842
  return {
829
843
  kind: 'failure',
844
+ answer: { status: response.status, body: text },
830
845
  failure: {
831
846
  code: 'invalid_response',
832
847
  kind: 'bad_response',
@@ -835,24 +850,34 @@ async function fetchMcpProtocolAttempt(transport, rpcId, mcpToolName, input, pro
835
850
  };
836
851
  }
837
852
  }
838
- async function negotiateMcpRpc(transport, rpcId, mcpToolName, input) {
853
+ export async function negotiateMcpRpc(transport, call) {
839
854
  let lastProtocolError;
840
855
  for (const protocolVersion of MCP_PROTOCOL_VERSIONS) {
841
- const outcome = await fetchMcpProtocolAttempt(transport, rpcId, mcpToolName, input, protocolVersion);
856
+ const outcome = await fetchMcpProtocolAttempt(transport, call, protocolVersion);
842
857
  if (outcome.kind === 'retry' || outcome.kind === 'protocol_retry') {
843
858
  if (outcome.kind === 'protocol_retry')
844
859
  lastProtocolError = outcome.error;
845
860
  continue;
846
861
  }
847
- if (outcome.kind === 'failure') {
848
- return { failure: outcome.failure, ...(outcome.refusal ? { refusal: outcome.refusal } : {}) };
849
- }
862
+ if (outcome.kind === 'failure')
863
+ return failureNegotiated(outcome);
850
864
  if (outcome.kind !== 'rpc')
851
865
  return { sessionRequired: true };
852
- return { rpc: outcome.response };
866
+ return { rpc: outcome.response, protocolVersion };
853
867
  }
854
868
  return { lastProtocolError };
855
869
  }
870
+ function failureNegotiated(outcome, sessionId) {
871
+ // why: A server can echo the session ID in its error; it goes no further than the server.
872
+ const hidden = (text) => (sessionId ? text.replaceAll(sessionId, '[session]') : text);
873
+ return {
874
+ failure: { ...outcome.failure, message: hidden(outcome.failure.message) },
875
+ ...(outcome.refusal ? { refusal: outcome.refusal } : {}),
876
+ ...(outcome.answer
877
+ ? { answer: { status: outcome.answer.status, body: hidden(outcome.answer.body) } }
878
+ : {}),
879
+ };
880
+ }
856
881
  const SESSION_HEADER = 'Mcp-Session-Id';
857
882
  /** The newest revision that has sessions; 2026-07-28 is stateless. */
858
883
  const SESSION_PROTOCOL_VERSION = '2025-11-25';
@@ -923,7 +948,7 @@ async function openMcpSession(transport) {
923
948
  return { id, protocolVersion };
924
949
  }
925
950
  /** The call in a session: an expired one is reopened once, so a server can't loop us. */
926
- async function negotiateInSession(transport, rpcId, mcpToolName, input, sessions) {
951
+ export async function negotiateInSession(transport, call, sessions) {
927
952
  let session = sessions.cached;
928
953
  for (let attempt = 0; attempt < 2; attempt++) {
929
954
  if (!session) {
@@ -939,22 +964,17 @@ async function negotiateInSession(transport, rpcId, mcpToolName, input, sessions
939
964
  const outcome = await fetchMcpProtocolAttempt({
940
965
  ...transport,
941
966
  originBoundHeaders: { ...transport.originBoundHeaders, [SESSION_HEADER]: session.id },
942
- }, rpcId, mcpToolName, input, session.protocolVersion);
967
+ }, call, session.protocolVersion);
943
968
  if (outcome.kind === 'session_expired') {
944
969
  sessions.cache.drop(sessions.key, session.id);
945
970
  session = undefined;
946
971
  continue;
947
972
  }
948
- if (outcome.kind === 'rpc')
949
- return { rpc: outcome.response };
950
- if (outcome.kind === 'failure') {
951
- // why: A server can echo the session ID in its error; it goes no further than the server.
952
- const failure = {
953
- ...outcome.failure,
954
- message: outcome.failure.message.replaceAll(session.id, '[session]'),
955
- };
956
- return { failure, ...(outcome.refusal ? { refusal: outcome.refusal } : {}) };
973
+ if (outcome.kind === 'rpc') {
974
+ return { rpc: outcome.response, protocolVersion: session.protocolVersion };
957
975
  }
976
+ if (outcome.kind === 'failure')
977
+ return failureNegotiated(outcome, session.id);
958
978
  return {
959
979
  lastProtocolError: outcome.kind === 'protocol_retry' ? outcome.error : undefined,
960
980
  };
@@ -1147,10 +1167,7 @@ async function* sendMcpRequest(tool, url, input, { authHeaders, secret }, ctx, b
1147
1167
  try {
1148
1168
  const transport = {
1149
1169
  url: url.href,
1150
- headers: {
1151
- 'Content-Type': 'application/json',
1152
- Accept: 'application/json, text/event-stream',
1153
- },
1170
+ headers: { ...MCP_REQUEST_HEADERS },
1154
1171
  originBoundHeaders: { ...tool.headers, ...authHeaders },
1155
1172
  policy: toolNetworkPolicy(ctx),
1156
1173
  resolveHost: ctx.resolveHost,
@@ -1164,21 +1181,13 @@ async function* sendMcpRequest(tool, url, input, { authHeaders, secret }, ctx, b
1164
1181
  };
1165
1182
  const key = await mcpSessionKey(url.href, transport.originBoundHeaders);
1166
1183
  const use = { tool: tool.name, ...tool.session };
1184
+ const call = mcpToolCall(base.callId, tool.mcpToolName, input);
1167
1185
  const cached = sessions.get(key, use);
1168
1186
  const first = cached
1169
- ? await negotiateInSession(transport, base.callId, tool.mcpToolName, input, {
1170
- cache: sessions,
1171
- key,
1172
- use,
1173
- cached,
1174
- })
1175
- : await negotiateMcpRpc(transport, base.callId, tool.mcpToolName, input);
1187
+ ? await negotiateInSession(transport, call, { cache: sessions, key, use, cached })
1188
+ : await negotiateMcpRpc(transport, call);
1176
1189
  const negotiated = first.sessionRequired
1177
- ? await negotiateInSession(transport, base.callId, tool.mcpToolName, input, {
1178
- cache: sessions,
1179
- key,
1180
- use,
1181
- })
1190
+ ? await negotiateInSession(transport, call, { cache: sessions, key, use })
1182
1191
  : first;
1183
1192
  const refused = yield* refusedCredentialOutcome(tool, negotiated.refusal, secret !== undefined, ctx, base);
1184
1193
  if (refused)
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import type { ToolPhaseEvent, TurnEvent } from '../turn-events.js';
7
7
  import type { StartedInvoke, StartedStep } from './invoke.js';
8
+ import type { InvokeToolStepRequest } from './types.js';
8
9
  /** The phase a call ends on: it completed, a gate held it, it failed, or it went on in the background. */
9
10
  export type SettledToolCall = Extract<ToolPhaseEvent, {
10
11
  phase: 'complete' | 'gate' | 'error' | 'background';
@@ -21,8 +22,23 @@ export type ToolCallResult = SettledToolCall & {
21
22
  export type ToolStepCallResult = ToolCallResult & {
22
23
  index: number;
23
24
  };
25
+ /** A step `runToolStep` runs, and what the host hears while it runs. */
26
+ export interface RunToolStepRequest extends InvokeToolStepRequest {
27
+ /**
28
+ * Your function that is given each of the step's events as it arrives, before the call it
29
+ * belongs to settles, such as a call's progress. Left out, you get only each call's end. A throw
30
+ * fails the step, as a throw from the invoke does.
31
+ *
32
+ * @remarks Called for every event the step emits, in order, before `runToolStep` yields the
33
+ * call that event settles.
34
+ */
35
+ onEvent?: (event: TurnEvent) => void;
36
+ }
24
37
  /** Run one call to its end. */
25
38
  declare function settledCall(started: StartedInvoke): Promise<ToolCallResult>;
26
- /** Run a step's calls, yielding each one's result as it settles; a call the step never settled comes last. */
27
- declare function settledCalls(started: StartedStep): AsyncGenerator<ToolStepCallResult>;
39
+ /**
40
+ * Run a step's calls, yielding each one's result as it settles; a call the step never settled comes
41
+ * last. `onEvent` hears each event first.
42
+ */
43
+ declare function settledCalls(started: StartedStep, onEvent?: (event: TurnEvent) => void): AsyncGenerator<ToolStepCallResult>;
28
44
  export { settledCall, settledCalls };
@@ -55,8 +55,11 @@ async function settledCall(started) {
55
55
  }
56
56
  return settle(fold, invokeError);
57
57
  }
58
- /** Run a step's calls, yielding each one's result as it settles; a call the step never settled comes last. */
59
- async function* settledCalls(started) {
58
+ /**
59
+ * Run a step's calls, yielding each one's result as it settles; a call the step never settled comes
60
+ * last. `onEvent` hears each event first.
61
+ */
62
+ async function* settledCalls(started, onEvent) {
60
63
  const folds = started.calls.map(({ name, callId }) => ({
61
64
  name,
62
65
  callId,
@@ -66,6 +69,7 @@ async function* settledCalls(started) {
66
69
  const yielded = new Set();
67
70
  let invokeError;
68
71
  for await (const event of started.events) {
72
+ onEvent?.(event);
69
73
  if (event.type === 'error')
70
74
  invokeError = event;
71
75
  if (event.type !== 'tool')
@@ -166,6 +166,7 @@ export type SignedInRequest = {
166
166
  * throws; the kernel turns it into a new sign-in or `sign_in.out_of_scope`.
167
167
  */
168
168
  export type SignedInFetch = (url: string | URL, request?: SignedInRequest) => Promise<Response>;
169
+ /** What a streaming handler (an async generator function) yields; only `complete` is its output. */
169
170
  export type ToolStreamEvent<TOut = unknown> = {
170
171
  kind: 'progress';
171
172
  data: unknown;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.5-next.966.g19b460d",
3
+ "version": "0.3.5-next.970.g11bd0cf",
4
4
  "description": "A flat TypeScript agent kernel for typed profiles, deterministic turn execution, registered tools, provider adapters, guardrails, and host-injected traces.",
5
5
  "keywords": [
6
6
  "agent",