import { C as ConnectorAdapter } from './types-eAvAgnKr.js';

/**
 * @stable Tangle Identity — `id.tangle.tools` connector + verifier.
 *
 * This is the *identity* substrate every Tangle product (legal, tax, gtm,
 * creative, agent-builder, sandbox, evals, …) sits on. The shape mirrors
 * what `tcloud` and the sandbox `PlatformClient` already implement against
 * the platform repo at `agent-dev-container-collab-m1/products/platform`,
 * so consumers can switch from a hand-rolled fetch loop to this adapter
 * without changing the wire protocol.
 *
 * What it covers, end-to-end:
 *
 *   verify_token({ token })
 *     → { kind: 'api_key' | 'session', valid, userId?, workspaceId?, scopes, expiresAt? }
 *     Verifies a single credential. Two token shapes are recognized:
 *       - `sk-tan-*` API keys — POST /v1/keys/verify with the service token.
 *         Returns `userId`, `keyId`, `product`, granted scopes (`allowedModels`
 *         + product flag), and budget metadata.
 *       - Better Auth session cookies / Bearer session tokens — GET
 *         /api/auth/get-session with the credential forwarded as-is.
 *         Returns the user row.
 *     Wrong-issuer / tampered / expired all surface as `{ valid: false }`
 *     with a stable `reason`. Never throws on bad-token; only throws when
 *     id.tangle.tools itself is unreachable or returns a 5xx (lets callers
 *     fail closed without confusing token failures with platform failures).
 *
 *   get_user({ userId })
 *     → { id, email, name?, image? }
 *     Read-only profile lookup. Service-token authenticated. Used by
 *     `requireTangleAuth` middleware to hydrate the request context when
 *     a downstream wants the user's email without re-verifying.
 *
 *   list_workspaces({ userId })
 *     → { workspaces: [{ id, name, role, isPersonal }] }
 *     A workspace = a Tangle team. Personal workspace is rendered with
 *     `isPersonal: true` (own id === userId on the platform schema).
 *     Mirrors `GET /v1/teams` on the platform side.
 *
 *   switch_workspace({ workspaceId })
 *     → { ok: true, workspaceId, scopes }
 *     Stateless on this adapter — the caller persists the workspaceId in
 *     its own session. The connector returns the workspace's effective
 *     scope set so the caller can immediately filter capability discovery
 *     against the new workspace's grant matrix.
 *
 *   revoke_session({ token })
 *     → { ok: true }
 *     For session tokens: POST /api/auth/sign-out. For API keys: DELETE
 *     /v1/keys/{id}. The adapter detects the kind from the prefix.
 *
 * Auth:
 *   - **Service token** (`Bearer svc_*`) is required for `verify_token` of
 *     `sk-tan-*` keys, `get_user`, `list_workspaces`, and `revoke_session`
 *     of API keys.
 *   - **Session cookie / Bearer session** is forwarded as-is for session
 *     verification and session revocation.
 *
 * The adapter is stateless. Caller resolves `serviceToken` + `baseUrl` from
 * env (`TANGLE_PLATFORM_URL`, `TANGLE_SERVICE_TOKEN`) and passes them at
 * construction. The adapter never reads from `process.env` itself — this
 * keeps it CF Worker compatible (no Node-only env semantics) and lets
 * tests inject a fake fetch + service token in one place.
 */

/** Default platform URL (matches `DEFAULT_PLATFORM_URL` in tcloud). */
declare const DEFAULT_TANGLE_PLATFORM_URL = "https://id.tangle.tools";
/** API-key prefix the platform issues. Used to disambiguate token kind
 *  without a round-trip. */
declare const TANGLE_API_KEY_PREFIX = "sk-tan-";
/** Service-token prefix. Mirrored from the platform's middleware so we
 *  can refuse to forward service tokens through the user-session path. */
declare const TANGLE_SERVICE_TOKEN_PREFIX = "svc_";
interface TangleIdentityOptions {
    /** Base URL of the id.tangle.tools deployment (no trailing slash). */
    baseUrl?: string;
    /**
     * Service token (`svc_*`) used for S2S calls (verify, provision, etc.).
     * Required for API-key verification and the user/workspace read paths.
     * Omit only for session-only flows on a deployment that exposes those
     * routes unauthenticated (rare; never in production).
     */
    serviceToken?: string;
    /** Service identity claimed in the `X-Service-Name` header. */
    serviceName?: string;
    /** Injected fetch — defaults to global. Tests pass a vi mock. */
    fetchImpl?: typeof fetch;
    /** Per-call timeout override (default {@link PLATFORM_FETCH_TIMEOUT_MS}). */
    timeoutMs?: number;
}
/** Stable result of a token verification. `valid: false` is returned for
 *  every recognizable bad-token shape (expired, tampered, wrong issuer,
 *  unknown kind); only true platform unreachability throws. */
