@theoremjs/agents 0.3.5-next.965.gc64f194 → 0.3.5-next.967.gd19ced6

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`, `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
@@ -76,8 +76,8 @@ export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ToolRegistry,
76
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';
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';
@@ -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
  }
@@ -75,9 +75,11 @@ export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ToolRegistry,
75
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';
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
+ export { toolAuthForCall } from './tools/registry.js';
79
+ export type { RunToolStepRequest, SettledToolCall, ToolCallResult, ToolStepCallResult, } from './tools/run.js';
78
80
  export { jsonSchemaFromZod } from './tools/schema.js';
79
81
  export { CredentialRefusedError } from './tools/signed-in-fetch.js';
80
- export type { ModelToolResult, PageAnswer, ToolAuthConfig, ToolContext, ToolLabels, ToolMediaEntry, } from './tools/types.js';
82
+ export type { ModelToolResult, PageAnswer, ToolAuthConfig, ToolAuthFor, ToolContext, ToolLabels, ToolMediaEntry, ToolStreamEvent, } from './tools/types.js';
81
83
  export { awaitingUserInputSchema, type GateReference, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, type ToolOutputPart, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './turn-events.js';
82
84
  export type * from './types.js';
83
85
  export { base64ToBytes, bytesToBase64 } from './util/base64.js';
@@ -45,6 +45,7 @@ export { answerGatedCall, GATE_DECISIONS, gateExpired, resolveGateTtlMs, session
45
45
  export { createMemoryToolExecution } from './tools/memory-execution.js';
46
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';
47
47
  export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, toolOperationReplySchema, } from './tools/operation.js';
48
+ export { toolAuthForCall } from './tools/registry.js';
48
49
  export { jsonSchemaFromZod } from './tools/schema.js';
49
50
  export { CredentialRefusedError } from './tools/signed-in-fetch.js';
50
51
  export { awaitingUserInputSchema, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './turn-events.js';
@@ -909,7 +909,7 @@ export const EXTRA_FIELDS = withFieldDocs({
909
909
  unset: 'The model can fill every channel the profile takes',
910
910
  },
911
911
  'registerTool.auth': {
912
- ...field('ToolAuthConfig'),
912
+ ...field('ToolAuthConfig | ToolAuthFor'),
913
913
  unset: 'No credential',
914
914
  },
915
915
  'registerTool.auth.type': field(unionType(TOOL_AUTH_TYPES), TOOL_AUTH_TYPES, OPTION_DOCS.TOOL_AUTH_TYPES),
@@ -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),
@@ -125,7 +125,12 @@ function toolCanGate(tool) {
125
125
  return false;
126
126
  if (tool.permission !== 'auto')
127
127
  return true;
128
- return ('auth' in tool && tool.auth !== undefined && (tool.auth.onUnauthenticated ?? 'gate') === 'gate');
128
+ if (!('auth' in tool) || tool.auth === undefined)
129
+ return false;
130
+ // why: Which sign-in, and so whether it gates, is only known once a call picks it.
131
+ if (typeof tool.auth === 'function')
132
+ return true;
133
+ return (tool.auth.onUnauthenticated ?? 'gate') === 'gate';
129
134
  }
130
135
  /** Why `profile` can't be run by an agent tool, or `undefined` when it can. */
131
136
  function agentProfileProblem(profile, find) {
@@ -10,7 +10,7 @@ import { type AgentCaller } from './agent.js';
10
10
  import { type ToolBackgroundSupport } from './background.js';
11
11
  import { startToolExecution, type ToolCallBase } from './events.js';
12
12
  import type { ToolExecutionCoordinator, ToolOperationClaim, ToolOperationOutcome } from './operation.js';
13
- import type { ToolRegistry } from './registry.js';
13
+ import { type ToolRegistry } from './registry.js';
14
14
  import { type ToolStageSupport } from './stage-run.js';
15
15
  import type { FunctionToolDef, ModelToolResult, RegisteredAgentTool, RegisteredTool, ToolContext, ToolFailure, ToolGate, TurnToolSnapshot } from './types.js';
16
16
  export { checkPermission, isGateResumeGranted, isResumeContinuation, permissionGranted, } from './permission.js';
@@ -24,6 +24,7 @@ import { formatToolFailureForModel, formatToolResult, frameToolFailure } from '.
24
24
  import { agentOutputSchema, markedFieldsIn, outputForModel } from './model-view.js';
25
25
  import { operationBroken, operationWireValue } from './operation.js';
26
26
  import { checkPermission, gateDetails, isGateResumeDenied, isGateResumeGranted, isResumeContinuation, } from './permission.js';
27
+ import { toolAuthForCall } from './registry.js';
27
28
  import { executeHttpTool, executeMcpTool, failureWithoutSecret, modelResultFromOutput, omitSecret, outcomeFromUnauth, parseToolOutput, refusedCredentialOutcome, resolveToolAuth, withMedia, } from './remote.js';
28
29
  import { extractLoadedIds, profileToolAllow, profileToolsSpec, promoteLoadedTools, } from './resolve.js';
29
30
  import { plainToolInput } from './schema.js';
@@ -488,9 +489,10 @@ function makeReproject(parse, project, labels) {
488
489
  }
489
490
  /** Order as for remote tools: schema → permission → auth → preTool/host stages → body. */
490
491
  async function* resolveFunctionSignIn(tool, ctx, base) {
491
- if (!tool.auth)
492
+ const auth = fixedAuth(tool);
493
+ if (!auth)
492
494
  return {};
493
- const resolved = yield* resolveToolAuth(tool.name, tool.auth, ctx, base);
495
+ const resolved = yield* resolveToolAuth(tool.name, auth, ctx, base);
494
496
  const outcome = outcomeFromUnauth(resolved);
495
497
  if (outcome)
496
498
  return { outcome };
@@ -616,7 +618,7 @@ agent, beginBody) {
616
618
  throw err;
617
619
  if (signedIn.prepared && err instanceof CredentialRefusedError) {
618
620
  checks.record();
619
- const refused = yield* refusedCredentialOutcome(tool, err.refusal, signedIn.secret !== undefined, ctx, base);
621
+ const refused = yield* refusedCredentialOutcome({ name: tool.name, auth: fixedAuth(tool) }, err.refusal, signedIn.secret !== undefined, ctx, base);
620
622
  if (refused)
621
623
  return yield* settleOutcome(refused);
622
624
  }
@@ -833,7 +835,28 @@ function turnReadBack({ modelResult }) {
833
835
  function signInService(tool, resume) {
834
836
  if (!resume?.signIn || tool.type === 'builtin' || tool.type === 'agent')
835
837
  return undefined;
836
- return tool.auth?.service;
838
+ return fixedAuth(tool)?.service;
839
+ }
840
+ /** A tool's sign-in for this call; `pinCallAuth` has already picked one the input chooses. */
841
+ function fixedAuth(tool) {
842
+ if (typeof tool.auth !== 'function')
843
+ return tool.auth;
844
+ throw new TheoremError('config', `Tool "${tool.name}" reached its sign-in before the call picked one`);
845
+ }
846
+ /**
847
+ * The tool with the sign-in its `auth` function picks from this call's input, so the gate, the
848
+ * resume and the notes all read one fixed sign-in. Input the schema refuses picks none; the call
849
+ * then fails on its input before anything signs in.
850
+ */
851
+ function pinCallAuth(tool, input) {
852
+ if (tool.type !== 'function' || typeof tool.auth !== 'function')
853
+ return { tool };
854
+ try {
855
+ return { tool: { ...tool, auth: toolAuthForCall(tool, input) } };
856
+ }
857
+ catch (err) {
858
+ return { failure: functionHandlerFailure(err) };
859
+ }
837
860
  }
838
861
  /**
839
862
  * A gate nobody answered: a sign-in for `expiredService` whose link expired, or any other gate
@@ -996,7 +1019,8 @@ async function* executeTracedTool(args) {
996
1019
  }
997
1020
  }
998
1021
  }
999
- async function* runRegisteredTool(args, tool) {
1022
+ async function* runRegisteredTool(args, registered) {
1023
+ let tool = registered;
1000
1024
  const { profile, name, callId, ctx, snapshot, stages } = args;
1001
1025
  const { input } = splitBackground(tool?.type === 'builtin' ? undefined : tool, args.input);
1002
1026
  const safeInput = plainToolInput(input);
@@ -1041,6 +1065,12 @@ async function* runRegisteredTool(args, tool) {
1041
1065
  yield failureEvent(base, eligibility);
1042
1066
  return earlyFailure(eligibility);
1043
1067
  }
1068
+ const pinned = pinCallAuth(tool, safeInput);
1069
+ if ('failure' in pinned) {
1070
+ yield failureEvent(base, pinned.failure);
1071
+ return earlyFailure(pinned.failure);
1072
+ }
1073
+ tool = pinned.tool;
1044
1074
  if (isGateResumeDenied(ctx.resume)) {
1045
1075
  return yield* settleToolFailure(resultGuard(args.tools, tool, { ...ctx, callId, profile, operationId }, snapshot, stages?.span), base, refusalFailure(tool, ctx.resume, profile.labels), stages, { toolName: name, callId, input: safeInput, callNotStarted: true, denied: true });
1046
1076
  }
@@ -2,9 +2,15 @@ import type { Profile, ProfileId } from '../types.js';
2
2
  import { type ToolBackground } from './background.js';
3
3
  import { type McpSessionCache } from './mcp-sessions.js';
4
4
  import { type JsonSchema } from './schema.js';
5
- import type { FunctionToolDef, HttpToolDef, McpToolDef, RegisteredTool, ToolDefinitionInput } from './types.js';
5
+ import type { FunctionToolDef, HttpToolDef, McpToolDef, RegisteredTool, ToolAuthConfig, ToolDefinitionInput } from './types.js';
6
+ /**
7
+ * The sign-in a tool uses for one call: its `auth`, or what its `auth` function picks from the
8
+ * call's input, checked as a registered one is. Input the schema refuses picks none. Throws what
9
+ * the function throws, or a `config` error for a pick that fails the checks.
10
+ */
11
+ export declare function toolAuthForCall(tool: RegisteredTool, input: unknown): ToolAuthConfig | undefined;
6
12
  /** The settings of a tool's definition that are plain values: every check `register` makes without running or converting anything. */
7
- declare function assertToolSettings(def: Pick<HttpToolDef, 'name'> & Partial<Pick<HttpToolDef, 'endpoint' | 'auth' | 'mapping' | 'limit' | 'timeoutMs'> & Pick<HttpToolDef, 'maxResponseBytes' | 'imageLimits'> & Pick<McpToolDef, 'session'> & Pick<FunctionToolDef, 'answeredBy'>> & {
13
+ declare function assertToolSettings(def: Pick<HttpToolDef, 'name'> & Partial<Pick<HttpToolDef, 'endpoint' | 'mapping' | 'limit' | 'timeoutMs'> & Pick<FunctionToolDef, 'auth'> & Pick<HttpToolDef, 'maxResponseBytes' | 'imageLimits'> & Pick<McpToolDef, 'session'> & Pick<FunctionToolDef, 'answeredBy'>> & {
8
14
  type?: string;
9
15
  background?: ToolBackground;
10
16
  }): void;
@@ -50,6 +50,24 @@ function schemasFromZod(def) {
50
50
  // invariant: Each registration gets its own copy, so nothing a tool does to its schemas reaches another.
51
51
  return { inputSchema: structuredClone(inputSchema), outputSchema: structuredClone(outputSchema) };
52
52
  }
53
+ /**
54
+ * The sign-in a tool uses for one call: its `auth`, or what its `auth` function picks from the
55
+ * call's input, checked as a registered one is. Input the schema refuses picks none. Throws what
56
+ * the function throws, or a `config` error for a pick that fails the checks.
57
+ */
58
+ export function toolAuthForCall(tool, input) {
59
+ if (!('auth' in tool))
60
+ return undefined;
61
+ if (typeof tool.auth !== 'function')
62
+ return tool.auth;
63
+ const parsed = tool.input.safeParse(input);
64
+ if (!parsed.success)
65
+ return undefined;
66
+ const auth = tool.auth(parsed.data);
67
+ assertAuthService(tool.name, auth);
68
+ assertQueryParam(tool.name, auth);
69
+ return auth;
70
+ }
53
71
  /** The person is told which service they sign in to; the tool's builder names it, never the model or the server. */
54
72
  function assertAuthService(name, auth) {
55
73
  if (auth && (typeof auth.service !== 'string' || !auth.service.trim())) {
@@ -116,16 +134,18 @@ function assertToolSettings(def) {
116
134
  }
117
135
  if (def.type === 'builtin' || def.type === 'agent')
118
136
  return;
119
- assertAuthService(def.name, def.auth);
137
+ // why: A sign-in a function picks per call is checked on each call, by `toolAuthForCall`.
138
+ const auth = typeof def.auth === 'function' ? undefined : def.auth;
139
+ assertAuthService(def.name, auth);
120
140
  if (def.type === 'http') {
121
141
  if (def.endpoint?.trim())
122
142
  assertFixedEndpointOrigin(def.endpoint);
123
- assertQueryParam(def.name, def.auth, def.mapping?.queryParams);
143
+ assertQueryParam(def.name, auth, def.mapping?.queryParams);
124
144
  assertLimit(def.name, def.limit);
125
145
  assertTimeout(def.name, def.timeoutMs);
126
146
  }
127
147
  else {
128
- assertQueryParam(def.name, def.auth);
148
+ assertQueryParam(def.name, auth);
129
149
  }
130
150
  if (def.type === 'http' || def.type === 'mcp')
131
151
  assertReadLimits(def);
@@ -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;
@@ -312,10 +313,14 @@ export interface FunctionToolDef<TIn = unknown, TOut = unknown> extends ToolBase
312
313
  *
313
314
  * @remarks The service the handler acts on for the person. The kernel resolves the slot before
314
315
  * the handler runs (gating, refreshing, or telling the model as the policy says) and hands the
315
- * handler `ctx.signedInFetch`; the handler never sees the credential.
316
+ * handler `ctx.signedInFetch`; the handler never sees the credential. A function of the call's
317
+ * input picks the sign-in per call, for a tool that acts on whichever service the input names;
318
+ * `undefined` from it means the call needs none.
316
319
  */
317
- auth?: ToolAuthConfig;
320
+ auth?: ToolAuthConfig | ToolAuthFor<TIn>;
318
321
  }
322
+ /** Picks a function tool's sign-in from the call's input; `undefined` when the call needs none. */
323
+ export type ToolAuthFor<TIn> = (input: TIn) => ToolAuthConfig | undefined;
319
324
  /** How a tool that acts for the person signs in to the service; http, mcp, and function tools share it. */
320
325
  export interface ToolAuthConfig {
321
326
  /** Which of the credentials the turn passes in this tool uses. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.5-next.965.gc64f194",
3
+ "version": "0.3.5-next.967.gd19ced6",
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",