@theoremjs/agents 0.3.5-next.965.gc64f194 → 0.3.5-next.966.g19b460d

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.
@@ -75,9 +75,10 @@ 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';
78
79
  export { jsonSchemaFromZod } from './tools/schema.js';
79
80
  export { CredentialRefusedError } from './tools/signed-in-fetch.js';
80
- export type { ModelToolResult, PageAnswer, ToolAuthConfig, ToolContext, ToolLabels, ToolMediaEntry, } from './tools/types.js';
81
+ export type { ModelToolResult, PageAnswer, ToolAuthConfig, ToolAuthFor, ToolContext, ToolLabels, ToolMediaEntry, } from './tools/types.js';
81
82
  export { awaitingUserInputSchema, type GateReference, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, type ToolOutputPart, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './turn-events.js';
82
83
  export type * from './types.js';
83
84
  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),
@@ -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);
@@ -312,10 +312,14 @@ export interface FunctionToolDef<TIn = unknown, TOut = unknown> extends ToolBase
312
312
  *
313
313
  * @remarks The service the handler acts on for the person. The kernel resolves the slot before
314
314
  * 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.
315
+ * handler `ctx.signedInFetch`; the handler never sees the credential. A function of the call's
316
+ * input picks the sign-in per call, for a tool that acts on whichever service the input names;
317
+ * `undefined` from it means the call needs none.
316
318
  */
317
- auth?: ToolAuthConfig;
319
+ auth?: ToolAuthConfig | ToolAuthFor<TIn>;
318
320
  }
321
+ /** Picks a function tool's sign-in from the call's input; `undefined` when the call needs none. */
322
+ export type ToolAuthFor<TIn> = (input: TIn) => ToolAuthConfig | undefined;
319
323
  /** How a tool that acts for the person signs in to the service; http, mcp, and function tools share it. */
320
324
  export interface ToolAuthConfig {
321
325
  /** 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.966.g19b460d",
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",