@theoremjs/agents 0.3.5-next.964.gc93d0c4 → 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.
@@ -1,4 +1,5 @@
1
- import type { AuthorizationServerMetadata, CreatePkceFlowOptions, ExchangePkceCodeOptions, ExchangePkceCodeResult, OAuthTransportOptions, PkceFlowResult, ProtectedResourceMetadata, RefreshOAuthTokenOptions } from './types.js';
1
+ import { TheoremError } from '../../guardrails/theorem-error.js';
2
+ import type { AuthorizationServerMetadata, CreatePkceFlowOptions, ExchangePkceCodeOptions, ExchangePkceCodeResult, OAuthRevocation, OAuthTransportOptions, PkceFlowResult, ProtectedResourceMetadata, RefreshOAuthTokenOptions, RevokeOAuthTokenOptions } from './types.js';
2
3
  /** `undefined` on HTTP 404. RFC 9728 §3.3: a `resource` not identical to `resourceUrl` is refused. */
3
4
  export declare function discoverResourceMetadata(resourceUrl: string, transport?: OAuthTransportOptions): Promise<ProtectedResourceMetadata | undefined>;
4
5
  /** A non-OK URL moves on to the next; metadata that answers but fails validation is refused outright. */
@@ -7,12 +8,47 @@ export declare function discoverAuthServerMetadata(issuer: string, transport?: O
7
8
  export declare function createOAuthPkceFlow(options: CreatePkceFlowOptions): Promise<PkceFlowResult>;
8
9
  /** RFC 9207 §2.4: `iss` is required when the server advertises it, and byte-exact (no URL normalization). */
9
10
  export declare function validateIssuer(expectedIssuer: string, receivedIss: string | undefined, issRequired: boolean): void;
11
+ /**
12
+ * A token, refresh, or revocation endpoint answered with an error. `kind` is `auth` when the
13
+ * grant or client was refused (`invalid_grant`, `invalid_client`, HTTP 401), so the user signs
14
+ * in again; otherwise it follows the HTTP status, so a 5xx is `unavailable` or `busy` and a
15
+ * 429 is `rate_limit`. A request that never got an answer throws the network's own
16
+ * `TheoremError` instead.
17
+ */
18
+ export declare class OAuthTokenError extends TheoremError {
19
+ /** The endpoint's HTTP status. */
20
+ readonly status: number;
21
+ /** The RFC 6749 §5.2 `error` code, when the body carried a well-formed one. */
22
+ readonly error?: string;
23
+ /** The RFC 6749 §5.2 `error_description`, when it is printable ASCII. */
24
+ readonly errorDescription?: string;
25
+ constructor(message: string, refusal: {
26
+ status: number;
27
+ error?: string;
28
+ errorDescription?: string;
29
+ });
30
+ }
10
31
  /**
11
32
  * Requires the session that began the flow (RFC 6749 §10.12), the same `redirect_uri` (§4.1.3)
12
33
  * and a valid `iss` (RFC 9207); posts to the token endpoint sealed in `state`, never a caller's.
13
34
  */
14
35
  export declare function exchangeOAuthPkce(options: ExchangePkceCodeOptions): Promise<ExchangePkceCodeResult>;
15
- /** Exchanges a refresh token for new tokens at the token endpoint; both the endpoint and the resource must be https URLs. */
36
+ /**
37
+ * Exchanges a refresh token for new tokens at the token endpoint; both the endpoint and the
38
+ * resource must be https URLs. A refusal throws `OAuthTokenError`.
39
+ */
16
40
  export declare function refreshOAuthToken(options: RefreshOAuthTokenOptions): Promise<ExchangePkceCodeResult>;
41
+ /**
42
+ * RFC 7009: asks the authorization server to forget a sign-in. The refresh token is revoked
43
+ * first, since §2.1 has that end the grant's access tokens too; the access token is revoked
44
+ * when there is no refresh token or the server does not revoke refresh tokens. The endpoint is
45
+ * `revocationEndpoint` when given, else the issuer's `revocation_endpoint` metadata.
46
+ *
47
+ * @returns `revoked` on HTTP 200, which per §2.2 also answers a token the server already
48
+ * dropped; `already_invalid` when the server says so with `invalid_token` or `invalid_grant`;
49
+ * `unsupported` when the issuer names no revocation endpoint or revokes neither token type.
50
+ * Any other refusal throws `OAuthTokenError`.
51
+ */
52
+ export declare function revokeOAuthToken(options: RevokeOAuthTokenOptions): Promise<OAuthRevocation>;
17
53
  /** RFC 8707: the same origin, and the resource's path or below it. */
18
54
  export declare function tokenAudienceCovers(resource: string, url: URL): boolean;
@@ -1,4 +1,6 @@
1
+ import { kindOfHttpStatus } from '../../guardrails/error.js';
1
2
  import { fetchGuarded } from '../../guardrails/network.js';
3
+ import { TheoremError } from '../../guardrails/theorem-error.js';
2
4
  import { isRecord } from '../util/record.js';
3
5
  import { computeCodeChallenge, generateCodeVerifier, sealStatePayload, toBase64Url, unsealStatePayload, } from './crypto.js';
4
6
  const HTTP_NOT_FOUND = 404;
@@ -145,11 +147,15 @@ function parseAuthServerMetadata(data, issuer, url) {
145
147
  const registrationEndpoint = data.registration_endpoint === undefined
146
148
  ? undefined
147
149
  : httpsUrl(data.registration_endpoint, 'registration_endpoint');
150
+ const revocationEndpoint = data.revocation_endpoint === undefined
151
+ ? undefined
152
+ : httpsUrl(data.revocation_endpoint, 'revocation_endpoint');
148
153
  return {
149
154
  issuer,
150
155
  authorization_endpoint: authorizationEndpoint.href,
151
156
  token_endpoint: tokenEndpoint.href,
152
157
  registration_endpoint: registrationEndpoint?.href,
158
+ revocation_endpoint: revocationEndpoint?.href,
153
159
  scopes_supported: stringList(data, 'scopes_supported'),
154
160
  response_types_supported: stringList(data, 'response_types_supported'),
155
161
  grant_types_supported: stringList(data, 'grant_types_supported'),
@@ -288,21 +294,60 @@ export function validateIssuer(expectedIssuer, receivedIss, issRequired) {
288
294
  /** RFC 6749 §5.2: `error_description` is printable ASCII without `"` or `\`. */
289
295
  const ERROR_DESCRIPTION = /^[\x20\x21\x23-\x5B\x5D-\x7E]*$/;
290
296
  /** RFC 6749 §5.2 shape only; any other body is not repeated into the error. */
291
- async function tokenErrorText(response) {
297
+ async function tokenErrorBody(response) {
292
298
  let data;
293
299
  try {
294
300
  data = await response.json();
295
301
  }
296
302
  catch {
297
- return '';
303
+ return {};
298
304
  }
299
305
  if (!isRecord(data))
300
- return '';
306
+ return {};
301
307
  const { error, error_description: description } = data;
302
308
  if (typeof error !== 'string' || !ERROR_DESCRIPTION.test(error))
303
- return '';
309
+ return {};
304
310
  const told = typeof description === 'string' && ERROR_DESCRIPTION.test(description);
305
- return told ? `: ${error} (${description})` : `: ${error}`;
311
+ return told ? { error, errorDescription: description } : { error };
312
+ }
313
+ /** RFC 6749 §5.2: the grant or the client was refused, so only a new sign-in or new client credentials help. */
314
+ const REFUSED_GRANT = new Set(['invalid_grant', 'invalid_client']);
315
+ /**
316
+ * A token, refresh, or revocation endpoint answered with an error. `kind` is `auth` when the
317
+ * grant or client was refused (`invalid_grant`, `invalid_client`, HTTP 401), so the user signs
318
+ * in again; otherwise it follows the HTTP status, so a 5xx is `unavailable` or `busy` and a
319
+ * 429 is `rate_limit`. A request that never got an answer throws the network's own
320
+ * `TheoremError` instead.
321
+ */
322
+ export class OAuthTokenError extends TheoremError {
323
+ /** The endpoint's HTTP status. */
324
+ status;
325
+ /** The RFC 6749 §5.2 `error` code, when the body carried a well-formed one. */
326
+ error;
327
+ /** The RFC 6749 §5.2 `error_description`, when it is printable ASCII. */
328
+ errorDescription;
329
+ constructor(message, refusal) {
330
+ const refused = refusal.error !== undefined && REFUSED_GRANT.has(refusal.error);
331
+ super(refused ? 'auth' : kindOfHttpStatus(refusal.status), message);
332
+ this.name = 'OAuthTokenError';
333
+ this.status = refusal.status;
334
+ if (refusal.error !== undefined)
335
+ this.error = refusal.error;
336
+ if (refusal.errorDescription !== undefined)
337
+ this.errorDescription = refusal.errorDescription;
338
+ }
339
+ }
340
+ async function tokenEndpointError(response, failed, endpoint) {
341
+ const body = await tokenErrorBody(response);
342
+ const said = body.error === undefined
343
+ ? ''
344
+ : body.errorDescription === undefined
345
+ ? `: ${body.error}`
346
+ : `: ${body.error} (${body.errorDescription})`;
347
+ return new OAuthTokenError(`${failed} at ${endpoint} (HTTP ${response.status})${said}`, {
348
+ status: response.status,
349
+ ...body,
350
+ });
306
351
  }
307
352
  function parseTokenResponse(data, tokenEndpoint) {
308
353
  const fail = (why) => {
@@ -368,7 +413,7 @@ async function requestToken(transport, grant, params, requested, previous) {
368
413
  }, transport);
369
414
  if (!response.ok) {
370
415
  const failed = previous ? 'Token refresh failed' : 'Token exchange failed'; // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
371
- throw new Error(`${failed} at ${grant.tokenEndpoint} (HTTP ${response.status})${await tokenErrorText(response)}`);
416
+ throw await tokenEndpointError(response, failed, grant.tokenEndpoint);
372
417
  }
373
418
  const tokens = parseTokenResponse(await response.json(), grant.tokenEndpoint);
374
419
  assertGrantWithin(tokens.scope, requested, grant.tokenEndpoint);
@@ -409,7 +454,10 @@ export async function exchangeOAuthPkce(options) {
409
454
  code_verifier: state.codeVerifier,
410
455
  }, state.scopes);
411
456
  }
412
- /** Exchanges a refresh token for new tokens at the token endpoint; both the endpoint and the resource must be https URLs. */
457
+ /**
458
+ * Exchanges a refresh token for new tokens at the token endpoint; both the endpoint and the
459
+ * resource must be https URLs. A refusal throws `OAuthTokenError`.
460
+ */
413
461
  export function refreshOAuthToken(options) {
414
462
  httpsUrl(options.tokenEndpoint, 'token_endpoint');
415
463
  httpsUrl(options.resource, 'resource');
@@ -425,6 +473,60 @@ export function refreshOAuthToken(options) {
425
473
  ...(options.scope ? { scope: options.scope } : {}),
426
474
  }, scopeTokens(options.scope), { refreshToken: options.refreshToken, scope: options.scope });
427
475
  }
476
+ /**
477
+ * RFC 7009 §2.2.1 lets a server name an error; some answer an unknown or expired token with
478
+ * `invalid_token` (RFC 6750) or `invalid_grant` (RFC 6749) instead of the 200 §2.2 asks for.
479
+ */
480
+ const ALREADY_INVALID = new Set(['invalid_token', 'invalid_grant']);
481
+ async function revokeOne(endpoint, token, hint, options) {
482
+ const body = new URLSearchParams({
483
+ token,
484
+ token_type_hint: hint,
485
+ client_id: options.credential.clientId,
486
+ ...(options.clientSecret === undefined ? {} : { client_secret: options.clientSecret }),
487
+ });
488
+ const response = await oauthFetch(endpoint, {
489
+ method: 'POST',
490
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
491
+ body: body.toString(),
492
+ }, options);
493
+ if (response.ok) {
494
+ await response.body?.cancel();
495
+ return 'revoked';
496
+ }
497
+ const failure = await tokenEndpointError(response, 'Token revocation failed', endpoint); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
498
+ if (failure.error === 'unsupported_token_type')
499
+ return 'unsupported_token_type';
500
+ if (failure.error !== undefined && ALREADY_INVALID.has(failure.error))
501
+ return 'already_invalid';
502
+ throw failure;
503
+ }
504
+ /**
505
+ * RFC 7009: asks the authorization server to forget a sign-in. The refresh token is revoked
506
+ * first, since §2.1 has that end the grant's access tokens too; the access token is revoked
507
+ * when there is no refresh token or the server does not revoke refresh tokens. The endpoint is
508
+ * `revocationEndpoint` when given, else the issuer's `revocation_endpoint` metadata.
509
+ *
510
+ * @returns `revoked` on HTTP 200, which per §2.2 also answers a token the server already
511
+ * dropped; `already_invalid` when the server says so with `invalid_token` or `invalid_grant`;
512
+ * `unsupported` when the issuer names no revocation endpoint or revokes neither token type.
513
+ * Any other refusal throws `OAuthTokenError`.
514
+ */
515
+ export async function revokeOAuthToken(options) {
516
+ const { credential } = options;
517
+ const endpoint = options.revocationEndpoint === undefined
518
+ ? (await discoverAuthServerMetadata(credential.issuer, options)).revocation_endpoint
519
+ : httpsUrl(options.revocationEndpoint, 'revocation_endpoint').href;
520
+ if (endpoint === undefined)
521
+ return 'unsupported';
522
+ if (credential.refreshToken) {
523
+ const answer = await revokeOne(endpoint, credential.refreshToken, 'refresh_token', options);
524
+ if (answer !== 'unsupported_token_type')
525
+ return answer;
526
+ }
527
+ const answer = await revokeOne(endpoint, credential.accessToken, 'access_token', options);
528
+ return answer === 'unsupported_token_type' ? 'unsupported' : answer;
529
+ }
428
530
  /** RFC 8707: the same origin, and the resource's path or below it. */
429
531
  export function tokenAudienceCovers(resource, url) {
430
532
  let audience;
@@ -15,6 +15,8 @@ export interface AuthorizationServerMetadata {
15
15
  authorization_endpoint: string;
16
16
  token_endpoint: string;
17
17
  registration_endpoint?: string;
18
+ /** RFC 7009 §4 (via RFC 8414 §2). */
19
+ revocation_endpoint?: string;
18
20
  scopes_supported?: string[];
19
21
  response_types_supported?: string[];
20
22
  grant_types_supported?: string[];
@@ -150,3 +152,14 @@ export interface RefreshOAuthTokenOptions extends OAuthTransportOptions {
150
152
  /** A confidential client's secret, sent in the token request body (RFC 6749 §2.3.1); never stored. */
151
153
  clientSecret?: string;
152
154
  }
155
+ /** Options for revoking a sign-in at its authorization server (RFC 7009). */
156
+ export interface RevokeOAuthTokenOptions extends OAuthTransportOptions {
157
+ /** Its refresh token is revoked first, else its access token; its `issuer` finds the endpoint. */
158
+ credential: Pick<OAuth2Credential, 'issuer' | 'clientId' | 'accessToken' | 'refreshToken'>;
159
+ /** Skips discovery; an https URL. */
160
+ revocationEndpoint?: string;
161
+ /** A confidential client's secret, sent in the request body (RFC 6749 §2.3.1); never stored. */
162
+ clientSecret?: string;
163
+ }
164
+ /** What the authorization server did with a revoked sign-in. */
165
+ export type OAuthRevocation = 'revoked' | 'already_invalid' | 'unsupported';
@@ -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.964.gc93d0c4",
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",