type TangleTokenVerifyResult = {
    valid: true;
    kind: 'api_key' | 'session';
    userId: string;
    /** Active workspace at the moment of issue, if the credential is
     *  workspace-scoped (team-owned API key). Personal credentials
     *  return the user's personal workspace (== `userId`). */
    workspaceId: string;
    scopes: string[];
    /** Wall-clock ms epoch when the credential expires. Undefined for
     *  non-expiring credentials (most session cookies are sliding). */
    expiresAt?: number;
    /** Stable id of the credential row, when known (key.id for API
     *  keys, session.id for sessions). Useful for revoke + audit. */
    credentialId?: string;
    /** Product the credential is scoped to, when known. */
    product?: string;
    /** Owner shape — `user` for personal credentials, `team` for
     *  team-owned API keys. Always matches the workspace's owner type. */
    ownerType: 'user' | 'team';
} | {
    valid: false;
    /** Stable reason code: `tampered`, `expired`, `revoked`,
     *  `wrong_issuer`, `unknown_kind`, `service_token_refused`. */
    reason: TangleTokenVerifyFailure;
};
type TangleTokenVerifyFailure = 'tampered' | 'expired' | 'revoked' | 'wrong_issuer' | 'unknown_kind' | 'service_token_refused' | 'malformed';
interface TangleUserSummary {
    id: string;
    email?: string;
    name?: string | null;
    image?: string | null;
}
interface TangleWorkspaceSummary {
    id: string;
    name: string;
    role: 'owner' | 'admin' | 'member';
    isPersonal: boolean;
    /** Effective scope set for the calling user inside this workspace.
     *  Sourced from the team's plan + per-product policy on the platform. */
    scopes: string[];
}
/** Thrown when id.tangle.tools is unreachable or returns 5xx. NOT thrown
 *  for bad-token responses — those round-trip as `{ valid: false }`. */
declare class TangleIdentityUnreachableError extends Error {
    readonly name = "TangleIdentityUnreachableError";
    readonly status?: number;
    constructor(message: string, opts?: {
        status?: number;
        cause?: unknown;
    });
}
/** Build a `ConnectorAdapter` exposing id.tangle.tools as a first-party
 *  integration. The adapter participates in the standard discovery /
 *  capability gating loop, so a product can list identity ops alongside
 *  Gmail / Stripe / etc. in the same tool registry. */
declare function tangleIdentity(opts?: TangleIdentityOptions): ConnectorAdapter;
/** Low-level HTTP client used by the adapter. Exported so consumers
 *  (middleware, connect routes, custom apps) can hit id.tangle.tools
 *  without going through the connector pipeline. */
interface TangleIdentityClient {
    verifyToken(token: string): Promise<TangleTokenVerifyResult>;
    getUser(userId: string): Promise<TangleUserSummary>;
    listWorkspaces(userId: string): Promise<TangleWorkspaceSummary[]>;
    switchWorkspace(userId: string, workspaceId: string): Promise<{
        ok: true;
        workspaceId: string;
        scopes: string[];
    }>;
    revokeSession(token: string): Promise<void>;
    /** Create a new workspace owned by `userId`. The platform's
     *  `POST /v1/teams` returns the persisted row. Idempotent on
     *  `(ownerId, name)` upstream; conflicts are unwrapped to the
     *  existing row, not surfaced as errors. */
    createWorkspace(userId: string, spec: {
        name: string;
        slug?: string;
    }): Promise<TangleWorkspaceSummary>;
    /** Delete a workspace. Refuses to delete the user's personal
     *  workspace (the platform-side `/v1/teams/{id}` returns 409). */
    deleteWorkspace(workspaceId: string): Promise<void>;
    /** Invite a member to a workspace by email. Idempotent: re-issuing
     *  the same invite returns the existing pending invitation row. */
    inviteMember(workspaceId: string, email: string, role?: TangleWorkspaceSummary['role']): Promise<TangleInvitationSummary>;
    /** Remove a member from a workspace by `userId`. 404 is a no-op. */
    removeMember(workspaceId: string, userId: string): Promise<void>;
    ping(): Promise<boolean>;
}
interface TangleInvitationSummary {
    id: string;
    workspaceId: string;
    email: string;
    role: TangleWorkspaceSummary['role'];
    status: 'pending' | 'accepted' | 'revoked';
}
declare function createTangleIdentityClient(opts?: TangleIdentityOptions): TangleIdentityClient;

export { DEFAULT_TANGLE_PLATFORM_URL as D, type TangleIdentityOptions as T, type TangleUserSummary as a, type TangleIdentityClient as b, type TangleTokenVerifyFailure as c, TANGLE_API_KEY_PREFIX as d, TANGLE_SERVICE_TOKEN_PREFIX as e, TangleIdentityUnreachableError as f, type TangleTokenVerifyResult as g, type TangleWorkspaceSummary as h, createTangleIdentityClient as i, tangleIdentity as t };
