/**
 * Short-lived, workspace-scoped bearer for the delegated-tool bridge.
 *
 * An external stateful agent — a voice caller, a long-running autonomous worker
 * — is handed one of these tokens and calls BACK into the product's tools
 * mid-session. The token names exactly which workspace and which tool names the
 * external agent may reach, and it EXPIRES, so a leaked lease stops working once
 * the session window closes. The product's connector credentials never leave the
 * product; the external agent only ever holds this opaque token and reaches the
 * product's callback endpoint (see {@link handleDelegatedToolCall}).
 *
 * This is a SIGNED-CLAIMS envelope, distinct from an identity capability token
 * (`HMAC(secret, "user:<id>")`, verified against a known id). Here the verifier
 * RECOVERS the claims (workspaceId, allowedTools, expiresAt) from the token
 * itself, so the bridge endpoint needs no prior knowledge of the lease.
 *
 * Crypto: WebCrypto HMAC-SHA256, base64url, constant-time compare. Runs on
 * Cloudflare Workers, Node, and the browser with no Node `crypto` dependency —
 * matching the sibling capability-token primitive. Fail-closed: with no secret,
 * mint returns `undefined` and verify returns `null`, so the bridge is simply
 * absent rather than silently unauthenticated.
 */
interface DelegatedToolClaims {
    workspaceId: string;
    allowedTools: string[];
    /** Epoch milliseconds at which the token stops verifying. */
    expiresAt: number;
}
interface MintDelegatedToolTokenInput {
    workspaceId: string;
    allowedTools: string[];
    ttlSeconds: number;
    /** Shared HMAC secret. When absent, mint returns `undefined` (fail-closed). */
    secret?: string;
    /** Token prefix (namespaces the credential; lets verify reject foreign tokens
     *  cheaply). Default `dtt_`. */
    prefix?: string;
    /** Override the clock (epoch ms) — for tests. Defaults to `Date.now()`. */
    now?: number;
}
interface VerifyDelegatedToolTokenOptions {
    secret?: string;
    prefix?: string;
    now?: number;
}
/**
 * Mint a delegated-tool token carrying signed claims, or `undefined` when no
 * secret is configured (fail-closed — the caller refuses to issue a lease rather
 * than hand out an unauthenticated one).
 */
declare function mintDelegatedToolToken(input: MintDelegatedToolTokenInput): Promise<string | undefined>;
/**
 * Verify a delegated-tool token and recover its claims. Returns `null` (never
 * throws) for an unconfigured secret, a wrong prefix, a malformed or forged
 * token, or an expired one.
 */
declare function verifyDelegatedToolToken(token: string, opts: VerifyDelegatedToolTokenOptions): Promise<DelegatedToolClaims | null>;

/**
 * Transport-agnostic JSON-RPC 2.0 callback handler for the delegated-tool
 * bridge — the endpoint an EXTERNAL stateful agent calls back into mid-session,
 * authorized by the bearer minted via {@link mintDelegatedToolToken}.
 *
 * The product supplies three seams; the handler bakes in no domain assumptions
 * (no voice/phony/calendar specifics):
 *
 *   - `verifyToken(bearer)` → claims | null — recover & validate the lease
 *     (fresh, signed). Usually {@link verifyDelegatedToolToken} bound to a secret.
 *   - `resolveTool(workspaceId, name)` → invocable | null — the product's tool
 *     registry. `null` means "this workspace cannot reach that tool right now".
 *   - `isIntegrationConnected(workspaceId, tool)` → boolean — the live
 *     connectivity gate; a stale token naming a since-disconnected integration
 *     resolves but fails this check.
 *
 * FAIL-CLOSED, in order, for `tools/call`: (1) bearer verifies, (2) tool is in
 * the lease allow-list, (3) tool resolves for the workspace, (4) the backing
 * integration is connected. Any miss returns a JSON-RPC error and the invocable
 * is never touched.
 *
 * `tools/list` is advisory: it returns the intersection of the allow-list with
 * what currently resolves + is connected, omitting (never erroring) the rest.
 */

