/** * Tool Manifest & Permission — scope enforcement for AI agent tool calls. * * A ToolManifest declares the permission level (read/write/delete/admin) * required for each tool on a connector. The `enforce()` method on the * Grantex client uses loaded manifests to check whether a grant token's * scopes allow a given tool call. * * @example * ```ts * import { ToolManifest, Permission } from '@grantex/sdk'; * * const manifest = new ToolManifest({ * connector: 'salesforce', * tools: { * query: Permission.READ, * create_lead: Permission.WRITE, * delete_contact: Permission.DELETE, * }, * }); * ``` */ import type { DenialReason } from './denials.js'; import type { CapLimit, CapsMode, Reservation } from './caps/meter.js'; import type { DecisionAction } from './decisions/action.js'; import type { ConsumedDecision } from './resources/decisions.js'; /** Permission levels for tool operations. */ export declare enum Permission { READ = "read", WRITE = "write", DELETE = "delete", ADMIN = "admin" } /** * Check whether a granted permission level covers the required level. * * Hierarchy: `admin > delete > write > read` * * - A `write` scope covers `read` + `write` tools. * - A `delete` scope covers `read` + `write` + `delete` tools. * - An `admin` scope covers everything. */ export declare function permissionCovers(granted: string, required: string): boolean; /** `$id` of the manifest 0.6 JSON Schema. */ export declare const MANIFEST_SCHEMA_ID = "https://grantex.dev/spec/manifest-0.6.schema.json"; /** Largest cap or cost-unit value a manifest may declare. */ export declare const MAX_COUNT = 2147483647; /** Not allowed as a tool name: grant `caps` use it for the cost-unit budget. */ export declare const RESERVED_TOOL_NAME = "cost_units"; /** Workload risk tiers a tool may declare; `high` needs a decision grant on every call. */ export declare const RISK_TIERS: readonly ['low', 'medium', 'high']; export type RiskTier = (typeof RISK_TIERS)[number]; /** Most extra semantic fields a tool may declare for decision grants. */ export declare const MAX_DECISION_FIELDS = 16; /** Syntax of an `allowed_purposes` entry (a purpose or a `prefix.*` wildcard). */ export declare const PURPOSE_PATTERN_RE: RegExp; /** A manifest does not conform to manifest schema 0.6. The message names the offending path. */ export declare class ManifestValidationError extends Error { constructor(message: string); } /** Call caps as written in a manifest. */ export interface ManifestToolCaps { per_hour?: number; per_day?: number; per_case?: number; } /** The object form of a tool declaration, exactly as written in a manifest file. */ export interface ManifestToolObject { permission: Permission | `${Permission}`; allowed_purposes?: string[]; caps?: ManifestToolCaps; cost_units?: Record; requires_decision?: boolean; risk_tier?: RiskTier; four_eyes_on?: string[]; decision_fields?: string[]; } /** A tool value: a permission string or a manifest 0.6 object. */ export type ToolDeclaration = Permission | `${Permission}` | ManifestToolObject; /** Call caps declared for a tool. Absent means no cap of that kind; `0` disables the tool. */ export interface ToolCaps { /** Rolling one-hour window. */ perHour?: number; /** Rolling one-day window. */ perDay?: number; /** Calls within one case. */ perCase?: number; } /** A tool's full, validated declaration. */ export interface ToolSpec { permission: Permission; /** Purpose patterns; absent means no purpose restriction. */ allowedPurposes?: readonly string[]; caps?: ToolCaps; costUnits?: Readonly>; requiresDecision: boolean; /** Workload risk tier; `high` needs a decision grant on every call whether or not `requiresDecision` is set. */ riskTier?: RiskTier; fourEyesOn: readonly string[]; /** Call arguments, beyond the core semantic action, that a decision grant binds (e.g. `currency`). */ decisionFields?: readonly string[]; } /** Whether `value` is a syntactically valid `allowed_purposes` entry. */ export declare function isValidPurposePattern(value: unknown): value is string; /** * Validate one tool value (string or object form) and return its ToolSpec. * * @throws {ManifestValidationError} the value does not conform to manifest 0.6. */ export declare function parseToolDeclaration(tool: string, value: unknown): ToolSpec; /** * Parse manifest JSON text, rejecting a key repeated in any object. `JSON.parse` * alone keeps the last value, so a tool declared twice would load silently. */ export declare function parseManifestJson(text: string): unknown; /** Render a ToolSpec in manifest 0.6 object form (omitting unset fields). */ export declare function toolSpecToObject(spec: ToolSpec): ManifestToolObject; export interface ToolManifestOptions { /** Connector name (e.g., "acme_kyb"). */ connector: string; /** Tool name → permission string or manifest 0.6 tool object. */ tools: Record; /** Manifest version (default "1.0.0"). */ version?: string; /** Human-readable description. */ description?: string; } /** * Declares the required permission level for each tool on a connector. * * Load manifests via `grantex.loadManifest()` and they will be used * automatically by `grantex.enforce()`. * * `tools` maps each tool to its permission (as before 0.6); `getToolSpec()` * returns the full declaration including constraints. */ export declare class ToolManifest { #private; readonly connector: string; readonly tools: Record; readonly version: string; readonly description: string; constructor(options: ToolManifestOptions); /** Get the declared permission for a tool. Returns undefined if not found. */ getPermission(toolName: string): Permission | undefined; /** * Get a tool's full declaration. Returns undefined if the tool is not declared. * * The permission always reflects `tools`; constraints declared for the tool * are kept even if `tools` was edited directly. * * @throws {ManifestValidationError} `tools` was edited into a combination the * schema forbids (for example `read` on a decision tool). */ getToolSpec(toolName: string): ToolSpec | undefined; /** * Add or update a tool. `permission` is a permission string or a manifest * 0.6 tool object; replacing a tool replaces its whole declaration. */ addTool(toolName: string, permission: ToolDeclaration): void; /** Number of tools in this manifest. */ get toolCount(): number; /** Render this manifest as a manifest 0.6 document. */ toJSON(): { connector: string; version: string; description?: string; tools: Record; }; /** * Load a ToolManifest from a JSON or YAML file. * YAML requires the `yaml` package to be installed. */ static fromFile(filePath: string): Promise; /** * Create a ToolManifest from a JSON object (e.g., loaded from file). * * A manifest that declares `$schema` or uses the object form for any tool * is validated against manifest schema 0.6, and an unknown key anywhere is * rejected. A manifest made only of permission strings keeps its pre-0.6 * behaviour: unknown top-level keys are ignored with a deprecation warning * (a future minor release will reject them). */ static fromJSON(data: Record): ToolManifest; } /** Result of a `grantex.enforce()` call. */ export interface EnforceResult { /** Whether the tool call is permitted. */ allowed: boolean; /** Human-readable reason if denied. */ reason: string; /** Grant ID from the JWT (empty if token invalid). */ grantId: string; /** Agent DID from the JWT (empty if token invalid). */ agentDid: string; /** All scopes from the grant token. */ scopes: string[]; /** Resolved permission for the requested tool. */ permission: string; /** Connector name. */ connector: string; /** Tool name. */ tool: string; /** Denial code from `DenialReason`; absent when allowed. */ reasonCode?: DenialReason; /** Finer-grained denial code, where one applies. */ subReason?: string; /** Structured denial context. Keys are snake_case (`allowed_purposes`, `limit`, `window`), identical to the Python SDK. */ details?: Record; /** The grant's purpose for this connector, when it carries one. */ purpose?: string; /** Caps reserved for this call, when the tool or grant declares caps. */ reservation?: Reservation; /** Counters this call is metered against (also set when `reserve: false`). */ capLimits?: readonly CapLimit[]; /** Tenant of `capLimits`; pass both to `CapsMeter.reserve`. */ capsTenantId?: string; /** * In caps or decisions warn mode, the first denial that was not applied. The * same as `wouldDenyAll[0]`; read `wouldDenyAll` to see every one. */ wouldDeny?: WouldDeny; /** * In caps or decisions warn mode, every denial that was not applied, in the * order the steps run (decision, amount cap, call caps, decision consumption). * Absent when there is none. */ wouldDenyAll?: readonly WouldDeny[]; /** For a tool that requires a decision: the decision grants consumed for this call. */ decision?: ConsumedDecision; } /** A denial reported, not applied, in caps or decisions warn mode. Keys match the Python SDK. */ export interface WouldDeny { reason_code: string; sub_reason: string; reason: string; details: Record; } /** Options for `grantex.enforce()`. */ export interface EnforceOptions { /** The Grantex grant token (JWT). */ grantToken: string; /** Connector name (e.g., "salesforce"). */ connector: string; /** Tool name (e.g., "delete_contact"). */ tool: string; /** * The call's amount, for a `capped:N` scope. When such a scope covers the * connector (on any permission: the cap applies to every tool of the * connector, read tools included), a call without an amount is denied with * `amount_missing`, or `malformed_cap` when the cap cannot be read (in caps * mode `warn` it is allowed and reported in `wouldDeny`; `off` skips it), and * an amount above the cap with `amount_cap` in every mode. */ amount?: number; /** Case the call belongs to; required when a per-case cap applies. Set by the gateway, never the agent. */ caseId?: string; /** Manifest cost units the call incurs (default: all the tool declares). Set by the gateway, never the agent. */ costComponents?: readonly string[]; /** * `false` checks caps against current usage without consuming anything; reserve * later with `CapsMeter.reserve(result.capsTenantId, result.capLimits)` or call * `enforce()` again at the call that incurs cost. Default `true`. */ reserve?: boolean; /** Overrides the client's caps mode for this call. */ capsMode?: CapsMode; /** Tenant of every counter of this call instead of the grant's developer. */ capsTenantId?: string; /** * Overrides the client's revocation check for this call, but only to * tighten it (`offline` < `feed` < `online`); a weaker value makes * `enforce()` reject before anything is checked. */ revocationCheck?: 'offline' | 'online' | 'feed'; /** Overrides the client's expected grant token audience for this call. */ audience?: string; /** Overrides the client's data region for this call (needs `dataRegionCheck: 'on'`). */ dataRegion?: string; /** * Decision grant tokens for a tool with `requires_decision` (one, or two for a decision in * `four_eyes_on`). Without them the call is denied with `decision_required`. */ decisionGrants?: readonly string[]; /** The action the grants must approve. Defaults to the action derived from `arguments`. */ decisionAction?: DecisionAction; /** The call's arguments: `case_id`, `decision`, `subject` and `amount` are read from them. */ arguments?: Record; /** The case's current version, from the application's own case state. */ caseVersion?: string; /** Overrides the client's decisions mode for this call. */ decisionsMode?: 'enforce' | 'warn'; } /** Options for `grantex.wrapTool()`. */ export interface WrapToolOptions { /** Connector name. */ connector: string; /** Tool name. */ tool: string; /** Grant token — static string or getter function for dynamic tokens. */ grantToken: string | (() => string); /** Case for per-case caps, or a getter evaluated per call. Never taken from the tool's (model-supplied) input. */ caseId?: string | (() => string | undefined); /** For a tool that requires a decision: the decision grants, or a getter evaluated per call. The action is derived from the tool's input. */ decisionGrants?: readonly string[] | (() => readonly string[] | undefined); /** The case's current version, or a getter, from the application's case state. */ caseVersion?: string | (() => string | undefined); /** Cost units the call incurs, or a getter evaluated per call. Never taken from the tool's input. */ costComponents?: readonly string[] | (() => readonly string[] | undefined); /** * For a grant with a `capped:N` scope: the call's amount, from the tool's input * (plain or async). Without it, or when it returns `undefined` or `null`, a * capped scope denies the call with `amount_missing`. If it throws the call is * refused; a value that is not a finite number is denied with `invalid_amount`. */ extractAmount?: (input: unknown) => number | undefined | null | Promise; } /** Options for `grantex.enforceMiddleware()`. */ export interface EnforceMiddlewareOptions { /** Extract the grant token from the request (e.g., from Authorization header). */ extractToken: (req: Record) => string | undefined; /** Extract the connector name from the request. */ extractConnector: (req: Record) => string; /** Extract the tool name from the request. */ extractTool: (req: Record) => string; /** Case for per-case caps, from trusted request context (not the agent's payload). */ extractCaseId?: (req: Record) => string | undefined; /** Cost units the call incurs, from trusted request context (not the agent's payload). */ extractCostComponents?: (req: Record) => readonly string[] | undefined; /** Decision grants presented with the request (for example from a header). */ extractDecisionGrants?: (req: Record) => readonly string[] | undefined; /** The tool call's arguments, from which the decision action is derived. */ extractArguments?: (req: Record) => Record | undefined; /** The case's current version, from trusted server-side case state. */ extractCaseVersion?: (req: Record) => string | undefined; /** * For a grant with a `capped:N` scope: the call's amount (plain or async). * Without it, or when it returns `undefined` or `null`, a capped scope denies * the request with `amount_missing`. If it throws, or returns something that is * not a finite number, the request is refused with 403 `invalid_amount`. */ extractAmount?: (req: Record) => number | undefined | null | Promise; } //# sourceMappingURL=manifest.d.ts.map