interface DelegatedToolDescriptor {
    /** Wire name the external agent calls by. */
    name: string;
    description?: string;
    /** JSON Schema for the tool arguments. Defaults to `{ type: 'object' }`. */
    inputSchema?: unknown;
}
interface ResolvedDelegatedTool extends DelegatedToolDescriptor {
    /**
     * Invoke the tool with the JSON-RPC `arguments`. Returns the JSON-RPC `result`
     * payload on success. Throw {@link DelegatedToolInvocationError} to surface a
     * structured JSON-RPC error (code + data); any other throw becomes -32000.
     */
    invoke(args: Record<string, unknown>): Promise<unknown>;
}
/** Throw from `resolveTool().invoke` to control the JSON-RPC error envelope. */
declare class DelegatedToolInvocationError extends Error {
    readonly code: number;
    readonly data?: unknown;
    constructor(message: string, options?: {
        code?: number;
        data?: unknown;
    });
}
interface DelegatedToolCallSeams {
    /** Recover lease claims from a raw bearer string, or `null` to reject. */
    verifyToken(bearer: string): Promise<DelegatedToolClaims | null> | DelegatedToolClaims | null;
    /** The product's tool registry. `null` ⇒ not reachable for this workspace. */
    resolveTool(workspaceId: string, name: string): Promise<ResolvedDelegatedTool | null> | ResolvedDelegatedTool | null;
    /** Live connectivity gate for the integration backing `tool`. */
    isIntegrationConnected(workspaceId: string, tool: ResolvedDelegatedTool): Promise<boolean> | boolean;
    /**
     * Optional advertised name/version for the JSON-RPC `initialize` handshake.
     * Defaults to `{ name: 'delegated-tools', version: '1' }`.
     */
    serverInfo?: {
        name: string;
        version: string;
    };
}
interface JsonRpcRequest {
    jsonrpc?: unknown;
    id?: unknown;
    method?: unknown;
    params?: unknown;
}
interface JsonRpcResponse {
    jsonrpc: '2.0';
    id: string | number | null;
    result?: unknown;
    error?: {
        code: number;
        message: string;
        data?: unknown;
    };
}
/**
 * Handle one JSON-RPC call. Accepts a parsed body + the raw `authorization`
 * header value. Returns the JSON-RPC response object (the transport wrapper —
 * {@link handleDelegatedToolRequest} — turns it into an HTTP `Response`).
 */
declare function handleDelegatedToolCall(body: JsonRpcRequest, authorization: string | null | undefined, seams: DelegatedToolCallSeams): Promise<JsonRpcResponse>;
/**
 * HTTP transport wrapper around {@link handleDelegatedToolCall}: parses the
 * request, enforces POST, maps the JSON-RPC response to a `Response`. Unauthorized
 * is the only non-200 status (401) so an unauthenticated probe can't distinguish
 * methods; every authenticated JSON-RPC error rides a 200 per the JSON-RPC contract.
 */
declare function handleDelegatedToolRequest(request: Request, seams: DelegatedToolCallSeams): Promise<Response>;

/**
 * Standardized lease payload the product hands to its external agent.
 *
 * The product resolves which tools a workspace may delegate right now, mints a
 * scoped token over exactly those names ({@link mintDelegatedToolToken}), and
 * packages the result as a lease. The external agent (or the broker that builds
 * its session) reads `callbackUrl` + `token` to reach the product's
 * {@link handleDelegatedToolRequest} endpoint mid-session.
 *
 * Standardizing the shape here means every caller's lease looks the same on the
 * wire regardless of the external runtime (voice broker, autonomous worker).
 */
interface IssueDelegatedToolLeaseInput {
    workspaceId: string;
    allowedTools: string[];
    ttlSeconds: number;
    /** Shared HMAC secret for the token. Absent ⇒ lease cannot be issued. */
    secret?: string;
    /** Token prefix; forwarded to {@link mintDelegatedToolToken}. */
    prefix?: string;
    /** Endpoint the external agent calls back into. Echoed onto the lease. */
    callbackUrl?: string;
    /** Override the clock (epoch ms) — for tests. */
    now?: number;
}
interface DelegatedToolLease {
    token: string;
    allowedTools: string[];
    /** Epoch milliseconds at which the lease (and its token) expires. */
    expiresAt: number;
    callbackUrl?: string;
}
/**
 * Issue a delegated-tool lease, or `null` when no secret is configured
 * (fail-closed — the product refuses to hand out an unauthenticated lease).
 * Pass an already-filtered `allowedTools`: this helper signs whatever it is
 * given, so the product MUST intersect against what the workspace can delegate
 * before calling.
 */
declare function issueDelegatedToolLease(input: IssueDelegatedToolLeaseInput): Promise<DelegatedToolLease | null>;

export { type DelegatedToolCallSeams, type DelegatedToolClaims, type DelegatedToolDescriptor, DelegatedToolInvocationError, type DelegatedToolLease, type IssueDelegatedToolLeaseInput, type JsonRpcRequest, type JsonRpcResponse, type MintDelegatedToolTokenInput, type ResolvedDelegatedTool, type VerifyDelegatedToolTokenOptions, handleDelegatedToolCall, handleDelegatedToolRequest, issueDelegatedToolLease, mintDelegatedToolToken, verifyDelegatedToolToken };
