import * as Automerge from '@automerge/automerge';
import { Doc } from '@automerge/automerge/slim';

/**
 * @module @granular-software/sdk/types
 * Type definitions for the Granular SDK
 */
/**
 * Configuration for the Granular client
 */
type AccessTokenProvider = () => Promise<string | null | undefined> | string | null | undefined;
type EndpointMode = "auto" | "local" | "production";
interface GranularOptions {
    /** Your Granular API key (for service/CLI auth; use with GRANULAR_API_KEY) */
    apiKey?: string;
    /** Application/session JWT (for user-context auth; use from simulator or getAccessToken) */
    token?: string;
    /** Optional provider used to refresh JWT before WebSocket (re)connect attempts */
    tokenProvider?: AccessTokenProvider;
    /** Optional API URL (for on-prem or testing) */
    apiUrl?: string;
    /** Optional endpoint mode when apiUrl is not explicitly provided */
    endpointMode?: EndpointMode;
    /** Optional WebSocket constructor (for Node.js environments) */
    WebSocketCtor?: any;
    /**
     * Optional callback invoked when a connected WebSocket closes unexpectedly.
     * Useful for forwarding close diagnostics to monitoring (e.g., Sentry).
     */
    onUnexpectedClose?: (info: WSDisconnectInfo) => void;
    /**
     * Optional callback invoked when automatic reconnect fails.
     * Useful to capture auth or gateway rejection causes.
     */
    onReconnectError?: (info: WSReconnectErrorInfo) => void;
}
/** Resolved auth credential: either apiKey or token must be provided */
type GranularAuth = string;
/**
 * A user/subject object returned from recordUser()
 */
interface User {
    /** Internal Granular user identifier */
    granularId: string;
    /** External user identifier from your app */
    userId: string;
    /** @deprecated Use `granularId` instead */
    subjectId: string;
    /** @deprecated Use `userId` instead */
    identityId: string;
    /** User's display name */
    name?: string;
    /** User's email */
    email?: string;
    /** Permission profile IDs to be assigned when connecting */
    permissions: string[];
}
/**
 * Options for recording a user
 */
interface RecordUserOptions {
    /** External user/identity ID (e.g. your Auth0 or database user ID) */
    userId: string;
    /** User's display name */
    name?: string;
    /** User's email */
    email?: string;
    /** Permission profile IDs to assign when connecting to sandboxes */
    permissions?: string[];
}
/**
 * Subject as returned from the API
 */
interface Subject {
    /** Internal Granular user identifier */
    granularId: string;
    /** External user identifier from your app */
    userId: string;
    subjectId: string;
    tenantId: string;
    identityId: string;
    email?: string | null;
    name?: string | null;
    metadata?: Record<string, unknown>;
    createdAt: number;
    updatedAt: number;
}
/**
 * Options for opening an ontology environment for one delegated subject.
 *
 * This does not open a live runtime session. Use
 * `environment.sessions.create()` or `granular.createSession({ environmentId })`
 * when you need a conversation/session with jobs, prompts, heap, and effects.
 */
interface OpenEnvironmentOptions {
    /** The ontology name or ID to open. */
    ontology: string;
    /** Version channel to follow, typically `dev` or `prod`. */
    tag?: string;
    /**
     * External user identifier from your app.
     *
     * Exactly one of `userId`, `granularId`, or `user` should be provided.
     */
    userId?: string;
    /**
     * Internal Granular user identifier.
     *
     * Exactly one of `userId`, `granularId`, or `user` should be provided.
     */
    granularId?: string;
    /** Optional display name used when upserting the user. */
    name?: string;
    /** Optional email used when upserting the user. */
    email?: string;
    /**
     * Permission profile names or IDs to ensure before opening the environment.
     * This should be provided even for existing users so the SDK can guarantee
     * assignments for first-time environment creation.
     */
    permissions: string[];
    /**
     * When true, if the latest environment for this ontology/user/tag is marked
     * outdated relative to the current tag target, create a fresh environment on
     * the newest tag target instead of reusing the outdated one.
     */
    createFreshIfOutdated?: boolean;
    /** Backwards-compatible user object returned from `recordUser()`. */
    user?: User;
}
/**
 * Deprecated compatibility alias for the legacy `connect()` entry point.
 *
 * `connect()` now resolves an environment handle and no longer opens a runtime
 * session automatically. Prefer `openEnvironment()` for new code.
 */
interface ConnectOptions extends OpenEnvironmentOptions {
    /** @deprecated Legacy explicit environment slot name. Prefer `tag`. */
    environment?: string;
    /** @deprecated Legacy tag field. Prefer `tag`. */
    tagName?: string;
    /** @deprecated Ignored by `connect()` now that it no longer opens sessions. */
    clientId?: string;
    /** @deprecated Ignored by `connect()` now that it no longer opens sessions. */
    initialHeap?: Array<{
        className: string;
        id: string;
    }>;
}
/**
 * Options for creating a live runtime session from an opened environment.
 */
interface CreateSessionOptions {
    /** Optional stable client ID. Defaults to `client_${Date.now()}`. */
    clientId?: string;
    /** Optional session heap seed. Each item is eagerly hydrated into the session heap on connect. */
    initialHeap?: Array<{
        className: string;
        id: string;
    }>;
}
/**
 * Control-plane session row: one real-time conversation thread with the agent for an environment.
 */
interface ConversationSessionInfo {
    sessionId: string;
    tenantId?: string;
    environmentId: string;
    versionId?: string | null;
    docId: string;
    status: "active" | "closed" | "expired";
    createdAt: string;
    lastSeenAt: string;
    summary?: string | null;
    summaryUpdatedAt?: string | null;
    subjectId?: string | null;
    jobCount?: number;
    toolCallCount?: number;
}
/**
 * A sandbox container
 */
interface Sandbox {
    sandboxId: string;
    tenantId: string;
    name: string;
    description?: string | null;
    createdAt: number;
    updatedAt: number;
}
/**
 * Data for creating a new sandbox
 */
interface CreateSandboxData {
    name: string;
    description?: string;
}
/**
 * List response for sandboxes
 */
interface SandboxListResponse {
    items: Sandbox[];
}
/**
 * Rules defining what effects and resources are allowed or denied.
 */
interface PermissionRules {
    /** Effect access rules */
    effects?: {
        /** Patterns for allowed effects (e.g. ["*"] for all, ["read_*"] for prefix match) */
        allow?: string[];
        /** Patterns for denied effects */
        deny?: string[];
    };
    /** Legacy alias accepted by the backend while migrating to `effects`. */
    tools?: {
        /** Patterns for allowed effects (e.g. ["*"] for all, ["read_*"] for prefix match) */
        allow?: string[];
        /** Patterns for denied effects */
        deny?: string[];
    };
    /** Resource access rules */
    resources?: {
        /** Patterns for allowed resources */
        allow?: string[];
        /** Patterns for denied resources */
        deny?: string[];
    };
}
/**
 * A permission profile defines access controls for an environment
 */
interface PermissionProfile {
    permissionProfileId: string;
    sandboxId: string;
    name: string;
    rules: PermissionRules;
    createdAt: number;
    updatedAt: number;
}
/**
 * Data for creating a new permission profile
 */
interface CreatePermissionProfileData {
    name: string;
    rules: PermissionRules;
}
/**
 * List response for permission profiles
 */
interface PermissionProfileListResponse {
    items: PermissionProfile[];
}
/**
 * An assignment links a subject to a sandbox with a permission profile
 */
interface Assignment {
    assignmentId: string;
    tenantId: string;
    subjectId: string;
    sandboxId: string;
    permissionProfileId: string;
    createdAt: number;
    createdBy?: string | null;
}
/**
 * List response for assignments
 */
interface AssignmentListResponse {
    items: Assignment[];
}
/**
 * Version tracking policy for environments.
 *
 * Environments either follow a version tag such as `dev` or `prod`, or they
 * pin themselves to one immutable ontology version.
 */
interface BuildPolicy {
    mode: "tag" | "current" | "pinned";
    buildId?: string;
    versionId?: string;
    tagId?: string;
    tagName?: string;
}
type VersionTracking = BuildPolicy;
interface VersionTag {
    tagId: string;
    sandboxId: string;
    name: string;
    kind: "channel" | "release" | "system";
    targetBuildId?: string | null;
    targetVersionId?: string | null;
    description?: string | null;
    protected?: boolean;
    createdAt: number;
    updatedAt: number;
}
/**
 * An environment links a user (subject) to a sandbox with specific permissions
 */
interface EnvironmentData {
    environmentId: string;
    sandboxId: string;
    ontologyId?: string;
    buildId: string;
    versionNumber?: number | null;
    versionId: string;
    subjectId: string;
    envName: string;
    environment?: string;
    permissionProfileId: string;
    tagId?: string | null;
    tag?: VersionTag | null;
    tracking?: BuildPolicy;
    buildPolicy: BuildPolicy;
    setup?: EnvironmentSetupSummary | null;
    updateState?: "up_to_date" | "update_available" | "upgrading" | "failed";
    createdAt: number;
    updatedAt: number;
}
/**
 * Data for creating a new environment
 */
interface CreateEnvironmentData {
    /** The user/subject ID to create the environment for */
    subjectId: string;
    /** Named environment slot such as dev or prod */
    environment?: string;
    /** @deprecated Use `environment` instead. */
    envName?: string;
    /** The permission profile to apply (optional - uses assignment if not specified) */
    permissionProfileId?: string | null;
    /** Follow a tag directly */
    tagId?: string;
    /** Follow a tag by name, typically dev or prod */
    tagName?: string;
    /** Pin the environment to a specific version */
    versionId?: string;
    /** Legacy/compat environment tracking input */
    buildPolicy?: BuildPolicy;
}
/**
 * List response for environments
 */
interface EnvironmentListResponse {
    items: EnvironmentData[];
}
/**
 * A manifest describes the structure and behavior of a sandbox
 */
interface Manifest {
    manifestId: string;
    sandboxId: string;
    version: string;
    digest: string;
    content?: Record<string, unknown>;
    createdAt: number;
    locked?: boolean;
}
/**
 * List response for manifests
 */
interface ManifestListResponse {
    items: Manifest[];
}
type BuildStatus = "queued" | "building" | "completed" | "failed" | "canceled";
/**
 * An immutable ontology version derived from a specific manifest revision.
 *
 * The same version may have multiple build runs over time when the manifest
 * content is unchanged but the compilation process is re-executed.
 */
interface Build {
    buildId: string;
    sandboxId: string;
    manifestId: string;
    manifestDigest?: string;
    versionNumber?: number;
    status: BuildStatus;
    graphBinaryId?: string | null;
    logsUri?: string | null;
    latestBuildRunId?: string | null;
    buildRunId?: string;
    createdNewVersion?: boolean;
    environmentCount?: number;
    laggingEnvironmentCount?: number;
    sessionCount?: number;
    createdAt: number;
    updatedAt: number;
    isCurrent?: boolean;
}
type Version = Build;
/**
 * List response for versions
 */
interface BuildListResponse {
    items: Build[];
}
interface SemanticVersionDiffEntry {
    operationId: string;
    kind: "create" | "update" | "relationship" | "effect" | "eventStream" | "unknown";
    changeType: "added" | "removed" | "changed";
    label: string;
    additive: boolean;
    breaking: boolean;
    before?: Record<string, unknown>;
    after?: Record<string, unknown>;
}
interface SemanticVersionDiff {
    summary: {
        added: number;
        removed: number;
        changed: number;
        additive: number;
        breaking: number;
        onlyAdditiveChanges: boolean;
    };
    entries: SemanticVersionDiffEntry[];
}
/**
 * Effect handler for static/global effects: receives (input, context)
 */
interface EffectHandlerContext {
    effectClientId: string;
    sandboxId: string;
    environmentId: string;
    buildId?: string;
    buildVersionNumber?: number;
    sessionId: string;
    tenantId?: string;
    principalId?: string;
    permissionProfileId?: string;
    user: {
        granularId?: string;
        userId?: string;
        subjectId: string;
        identityId?: string;
        principalId?: string;
    };
    behaviors?: ResolvedEffectBehaviors;
    invocation?: EffectInvocationMetadata;
}
interface ResolvedEffectPostCondition {
    condition: string;
    description?: string;
}
interface ResolvedEffectDryRun {
    enabled: boolean;
    description?: string;
}
interface ResolvedEffectReverse {
    handler?: string;
    description?: string;
}
interface ResolvedEffectApprovalRequired {
    required: boolean;
    reason?: string;
    mode?: string;
}
interface ResolvedEffectBehaviors {
    postCondition?: ResolvedEffectPostCondition;
    dryRun?: ResolvedEffectDryRun;
    reverse?: ResolvedEffectReverse;
    approvalRequired?: ResolvedEffectApprovalRequired;
}
type EffectInvocationMode = "execute" | "dryRun" | "reverse";
interface EffectInvocationMetadata {
    mode?: EffectInvocationMode;
    reverseHandler?: string;
    sourceEffectKey?: string;
    sourceEffectName?: string;
}
type ToolHandler = (input: any, context: EffectHandlerContext) => Promise<unknown>;
/**
 * Effect handler for instance methods: receives (objectId, input, context)
 */
type InstanceToolHandler = (id: string, input: any, context: EffectHandlerContext) => Promise<unknown>;
/**
 * Effect schema for declaring or registering an effect.
 *
 * Effects come in three flavours:
 *
 * 1. **Instance methods** — set `className`, omit `static`.
 *    In the sandbox: `tolkien.get_bio({ detailed: true })`
 *    Handler signature: `(objectId: string, params: any) => any`
 *
 * 2. **Static methods** — set `className` + `static: true`.
 *    In the sandbox: `Author.search({ query: 'tolkien' })`
 *    Handler signature: `(params: any) => any`
 *
 * 3. **Global effects** — omit `className`.
 *    In the sandbox: `global_search({ query: 'rings' })`
 *    Handler signature: `(params: any) => any`
 *
 * Both `inputSchema` and `outputSchema` accept JSON Schema objects.
 * The `outputSchema` drives the return type in the auto-generated
 * TypeScript declarations that sandbox code imports from `./sandbox-tools`.
 */
interface ToolSchema {
    effectKey?: string;
    name: string;
    description: string;
    /** JSON Schema for the effect input parameters */
    inputSchema: Record<string, unknown>;
    /**
     * JSON Schema for the tool's return value.
     * Used to generate typed return types in the sandbox TypeScript declarations.
     *
     * @example
     * ```typescript
     * outputSchema: {
     *   type: 'object',
     *   properties: {
     *     bio: { type: 'string', description: 'The biography text' },
     *     source: { type: 'string', description: 'Source of the bio' },
     *   },
     *   required: ['bio'],
     * }
     * // Generates: Promise<{ bio: string; source?: string }>
     * ```
     */
    outputSchema?: Record<string, unknown>;
    stability?: "stable" | "experimental" | "deprecated";
    provenance?: {
        source: "mcp" | "custom";
    };
    tags?: string[];
    /**
     * The class this effect belongs to (e.g., `'author'`, `'book'`).
     * When set, the effect becomes a method on the auto-generated class.
     * Omit for global effects (standalone exported functions).
     */
    className?: string;
    /**
     * If `true`, this is a static/class-level method (no object ID required).
     * If `false` or omitted and `className` is set, this is an instance method
     * that operates on a specific object (the object's real-world ID is
     * passed as the first argument to the handler).
     */
    static?: boolean;
    /**
     * Optional build-version selector for this live effect binding.
     *
     * When omitted, the binding applies to all build versions for the sandbox.
     */
    versionSelector?: EffectVersionSelector;
    /** Declarative runtime behaviors attached to the effect. */
    metamodels?: ManifestEffectMetamodelSpec;
}
type EffectSchema = ToolSchema;
/**
 * Effect with handler — what users provide to `registerEffect()`.
 *
 * - **Instance methods** (`className` set, `static` omitted):
 *   handler receives `(objectId: string, params: any)`
 * - **Static methods** (`className` set, `static: true`):
 *   handler receives `(params: any)`
 * - **Global tools** (no `className`):
 *   handler receives `(params: any)`
 */
interface ToolWithHandler extends ToolSchema {
    handler: ToolHandler | InstanceToolHandler;
    dryRunHandler?: ToolHandler | InstanceToolHandler;
    reverseHandler?: ToolHandler | InstanceToolHandler;
}
type EffectWithHandler = ToolWithHandler;
/**
 * Result from publishing or synchronizing effects
 */
interface PublishToolsResult {
    accepted: boolean;
    domainRevision: string;
    rejected?: Array<{
        name: string;
        reason: string;
    }>;
}
type PublishEffectsResult = PublishToolsResult;
type EffectVersionSelector = {
    mode: "all";
} | {
    mode: "exact";
    versionNumber: number;
} | {
    mode: "before";
    versionNumber: number;
} | {
    mode: "after";
    versionNumber: number;
};
/**
 * Domain state response
 */
interface DomainState {
    activeDomainRevision?: string;
    tools?: Array<{
        name: string;
        description?: string;
        inputSchema?: Record<string, unknown>;
        outputSchema?: Record<string, unknown>;
        metamodels?: ManifestEffectMetamodelSpec;
    }>;
    [key: string]: unknown;
}
/**
 * Information about a live or declared effect
 */
interface ToolInfo {
    effectKey?: string;
    /** Unique name of the effect */
    name: string;
    /** Description of what the effect does */
    description?: string;
    /** JSON Schema for effect input */
    inputSchema?: Record<string, unknown>;
    /** JSON Schema for effect output */
    outputSchema?: Record<string, unknown>;
    /** Client ID that published this effect (absent for domain-only entries) */
    clientId?: string;
    /** Whether the effect is ready for use (has a registered handler) */
    ready: boolean;
    /** Timestamp when the effect was published */
    publishedAt?: number;
    /** Class this effect belongs to (instance/static method) */
    className?: string;
    /** Whether this is a static method */
    static?: boolean;
    /** Optional build-version selector associated with the live binding. */
    versionSelector?: EffectVersionSelector;
    /** Declarative runtime behaviors attached to the effect. */
    metamodels?: ManifestEffectMetamodelSpec;
}
interface EffectInfo extends ToolInfo {
}
/**
 * Event data when the list of available effects changes
 */
interface ToolsChangedEvent {
    /** The current list of all available effects */
    tools: ToolInfo[];
    /** Names of effects that were added or updated */
    added: string[];
    /** Names of effects that were removed */
    removed: string[];
}
interface EffectsChangedEvent extends ToolsChangedEvent {
    /** The current list of all available effects */
    effects: EffectInfo[];
}
type EffectHandler = ToolHandler;
type InstanceEffectHandler = InstanceToolHandler;
type JobStatus = "queued" | "running" | "awaitingTool" | "awaitingHuman" | "succeeded" | "failed" | "timeout" | "canceled";
type JobFeedbackSentiment = "good" | "bad";
interface JobFeedbackToolCall {
    callId?: string;
    toolName?: string;
    input?: unknown;
    output?: unknown;
    error?: string;
    startedAt?: number;
    completedAt?: number;
    durationMs?: number | null;
}
interface JobFeedbackMetadata {
    source: "sdk";
    status: JobStatus;
    code: string;
    domainRevision?: string;
    createdAt: number;
    startedAt?: number;
    completedAt?: number;
    durationMs?: number | null;
    result?: unknown;
    error?: string;
    stdout: string[];
    stderr: string[];
    toolCalls: JobFeedbackToolCall[];
}
interface JobFeedbackInput {
    sentiment: JobFeedbackSentiment;
    comment?: string | null;
}
interface JobFeedbackRecord {
    feedbackId: string;
    tenantId?: string;
    sessionId: string;
    environmentId: string;
    sandboxId?: string;
    buildId?: string;
    subjectId?: string;
    jobId: string;
    sentiment: JobFeedbackSentiment;
    comment?: string | null;
    metadata: JobFeedbackMetadata & Record<string, unknown>;
    createdAt: number;
    updatedAt: number;
}
/**
 * Persisted feedback row listed at the environment level.
 */
interface EnvironmentFeedbackRecord {
    feedbackId: string;
    sessionId: string;
    jobId: string;
    sentiment: JobFeedbackSentiment;
    comment?: string | null;
    metadata?: Record<string, unknown> | null;
    createdAt: string | null;
}
/**
 * Result from submitting a job
 */
interface JobSubmitResult {
    jobId: string;
}
/**
 * Represents a job executed in the sandbox
 */
interface Job {
    /** Unique Job ID */
    id: string;
    /** Current status of the job */
    status: JobStatus;
    /** Promise that resolves with the job result */
    result: Promise<unknown>;
    /** Attach user feedback to this job and persist it with job/session metadata */
    leaveFeedback(input: JobFeedbackInput): Promise<JobFeedbackRecord>;
    /** Subscribe to job events */
    on(event: string, handler: (data: unknown) => void): () => void;
}
interface Prompt {
    id: string;
    type: "confirm" | "choice" | "input";
    title: string;
    message: string;
    options?: Array<string | {
        value: string;
        label: string;
        description?: string;
    }>;
    defaultValue?: unknown;
    placeholder?: string;
    allowEmpty?: boolean;
    metadata?: Record<string, unknown>;
}
interface ConversationMessageShowRefs {
    entryPaths?: string[];
    listNames?: string[];
    variableNames?: string[];
}
interface ConversationMessageInput {
    role: "user" | "assistant";
    content?: string;
    show?: ConversationMessageShowRefs;
    jobId?: string;
    promptId?: string;
    timestamp?: number;
}
interface ConversationAppendResult {
    ok: boolean;
    messageId: string;
    timestamp: number;
    jobId?: string;
    promptId?: string;
}
interface SessionConversationMessage {
    id: string;
    role: "user" | "assistant";
    content?: string;
    show?: ConversationMessageShowRefs;
    jobId?: string;
    promptId?: string;
    ts: number;
    [key: string]: unknown;
}
interface SessionTimelineEvent {
    id?: string;
    eventId?: string;
    kind?: string;
    type?: string;
    status?: string | null;
    message?: string;
    summary?: string;
    title?: string;
    ts?: number;
    timestamp?: number;
    at?: number;
    createdAt?: number;
    [key: string]: unknown;
}
interface SessionJobRecord {
    jobId: string;
    status: string;
    code?: string;
    createdAt?: number;
    startedAt?: number;
    completedAt?: number;
    durationMs?: number | null;
    progressPercent?: number | null;
    progressMessage?: string | null;
    stdout?: string[];
    stderr?: string[];
    result?: unknown;
    error?: string | null;
    toolCalls?: JobFeedbackToolCall[];
    prompts?: Record<string, unknown>;
    actionSummary?: string[];
    actionTrace?: Array<Record<string, unknown>>;
    agentMessages?: Array<Record<string, unknown>>;
    [key: string]: unknown;
}
interface SessionTranscriptEntry {
    id: string;
    role: "user" | "assistant";
    content: string;
    timestamp: number;
    jobId?: string;
    promptId?: string;
    code?: string;
    jobStatus?: string;
    jobResultPreview?: string;
    error?: string;
    show?: ConversationMessageShowRefs;
    historyContent?: string;
    source: "conversation" | "job_code" | "job_result" | "job_prompt" | "job_agent_message";
}
type SessionHeapFieldType = "string" | "number" | "boolean" | "null" | "unknown";
interface SessionHeapFieldValue {
    name: string;
    type: SessionHeapFieldType;
    value: string | number | boolean | null;
}
interface SessionHeapEntry {
    path: string;
    className: string;
    id: string;
    label?: string | null;
    description?: string | null;
    prototypes: string[];
    fields: SessionHeapFieldValue[];
    relatedJobIds: string[];
    source: string;
    createdAt: number;
    updatedAt: number;
}
interface SessionHeapList {
    name: string;
    className: string;
    paths: string[];
    relatedJobIds: string[];
    updatedAt: number;
}
interface SessionHeapVariable {
    name: string;
    kind: "entry" | "list" | "scalar";
    entryPath?: string;
    listName?: string;
    value?: string | number | boolean | null;
    className?: string;
    updatedAt: number;
}
interface SessionHeapSnapshot {
    entriesByPath: Record<string, SessionHeapEntry>;
    listsByName: Record<string, SessionHeapList>;
    variablesByName: Record<string, SessionHeapVariable>;
    updatedAt: number;
}
interface SessionDocumentResult {
    sessionState: Record<string, unknown> | null;
    document: Record<string, unknown> | null;
    savedAt: number;
}
interface SessionCollectionListOptions {
    limit?: number;
    cursor?: string | null;
}
interface SessionJobListOptions extends SessionCollectionListOptions {
    status?: string | null;
}
interface SessionCollectionListResult<T = unknown> {
    items: T[];
    nextCursor: string | null;
    totalCount: number;
}
interface WSDisconnectInfo {
    code?: number;
    reason?: string;
    wasClean?: boolean;
    unexpected: boolean;
    timestamp: number;
    reconnectScheduled: boolean;
    reconnectDelayMs?: number;
}
interface WSReconnectErrorInfo {
    sessionId: string;
    error: string;
    timestamp: number;
}
interface WSClientOptions {
    url: string;
    sessionId: string;
    token: string;
    tokenProvider?: AccessTokenProvider;
    WebSocketCtor?: any;
    onUnexpectedClose?: (info: WSDisconnectInfo) => void;
    onReconnectError?: (info: WSReconnectErrorInfo) => void;
}
interface RPCRequest {
    type: "rpc";
    method: string;
    params: unknown;
    id: string;
}
interface RPCResponse {
    type: "rpc_result" | "rpc_error";
    id: string;
    result?: unknown;
    error?: {
        code: number;
        message: string;
        data?: unknown;
    };
}
interface SyncMessage {
    type: "sync";
    message?: string | number[] | Uint8Array;
    data?: number[];
}
interface RPCRequestFromServer {
    type: "rpc";
    method: string;
    params: unknown;
    id: string;
}
interface ToolInvokeParams {
    callId: string;
    toolName: string;
    input: unknown;
}
interface ToolResultParams {
    callId: string;
    result?: unknown;
    error?: string | {
        code: string;
        message: string;
    };
}
/**
 * A model reference as returned from relationship queries
 */
interface ModelRef {
    path: string;
    label?: string;
}
/**
 * Relationship info as returned from the GraphQL API.
 * Represents a typed, bidirectional relationship between two model types,
 * seen from one model's perspective.
 */
interface RelationshipInfo {
    /** Unique name of this relationship definition */
    name: string;
    /** The submodel on this model that holds the relationship */
    local_submodel: ModelRef;
    /** Whether this side is a "many" collection */
    local_is_many: boolean;
    /** The submodel on the foreign model */
    foreign_submodel: ModelRef;
    /** Whether the foreign side is a "many" collection */
    foreign_is_many: boolean;
    /** The foreign model type */
    foreign_model: ModelRef;
    /** Computed relationship kind: "one_to_one" | "one_to_many" | "many_to_one" | "many_to_many" */
    relationship_kind: "one_to_one" | "one_to_many" | "many_to_one" | "many_to_many";
}
/**
 * Options for defining a relationship between two model types
 */
interface DefineRelationshipOptions {
    /** The model to define the relationship on (the "left" / "local" type) */
    model: string;
    /** The submodel name on the local model (e.g., "books") */
    localSubmodel: string;
    /** Whether the local side is "many" */
    localIsMany: boolean;
    /** The foreign model type (e.g., "book") */
    foreignModel: string;
    /** The submodel name on the foreign model (e.g., "author") */
    foreignSubmodel: string;
    /** Whether the foreign side is "many" */
    foreignIsMany: boolean;
    /** Optional relationship name (auto-generated if omitted) */
    name?: string;
}
/**
 * Options for creating or updating a class instance in the graph.
 *
 * `recordObject` uses the graph's `instantiate` (find-or-create) semantics:
 * if an instance with the given `id` already exists under the class, its
 * fields are updated in place; otherwise a new instance is created.
 */
interface RecordObjectOptions {
    /** The class to instantiate (e.g., "author") */
    className: string;
    /**
     * Real-world object ID. Unique within its class, but two objects of
     * different classes may share the same ID.  Internally the SDK derives
     * a unique graph path as `{className}__{id}`.
     */
    id: string;
    /** Optional display label (defaults to `id`) */
    label?: string;
    /** Scalar field values to set on the instance */
    fields?: Record<string, string | number | boolean | null>;
    /**
     * Relationship attachments.
     * Keys are relationship submodel names.  Values are real-world IDs
     * (not graph paths) — the SDK resolves them using the foreign class
     * derived from the relationship definition.
     * - For a "one" side: pass a single target ID (string)
     * - For a "many" side: pass an array of target IDs
     */
    relationships?: Record<string, string | string[]>;
}
/**
 * Return value from `recordObject()`
 */
interface RecordObjectResult {
    /** The internal graph path (e.g., "author__tolkien") */
    path: string;
    /** The real-world object ID as provided by the caller (e.g., "tolkien") */
    id: string;
    /** Whether the instance was newly created (false = updated) */
    created: boolean;
}
/**
 * Metadata for one completed HTTP chunk in `recordObjects()`.
 * Chunk indices follow input order; when concurrency is greater than 1, completion order may differ.
 */
interface RecordObjectsChunkInfo {
    /** Zero-based chunk index */
    chunkIndex: number;
    totalChunks: number;
    /** Zero-based offset into the original `records` array */
    offset: number;
    /** Number of records in this chunk */
    recordCount: number;
    /** Wall time for this chunk’s POST (including retries) */
    durationMs: number;
    /** Acknowledgements for this chunk, in the same order as the slice sent */
    results: RecordObjectResult[];
}
/**
 * Optional tuning for `recordObjects()` — batching, parallelism, and progress hooks.
 */
interface RecordObjectsOptions {
    /**
     * Max records per HTTP POST to the control-plane batch endpoint. Default 100.
     * Smaller values: more round trips and finer `onChunkComplete` updates.
     * Larger values: fewer requests (watch request size/timeouts).
     */
    batchSize?: number;
    /**
     * How many chunk POSTs may run concurrently. Default 1 (strictly sequential).
     * Values above 1 can reduce wall time when the server can overlap work; capped at 16.
     */
    concurrency?: number;
    /**
     * Called after each chunk succeeds (after retries). Useful for UI progress bars.
     */
    onChunkComplete?: (info: RecordObjectsChunkInfo) => void | Promise<void>;
}
type RecordImportStatus = "queued" | "processing" | "completed" | "failed" | "canceled";
type RecordImportItemStatus = "queued" | "processing" | "completed" | "failed" | "canceled";
interface RecordImportStats {
    totalRecords: number;
    queuedRecords: number;
    processingRecords: number;
    completedRecords: number;
    failedRecords: number;
    canceledRecords: number;
    awaitingRecords: number;
}
interface RecordImportItem {
    itemId: string;
    importId: string;
    tenantId: string;
    environmentId: string;
    className: string;
    id: string;
    label: string | null;
    fields: Record<string, string | number | boolean | null> | null;
    relationships: Record<string, string | string[]> | null;
    status: RecordImportItemStatus;
    attempts: number;
    errorMessage: string | null;
    resultPath: string | null;
    resultCreated: boolean | null;
    createdAt: number;
    updatedAt: number;
    processedAt: number | null;
}
interface RecordImport {
    importId: string;
    tenantId: string;
    environmentId: string;
    sandboxId: string;
    subjectId: string;
    setupRunId?: string | null;
    status: RecordImportStatus;
    batchSize: number;
    errorMessage: string | null;
    createdAt: number;
    updatedAt: number;
    startedAt: number | null;
    finishedAt: number | null;
    canceledAt: number | null;
    stats: RecordImportStats;
}
interface EnvironmentRecordImportSummary extends RecordImportStats {
    environmentId: string;
    totalImports: number;
    activeImports: number;
    updatedAt: number;
}
type EnvironmentSetupTriggerReason = "new_environment" | "fresh_after_version_update";
type EnvironmentSetupLifecycleStatus = "running" | "completed" | "failed";
interface EnvironmentSetupSummary extends RecordImportStats {
    setupRunId: string;
    environmentId: string;
    sandboxId: string;
    subjectId: string;
    triggerReason: EnvironmentSetupTriggerReason;
    lifecycleStatus: EnvironmentSetupLifecycleStatus;
    stage: string | null;
    totalObjectsToImport: number;
    totalImports: number;
    activeImports: number;
    errorMessage: string | null;
    startedAt: number;
    hookCompletedAt: number | null;
    finishedAt: number | null;
    updatedAt: number;
}
interface EnvironmentImporterImportOptions {
    batchSize?: number;
}
interface EnvironmentImporter {
    environmentId: string;
    sandboxId: string;
    subjectId: string;
    reason: EnvironmentSetupTriggerReason;
    incrementTotalObjectsToImportCount: (n: number) => Promise<void>;
    setStage: (stage: string | null) => Promise<void>;
    importRecords: (records: RecordObjectOptions[], options?: EnvironmentImporterImportOptions) => Promise<RecordImport>;
}
/**
 * Property specification in a manifest operation
 */
interface ManifestPropertySpec {
    value?: string | number | boolean;
    ref?: string;
    instanceOf?: string;
    create?: string;
    has?: Record<string, ManifestPropertySpec>;
    type?: string;
    description?: string;
    required?: boolean;
    note?: string | string[];
    enum?: string[] | ManifestEnumRuleSpec;
    filterBy?: boolean | string[] | ManifestFilterBySpec;
    validate?: ManifestValidationRuleSpec[];
}
type ManifestValidationOperator = "eq" | "neq" | "gt" | "gte" | "lt" | "lte" | "true" | "false" | "regex" | "contains" | "not_contains" | "starts_with" | "ends_with";
interface ManifestEnumRuleSpec {
    values: string[];
    message?: string;
}
interface ManifestFilterBySpec {
    operators: string[];
    scalarType?: string;
}
interface ManifestValidationRuleSpec {
    operator: ManifestValidationOperator;
    stringValue?: string;
    numberValue?: number;
    booleanValue?: boolean;
    message?: string;
}
interface ManifestStateMachineStateSpec {
    name: string;
    isFinal?: boolean;
}
interface ManifestStateMachineTransitionSpec {
    name: string;
    from: string;
    to: string;
}
interface ManifestStateMachineSpec {
    name: string;
    entryState: string;
    states: Array<string | ManifestStateMachineStateSpec>;
    transitions: ManifestStateMachineTransitionSpec[];
    finalStates?: string[];
}
interface ManifestPostConditionSpec {
    condition: string;
    description?: string;
}
interface ManifestDryRunSpec {
    enabled?: boolean;
    description?: string;
}
interface ManifestReverseSpec {
    handler?: string;
    description?: string;
}
interface ManifestApprovalRequiredSpec {
    required?: boolean;
    reason?: string;
    mode?: string;
}
interface ManifestEffectMetamodelSpec {
    postCondition?: string | ManifestPostConditionSpec;
    dryRun?: boolean | ManifestDryRunSpec;
    reverse?: string | ManifestReverseSpec;
    approvalRequired?: boolean | ManifestApprovalRequiredSpec;
}
/**
 * Relationship definition between two classes
 */
interface ManifestRelationshipDef {
    /** Optional name (auto-generated from left_right if omitted) */
    name?: string;
    /** Left model path */
    left: string;
    /** Right model path */
    right: string;
    /** Submodel name on the left model */
    leftSubmodel: string;
    /** Submodel name on the right model */
    rightSubmodel: string;
    /** Whether the left side is a collection */
    leftIsMany: boolean;
    /** Whether the right side is a collection */
    rightIsMany: boolean;
}
interface ManifestEffectSchema {
    type: string;
    properties?: Record<string, unknown>;
    required?: string[];
    items?: unknown;
    description?: string;
    [key: string]: unknown;
}
interface ManifestEffectDeclaration {
    name: string;
    description?: string;
    attachedClass?: string;
    isStatic?: boolean;
    inputSchema: ManifestEffectSchema;
    outputSchema?: ManifestEffectSchema;
    stability?: "stable" | "experimental" | "deprecated";
    tags?: string[];
    metamodels?: ManifestEffectMetamodelSpec;
}
/**
 * An event type within an event stream definition
 */
interface ManifestEventTypeDef {
    name: string;
    description?: string;
    payloadSchema: ManifestEffectSchema;
}
/**
 * Event stream definition for outgoing typed events
 */
interface ManifestEventStreamDef {
    name: string;
    description?: string;
    eventTypes: ManifestEventTypeDef[];
}
/**
 * A single operation in a manifest volume
 */
interface ManifestOperation {
    /** Create a new model/class */
    create?: string;
    /** Target an existing model for modification */
    on?: string;
    /** Extend from a parent class */
    extends?: string;
    /** Instantiate a type */
    instanceOf?: string;
    /** Define submodels/fields */
    has?: Record<string, ManifestPropertySpec>;
    /** Advisory notes attached to the model/class itself */
    note?: string | string[];
    /** State machines attached to the created or targeted class */
    stateMachines?: ManifestStateMachineSpec[];
    /** Define a relationship between two classes */
    defineRelationship?: ManifestRelationshipDef;
    /** Declare a build-owned effect */
    withEffect?: ManifestEffectDeclaration;
    /** Define an outgoing event stream with typed events */
    defineEventStream?: ManifestEventStreamDef;
}
/**
 * A volume in a manifest
 */
/**
 * Import descriptor for referencing modules
 */
interface ManifestImport {
    /** Alias prefix used in operations (e.g., "@std") */
    alias: string;
    /** Module name (e.g., "standard_modules") */
    name: string;
    /** Version label (e.g., "prod", "v1.2.3") */
    label?: string;
}
interface ManifestVolume {
    name: string;
    scope: "sandbox" | "build" | "user";
    imports?: ManifestImport[];
    operations: ManifestOperation[];
}
/**
 * A manifest defines the structure of a sandbox's data model
 */
interface ManifestContent {
    schemaVersion: 2;
    name: string;
    description?: string;
    volumes: ManifestVolume[];
}
/**
 * Result from a GraphQL query execution
 */
interface GraphQLResult<T = any> {
    data?: T;
    errors?: Array<{
        message: string;
        locations?: Array<{
            line: number;
            column: number;
        }>;
        path?: Array<string | number>;
        extensions?: Record<string, any>;
    }>;
}
interface APIError {
    error: string;
    message?: string;
}
interface DeleteResponse {
    deleted: boolean;
}
interface StreamEvent {
    eventId: string;
    streamName: string;
    eventType: string;
    payload: Record<string, unknown>;
    environmentId: string;
    sessionId?: string;
    subjectId?: string;
    source: "sandbox" | "api";
    isAcked: boolean;
    createdAt: number;
}
interface StreamSubscription {
    unsubscribe(): void;
}
interface StreamStats {
    streamName: string;
    eventType: string;
    total: number;
    last1h: number;
    last24h: number;
    unacked: number;
}

declare class WSClient {
    private ws;
    private url;
    private sessionId;
    private token;
    private messageQueue;
    private syncHandlers;
    private rpcHandlers;
    private eventHandlers;
    private nextRpcId;
    doc: Automerge.Doc<Record<string, unknown>>;
    private syncState;
    private reconnectTimer;
    private tokenRefreshTimer;
    private isExplicitlyDisconnected;
    private options;
    constructor(options: WSClientOptions);
    get currentSessionId(): string;
    private clearTokenRefreshTimer;
    private decodeBase64Url;
    private getTokenExpiryMs;
    private scheduleTokenRefresh;
    private refreshTokenInBackground;
    private resolveTokenForConnect;
    /**
     * Connect to the WebSocket server
     * @returns {Promise<void>} Resolves when connection is open
     */
    connect(): Promise<void>;
    private normalizeReason;
    private rejectPending;
    private buildDisconnectError;
    private handleDisconnect;
    private handleMessage;
    /**
     * Make an RPC call to the server
     * @param {string} method - RPC method name
     * @param {unknown} params - Request parameters
     * @returns {Promise<unknown>} Response result
     * @throws {Error} If connection is closed or timeout occurs
     */
    call(method: string, params: unknown): Promise<unknown>;
    private handleIncomingRpc;
    /**
     * Subscribe to client events
     * @param {string} event - Event name
     * @param {Function} handler - Event handler
     */
    on(event: string, handler: (params: unknown) => void): void;
    /**
     * Register an RPC handler for incoming server requests
     * @param {string} method - RPC method name
     * @param {Function} handler - Handler function
     */
    registerRpcHandler(method: string, handler: (params: unknown) => Promise<unknown>): void;
    /**
     * Unsubscribe from client events
     * @param {string} event - Event name
     * @param {Function} handler - Handler to remove
     */
    off(event: string, handler: (params: unknown) => void): void;
    /**
     * Emit an event locally
     * @param {string} event - Event name
     * @param params - Event data
     */
    emit(event: string, params: unknown): void;
    /**
     * Disconnect the WebSocket and clear state
     */
    disconnect(): void;
}

declare class Session {
    protected client: WSClient;
    private clientId;
    private jobsMap;
    private pendingAgentMessagesByJobId;
    private eventListeners;
    private toolHandlers;
    /** Tracks which tools are instance methods (className set, not static) */
    private instanceTools;
    private currentDomainRevision;
    /** Local effect registry: name → full ToolWithHandler */
    private effects;
    /** Last known tools for diffing */
    private lastKnownTools;
    /** Last seen live prompts, keyed by prompt id, for answer normalization */
    private promptCache;
    constructor(client: WSClient, clientId?: string);
    private extractDomainRevisionFromDoc;
    private buildLegacyEffectContext;
    private stringifyConversationValue;
    get document(): Doc<Record<string, unknown>>;
    get sessionId(): string;
    get domainRevision(): string | null;
    /**
     * Make a raw RPC call to the session's Durable Object.
     *
     * Use this when you need to call an RPC method that doesn't have a
     * dedicated wrapper method on the Session/Environment class.
     *
     * @param method - RPC method name (e.g. 'domain.fetchPackagePart')
     * @param params - Request parameters
     * @returns The raw RPC response
     *
     * @example
     * ```typescript
     * const result = await env.rpc('domain.fetchPackagePart', {
     *   moduleSpecifier: '@sandbox/domain',
     *   part: 'types',
     * });
     * ```
     */
    rpc<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;
    /**
     * Send client hello to establish the session
     */
    hello(): Promise<{
        ok: boolean;
        environmentId?: string;
        docId?: string;
        graphContainerStatus?: {
            lastKeepAliveAt: number;
            status: "warming" | "hot" | "unknown";
        };
    }>;
    publishTools(tools: ToolWithHandler[], revision?: string): Promise<PublishToolsResult>;
    publishEffect(effect: ToolWithHandler): Promise<PublishToolsResult>;
    publishEffects(effects: ToolWithHandler[]): Promise<PublishToolsResult>;
    unpublishEffect(name: string): Promise<PublishToolsResult>;
    unpublishAllEffects(): Promise<PublishToolsResult>;
    /**
     * Submit a job to execute code in the sandbox.
     *
     * The code can import typed classes from `./sandbox-tools`:
     * ```typescript
     * import { Author, Book, global_search } from './sandbox-tools';
     *
     * const totalAuthors = await Author.count();
     * const firstAuthorsPage = await Author.page({ page: 1, perPage: 10, saveAs: 'recent_authors' });
     * const authors = firstAuthorsPage.items;
     * const tolkien = await Author.get({ path: 'author_tolkien' });
     * const bio = await tolkien.get_bio({ detailed: true });
     * const books = await tolkien.get_books();
     * for await (const author of Author.iterate({ perPage: 100, maxItems: 500 })) {
     *   console.log(author.id);
     * }
     * ```
     *
     * Effect calls (instance methods, static methods, global functions) trigger
     * `effect.invoke` RPC back to the sandbox effect host, where the registered handlers
     * execute locally and return the result to the sandbox.
     */
    submitJob(code: string, domainRevision?: string): Promise<Job>;
    /**
     * Register a handler for a specific tool.
     * @param isInstance - If true, handler will receive (id, params) for instance method dispatch.
     */
    registerToolHandler(name: string, handler: ToolHandler | InstanceToolHandler, isInstance?: boolean): void;
    /**
     * Respond to a prompt request from the sandbox
     */
    answerPrompt(promptId: string, answer: unknown): Promise<void>;
    appendConversationMessage(input: ConversationMessageInput): Promise<ConversationAppendResult>;
    /**
     * Get the current list of available effects.
     * Consolidates effect declarations and live availability for the session.
     */
    getEffects(): EffectInfo[];
    /**
     * Backwards-compatible alias for `getEffects()`.
     */
    getTools(): ToolInfo[];
    /**
     * Subscribe to effect changes (added, removed, updated).
     * @param callback - Function called with change events
     * @returns Unsubscribe function
     */
    onEffectsChanged(callback: (event: EffectsChangedEvent) => void): () => void;
    /**
     * Backwards-compatible alias for `onEffectsChanged()`.
     */
    onToolsChanged(callback: (event: ToolsChangedEvent) => void): () => void;
    /**
     * Get the current domain state and available tools
     */
    getDomain(): Promise<DomainState>;
    /**
     * Fetch a domain package part from the backend (no fallback).
     */
    private fetchDomainPart;
    /**
     * Get TypeScript class declarations for the current domain (for LLM/code gen).
     */
    getDomainTypes(): Promise<string>;
    /**
     * Get Markdown documentation for the current domain (human-readable).
     */
    getDomainDocs(): Promise<string>;
    /**
     * Get domain documentation for LLMs. Returns types (preferred) or fallback.
     */
    getDomainDocumentation(): Promise<string>;
    /**
     * Generate markdown documentation from the domain summary.
     * Class-aware: groups tools by class with property/relationship info.
     */
    private generateFallbackDocs;
    /**
     * Close the session and disconnect from the sandbox
     */
    disconnect(): Promise<void>;
    /**
     * Subscribe to session events
     */
    on(event: string, handler: (data: unknown) => void): () => void;
    /**
     * Unsubscribe from session events
     */
    off(event: string, handler: (data: unknown) => void): void;
    private setupToolInvokeHandler;
    private setupEventHandlers;
    protected emit(event: string, data: unknown): void;
    /**
     * Check for changes in the effect catalog and emit change events if needed.
     */
    private checkForToolChanges;
}

type EnvironmentImporterHandler = (importer: EnvironmentImporter) => Promise<void> | void;
/**
 * Environment is the sessionless handle for one resolved ontology environment.
 *
 * Use it to query or mutate environment data directly, or to open live runtime
 * sessions through `environment.sessions.*` when you need jobs, prompts, or a
 * synced Automerge document.
 */
declare class Environment {
    private granular;
    private envData;
    private _apiKey;
    private _apiEndpoint;
    constructor(granular: Granular, envData: EnvironmentData, apiKey: string, apiEndpoint: string);
    /** The environment ID */
    get environmentId(): string;
    /** The sandbox ID */
    get sandboxId(): string;
    /** The ontology ID */
    get ontologyId(): string;
    /** The subject ID */
    get subjectId(): string;
    /** The named environment slot, such as dev or prod */
    get envName(): string;
    /** The named environment slot, such as dev or prod */
    get environment(): string;
    /** The resolved ontology version backing this environment */
    get versionId(): string;
    /** Internal Granular user identifier for this environment */
    get granularId(): string;
    /** The permission profile ID */
    get permissionProfileId(): string;
    /** The current build policy backing this environment */
    get buildPolicy(): BuildPolicy;
    /** The current update state relative to the followed tag */
    get updateState(): EnvironmentData["updateState"];
    /** The latest setup/import run summary for this environment, when available. */
    get setup(): EnvironmentSetupSummary | null;
    /** Convenience flag for whether this environment trails the current tag target */
    get isOutdated(): boolean;
    /** The followed tag name when this environment is tag-tracked */
    get tag(): string | null;
    /** The GraphQL API endpoint URL */
    get apiEndpoint(): string;
    /** Internal auth token used for control-plane and runtime fallback requests */
    get authToken(): string;
    /** Base runtime URL derived from the GraphQL endpoint */
    get runtimeBaseUrl(): string;
    syncEnvironmentData(envData: EnvironmentData): void;
    get sessions(): {
        list: (options?: {
            status?: "active" | "closed" | "all";
        }) => Promise<ConversationSessionInfo[]>;
        create: (options?: CreateSessionOptions) => Promise<EnvironmentSession>;
        connect: (sessionId: string, options?: {
            clientId?: string;
        }) => Promise<EnvironmentSession>;
        reopen: (sessionId: string, options?: {
            clientId?: string;
        }) => Promise<EnvironmentSession>;
        close: (sessionId: string, session?: EnvironmentSession | null) => Promise<void>;
    };
    get data(): {
        record: (record: RecordObjectOptions) => Promise<RecordObjectResult>;
        recordMany: (records: RecordObjectOptions[], options?: RecordObjectsOptions) => Promise<RecordObjectResult[]>;
        import: (records: RecordObjectOptions[], options?: {
            batchSize?: number;
        }) => Promise<RecordImport>;
        listImports: (status?: RecordImportStatus) => Promise<RecordImport[]>;
        getImport: (importId: string) => Promise<RecordImport>;
        getImportSummary: () => Promise<EnvironmentRecordImportSummary>;
        cancelImport: (importId: string) => Promise<RecordImport>;
        getAwaitingCount: () => Promise<number>;
    };
    get feedback(): {
        list: () => Promise<EnvironmentFeedbackRecord[]>;
    };
    /**
     * Sessionless environments do not own a live transport, so disconnecting the
     * environment handle itself is a no-op. This keeps the public surface
     * symmetric with `EnvironmentSession.disconnect()` and lets callers always
     * clean up safely without tracking whether they currently hold an environment
     * or a session.
     */
    disconnect(): Promise<void>;
    listSessions(status?: "active" | "closed" | "all"): Promise<ConversationSessionInfo[]>;
    createSession(options?: CreateSessionOptions): Promise<EnvironmentSession>;
    connectSession(sessionId: string, options?: {
        clientId?: string;
    }): Promise<EnvironmentSession>;
    reopenSession(sessionId: string, options?: {
        clientId?: string;
    }): Promise<EnvironmentSession>;
    closeSession(sessionId: string, session?: EnvironmentSession | null): Promise<void>;
    listFeedback(): Promise<EnvironmentFeedbackRecord[]>;
    private getRuntimeBaseUrl;
    private controlPlaneRequest;
    /**
     * Convert a class name + real-world ID into a unique graph path.
     *
     * Two objects of *different* classes may share the same real-world ID,
     * so the graph path must incorporate the class to guarantee uniqueness.
     *
     * Format: `{className}_{id}` — deterministic, human-readable.
     *
     * **Convention**: class names should be simple identifiers without
     * underscores (e.g. `author`, `book`).  This ensures the prefix is
     * unambiguously parseable by `extractIdFromGraphPath`.
     */
    static toGraphPath(className: string, id: string): string;
    /**
     * Extract the real-world ID from a graph path, given the class name.
     *
     * Strips the `{className}_` prefix. Returns the raw path if the
     * expected prefix is not found.
     */
    static extractIdFromGraphPath(graphPath: string, className: string): string;
    /**
     * Execute a GraphQL query against the environment's graph.
     *
     * The query uses the Granular graph query language (based on Cypher/GraphQL).
     * Authentication is handled automatically using the SDK's API key.
     *
     * @param query - The GraphQL query string
     * @param variables - Optional variables for the query
     * @returns The query result data
     *
     * @example
     * ```typescript
     * // Read the workspace
     * const result = await env.graphql(
     *   `query { model(path: "workspace") { path label submodels { path label } } }`
     * );
     * console.log(result.data);
     *
     * // Create a model
     * const created = await env.graphql(
     *   `mutation { at(path: "workspace") { create_submodel(subpath: "my_node", label: "My Node", prototype: "Model") { model { path label } } } }`
     * );
     * ```
     */
    graphql<T = any>(query: string, variables?: Record<string, any>): Promise<GraphQLResult<T>>;
    /**
     * Define a relationship between two model types.
     *
     * Creates both submodels (if they don't exist) and links them with
     * a RelationshipDef node that encodes cardinality.
     *
     * @example
     * ```typescript
     * // Author has many Books, Book has one Author
     * const rel = await env.defineRelationship({
     *   model: 'author',
     *   localSubmodel: 'books',
     *   localIsMany: true,
     *   foreignModel: 'book',
     *   foreignSubmodel: 'author',
     *   foreignIsMany: false,
     * });
     * console.log(rel.relationship_kind); // "one_to_many"
     * ```
     */
    defineRelationship(options: DefineRelationshipOptions): Promise<RelationshipInfo>;
    /**
     * Get all relationships for a model type.
     *
     * @param modelPath - The model type path (e.g., "author")
     * @returns Array of relationships from this model's perspective
     *
     * @example
     * ```typescript
     * const rels = await env.getRelationships('author');
     * for (const rel of rels) {
     *   console.log(`${rel.local_submodel.path} -> ${rel.foreign_model.path} (${rel.relationship_kind})`);
     * }
     * ```
     */
    getRelationships(modelPath: string): Promise<RelationshipInfo[]>;
    /**
     * Attach a target model to a relationship submodel.
     *
     * Handles cardinality automatically:
     * - "One" side: sets/replaces the reference
     * - "Many" side: adds the target to the collection
     *
     * If the target model doesn't exist, it's created as an instance of the foreign type.
     * Bidirectional sync is automatic.
     *
     * @param modelPath - The model instance path (e.g., "tolkien")
     * @param submodelPath - The relationship submodel (e.g., "books")
     * @param targetPath - The target model to attach (e.g., "lord_of_the_rings")
     *
     * @example
     * ```typescript
     * // Attach a book to an author (many side)
     * await env.attach('tolkien', 'books', 'lord_of_the_rings');
     * // This also automatically sets lord_of_the_rings:author -> tolkien
     * ```
     */
    attach(modelPath: string, submodelPath: string, targetPath: string): Promise<void>;
    /**
     * Detach a target model from a relationship submodel.
     *
     * Handles bidirectional cleanup automatically.
     *
     * @param modelPath - The model instance path
     * @param submodelPath - The relationship submodel
     * @param targetPath - The target to detach (optional for "one" side; omit on "many" side to detach all)
     *
     * @example
     * ```typescript
     * // Detach a specific book
     * await env.detach('tolkien', 'books', 'lord_of_the_rings');
     *
     * // Detach all books
     * await env.detach('tolkien', 'books');
     * ```
     */
    detach(modelPath: string, submodelPath: string, targetPath?: string): Promise<void>;
    /**
     * List all related models through a relationship submodel.
     *
     * @param modelPath - The model instance path
     * @param submodelPath - The relationship submodel
     * @returns Array of related model references
     *
     * @example
     * ```typescript
     * const books = await env.listRelated('tolkien', 'books');
     * console.log(books); // [{ path: "lord_of_the_rings", label: "Lord of the Rings" }, ...]
     * ```
     */
    listRelated(modelPath: string, submodelPath: string): Promise<ModelRef[]>;
    /**
     * Apply a manifest to the current environment's graph.
     *
     * Translates each manifest operation into GraphQL mutations and executes them
     * in order. This is the core mechanism for creating classes, fields, and
     * relationships from a declarative manifest.
     *
     * @param manifest - The manifest content to apply
     * @returns Summary of applied operations
     *
     * @example
     * ```typescript
     * await environment.applyManifest({
     *   schemaVersion: 2,
     *   name: 'my-app',
     *   volumes: [{
     *     name: 'schema',
     *     scope: 'sandbox',
     *     operations: [
     *       { create: 'author', extends: 'class', has: { name: { type: 'string' } } },
     *       { create: 'book', extends: 'class', has: { title: { type: 'string' } } },
     *       { defineRelationship: {
     *         left: 'author', right: 'book',
     *         leftSubmodel: 'books', rightSubmodel: 'author',
     *         leftIsMany: true, rightIsMany: false,
     *       }},
     *     ],
     *   }],
     * });
     * ```
     */
    applyManifest(manifest: ManifestContent): Promise<{
        applied: number;
        errors: string[];
    }>;
    /**
     * Resolve an alias reference like "@std/class" → "class"
     * Strips the alias prefix, returning the bare model path.
     */
    private _resolveAlias;
    private _runGraphql;
    private _applyFieldMetamodels;
    private _applyModelMetamodels;
    private _ensureWorkspaceToolsRoot;
    private _storeEffectSchemas;
    private _applyEffectMetamodels;
    private _ensureWorkspaceStreamsRoot;
    private _applyEventStreamDeclaration;
    private _applyEffectDeclaration;
    /**
     * Apply a single manifest operation via GraphQL
     */
    private _applyOperation;
    /**
     * Apply field definitions (has) to a model via GraphQL
     */
    private _applyFields;
    /**
     * Create or update an instance of a class in the graph.
     *
     * Uses `instantiate` under the hood, which has find-or-create semantics:
     * if an instance with the given `id` already exists for the class it is
     * returned; otherwise a new instance is created.  Fields are then set
     * (overwriting previous values) and relationships are attached.
     *
     * The graph path is derived as `{className}_{id}` to ensure uniqueness
     * across classes (two objects of different classes may share the same
     * real-world ID).  Relationship targets are also resolved automatically
     * using the foreign class from the relationship definition.
     *
     * @param options - The object specification
     * @returns The graph path, real-world ID, and creation status
     *
     * @example
     * ```typescript
     * // Create an author with fields
     * const result = await env.recordObject({
     *   className: 'author',
     *   id: 'tolkien',
     *   label: 'J.R.R. Tolkien',
     *   fields: { name: 'J.R.R. Tolkien', birth_year: 1892 },
     *   relationships: { books: ['lotr', 'silmarillion'] },
     * });
     * // result.path → 'author_tolkien'  (internal graph path)
     * // result.id   → 'tolkien'         (real-world ID)
     * // result.created → true
     * ```
     */
    recordObject(options: RecordObjectOptions): Promise<RecordObjectResult>;
    /**
     * Batch version of `recordObject()`.
     *
     * Sends rows through the control-plane **`/records/batch`** endpoint in **chunks** (default
     * **100** records per HTTP request) so individual requests stay bounded and gateway timeouts are
     * unlikely. Each chunk is retried on transient network / worker errors.
     *
     * Use the optional second argument to:
     * - **`batchSize`** — rows per POST (smaller = more progress events; larger = fewer round trips).
     * - **`concurrency`** — run up to N chunk POSTs in parallel (capped at 16) when you want lower wall time.
     * - **`onChunkComplete`** — hook for UIs after each chunk succeeds (row order in the returned array
     *   always matches `records`; chunk **completion** order may differ when `concurrency > 1`).
     *
     * For **asynchronous** ingestion with worker-side batching and aggregate counters (`queued`,
     * `completed`, …), use **`enqueueRecordImport`** and poll **`getRecordImport`** /
     * **`getRecordImportSummary`** — best for very large fire-and-forget loads when immediate
     * synchronous commit of every row is not required.
     */
    recordObjects(records: RecordObjectOptions[], options?: RecordObjectsOptions): Promise<RecordObjectResult[]>;
    private executeRecordObjectsChunk;
    /**
     * Queue a background record import for this environment (async worker pipeline).
     *
     * **vs `recordObjects`:** this path accepts the full payload in one request, returns an
     * **`importId`**, and processes rows in the background — use **`getRecordImport`** /
     * **`getRecordImportSummary`** for progress. Choose it for large bulk loads where you do not
     * need every row committed before the HTTP call returns. Use **`recordObjects`** when you need
     * synchronous upserts and fine-grained chunk progress via **`onChunkComplete`**.
     */
    enqueueRecordImport(records: RecordObjectOptions[], options?: {
        batchSize?: number;
        setupRunId?: string;
    }): Promise<RecordImport>;
    /**
     * List queued or completed record imports for this environment.
     */
    listRecordImports(status?: RecordImportStatus): Promise<RecordImport[]>;
    /**
     * Fetch the latest aggregate import counters for this environment.
     */
    getRecordImportSummary(): Promise<EnvironmentRecordImportSummary>;
    /**
     * Convenience helper returning queued + processing records for this environment.
     */
    getAwaitingRecordCount(): Promise<number>;
    /**
     * Fetch a single record import by id.
     */
    getRecordImport(importId: string): Promise<RecordImport>;
    /**
     * Cancel a queued/background record import.
     */
    cancelRecordImport(importId: string): Promise<RecordImport>;
}
/**
 * Live runtime session attached to one opened environment.
 *
 * This is the object returned by `environment.sessions.create()` and friends.
 * It owns websocket state, prompts, job execution, and the synced Automerge
 * document while delegating environment-level data APIs back to
 * `session.environment`.
 */
declare class EnvironmentSession extends Session {
    readonly environment: Environment;
    /** The last known graph container status, updated by checkReadiness() or on heartbeat */
    graphContainerStatus: {
        lastKeepAliveAt: number;
        status: "warming" | "hot" | "unknown";
    } | null;
    constructor(client: WSClient, environment: Environment, clientId: string);
    get environmentId(): string;
    get sandboxId(): string;
    get ontologyId(): string;
    get subjectId(): string;
    get envName(): string;
    get tag(): string | null;
    get versionId(): string;
    get granularId(): string;
    get permissionProfileId(): string;
    get apiEndpoint(): string;
    get data(): {
        record: (record: RecordObjectOptions) => Promise<RecordObjectResult>;
        recordMany: (records: RecordObjectOptions[], options?: RecordObjectsOptions) => Promise<RecordObjectResult[]>;
        import: (records: RecordObjectOptions[], options?: {
            batchSize?: number;
        } | undefined) => Promise<RecordImport>;
        listImports: (status?: RecordImportStatus) => Promise<RecordImport[]>;
        getImport: (importId: string) => Promise<RecordImport>;
        getImportSummary: () => Promise<EnvironmentRecordImportSummary>;
        cancelImport: (importId: string) => Promise<RecordImport>;
        getAwaitingCount: () => Promise<number>;
    };
    get feedback(): {
        list: () => Promise<EnvironmentFeedbackRecord[]>;
    };
    /**
     * Return a plain JS copy of the synced session heap.
     */
    getHeap(): SessionHeapSnapshot;
    private sessionDataRequest;
    private collectAllSessionItems;
    /**
     * Fetch the live session document from the runtime DO.
     *
     * For history and saved artifacts, prefer the collection APIs on
     * `messages`, `timeline`, `jobs`, and `heap`.
     */
    getDocument(): Promise<SessionDocumentResult>;
    get messages(): {
        list: (options?: SessionCollectionListOptions) => Promise<SessionCollectionListResult<SessionConversationMessage>>;
    };
    get timeline(): {
        list: (options?: SessionCollectionListOptions) => Promise<SessionCollectionListResult<SessionTimelineEvent>>;
    };
    get jobs(): {
        list: (options?: SessionJobListOptions) => Promise<SessionCollectionListResult<SessionJobRecord>>;
        get: (jobId: string) => Promise<SessionJobRecord>;
    };
    get heap(): {
        entries: {
            list: (options?: SessionCollectionListOptions) => Promise<SessionCollectionListResult<SessionHeapEntry>>;
            get: (path: string) => Promise<SessionHeapEntry>;
        };
        lists: {
            list: (options?: SessionCollectionListOptions) => Promise<SessionCollectionListResult<SessionHeapList>>;
            get: (name: string) => Promise<SessionHeapList>;
        };
    };
    get transcript(): {
        list: (options?: SessionCollectionListOptions) => Promise<SessionCollectionListResult<SessionTranscriptEntry>>;
    };
    graphql<T = any>(query: string, variables?: Record<string, any>): Promise<GraphQLResult<T>>;
    defineRelationship(options: DefineRelationshipOptions): Promise<RelationshipInfo>;
    getRelationships(modelPath: string): Promise<RelationshipInfo[]>;
    attach(modelPath: string, submodelPath: string, targetPath: string): Promise<void>;
    detach(modelPath: string, submodelPath: string, targetPath?: string): Promise<void>;
    listRelated(modelPath: string, submodelPath: string): Promise<ModelRef[]>;
    applyManifest(manifest: ManifestContent): Promise<{
        applied: number;
        errors: string[];
    }>;
    recordObject(options: RecordObjectOptions): Promise<RecordObjectResult>;
    recordObjects(records: RecordObjectOptions[], options?: RecordObjectsOptions): Promise<RecordObjectResult[]>;
    enqueueRecordImport(records: RecordObjectOptions[], options?: {
        batchSize?: number;
    }): Promise<RecordImport>;
    listRecordImports(status?: RecordImportStatus): Promise<RecordImport[]>;
    getRecordImportSummary(): Promise<EnvironmentRecordImportSummary>;
    getAwaitingRecordCount(): Promise<number>;
    getRecordImport(importId: string): Promise<RecordImport>;
    cancelRecordImport(importId: string): Promise<RecordImport>;
    listFeedback(): Promise<EnvironmentFeedbackRecord[]>;
    /**
     * Close the session and disconnect from the sandbox.
     *
     * Sends `client.goodbye` over WebSocket first, then issues an HTTP fallback
     * to the runtime goodbye endpoint if no definitive WS-side runtime notify
     * acknowledgement was observed.
     */
    disconnect(): Promise<void>;
    /**
     * Close only the socket transport without sending `client.goodbye`.
     */
    disconnectTransport(): void;
    /**
     * Backwards-compatible alias for `disconnect()`.
     */
    close(): Promise<void>;
    /**
     * Check if the graph container is ready and warm.
     */
    checkReadiness(): Promise<{
        lastKeepAliveAt: number;
        status: "warming" | "hot" | "unknown";
    }>;
}
declare class OntologyHandle {
    private granular;
    private ontologyNameOrId;
    constructor(granular: Granular, ontologyNameOrId: string);
    get effects(): {
        register: (effect: ToolWithHandler) => Promise<void>;
        registerMany: (effects: ToolWithHandler[]) => Promise<void>;
        unregister: (name: string) => Promise<void>;
        clear: () => Promise<void>;
        disconnect: () => Promise<void>;
    };
    get importer(): {
        onEnvironmentCreate: (handler: EnvironmentImporterHandler) => void;
        clear: () => void;
    };
}
declare class Granular {
    private apiKey;
    private apiUrl;
    private httpUrl;
    private tokenProvider?;
    private WebSocketCtor?;
    private onUnexpectedClose?;
    private onReconnectError?;
    private debugHttp;
    /** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
    private sandboxEffects;
    /** Live sandbox-scoped effect hosts keyed by sandboxId */
    private sandboxEffectHosts;
    /** In-flight host connection promises to avoid duplicate concurrent connects */
    private sandboxEffectHostPromises;
    /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
    private ontologyImporters;
    /** Resolved importer hooks keyed by sandboxId for fast lookups during openEnvironment(). */
    private sandboxImporters;
    /**
     * Create a new Granular client
     * @param options - Client configuration
     */
    constructor(options: GranularOptions);
    /**
     * Return an ontology-scoped handle for effects and other ontology-level APIs.
     */
    ontology(ontologyNameOrId: string): OntologyHandle;
    registerEnvironmentImporter(ontologyNameOrId: string, handler: EnvironmentImporterHandler): void;
    clearEnvironmentImporter(ontologyNameOrId: string): void;
    /**
     * Records/upserts a user and prepares them for sandbox connections
     *
     * @param options - User options
     * @returns The recorded user with both `userId` and `granularId`
     *
     * @example
     * ```typescript
     * const user = await granular.recordUser({
     *   userId: 'user_123',
     *   name: 'John Doe',
     *   permissions: ['agent'],
     * });
     * ```
     */
    recordUser(options: RecordUserOptions): Promise<User>;
    /**
     * Alias for `recordUser()` with user-facing naming that matches upsert semantics.
     */
    upsertUser(options: RecordUserOptions): Promise<User>;
    private resolveConnectUser;
    /**
     * Open or resolve an ontology environment for one user without opening a session.
     *
     * @example
     * ```typescript
     * const environment = await granular.openEnvironment({
     *   ontology: 'my-ontology',
     *   tag: 'dev',
     *   userId: 'user_123',
     *   permissions: ['agent'],
     * });
     *
     * await environment.data.record({
     *   className: 'customer',
     *   id: 'acme',
     *   fields: { name: 'Acme' },
     * });
     *
     * const session = await environment.sessions.create();
     * const job = await session.submitJob(`return "hello";`);
     * console.log(await job.result);
     * ```
     */
    openEnvironment(options: OpenEnvironmentOptions): Promise<Environment>;
    /**
     * Deprecated compatibility alias for `openEnvironment()`.
     *
     * `connect()` no longer opens a runtime session automatically.
     */
    connect(options: ConnectOptions): Promise<Environment>;
    private resolveRequestedTag;
    private buildManagedEnvironmentName;
    private matchesTagTrackedEnvironment;
    private sortEnvironmentsByRecency;
    private resolveOpenEnvironmentData;
    /**
     * List active (open) sessions for an environment — each session is one agent conversation thread.
     */
    listOpenSessions(filters: {
        environmentId: string;
    }): Promise<ConversationSessionInfo[]>;
    /**
     * List closed sessions for an environment (conversations that have disconnected).
     */
    listClosedSessions(filters: {
        environmentId: string;
    }): Promise<ConversationSessionInfo[]>;
    private listSessionsForEnvironment;
    private normalizeConversationSession;
    private static coerceIsoDate;
    /**
     * Create a new session (conversation) for an existing environment and connect to it.
     * The runtime graph is shared across all sessions for the same environment.
     */
    createSession(options: {
        environmentId: string;
        clientId?: string;
        initialHeap?: CreateSessionOptions["initialHeap"];
    }): Promise<EnvironmentSession>;
    /**
     * Connect to an existing open session (same conversation thread) using a freshly minted WebSocket token.
     */
    connectSession(options: {
        sessionId: string;
        clientId?: string;
    }): Promise<EnvironmentSession>;
    /**
     * Mark a session closed in the control plane. If `environment` is the connected handle for that
     * `sessionId`, disconnects the WebSocket so the runtime tears down cleanly.
     */
    closeSession(sessionId: string, environment?: EnvironmentSession | null): Promise<void>;
    /**
     * Re-open a closed session in the index and connect to its existing runtime document.
     */
    reopenSession(sessionId: string, options?: {
        clientId?: string;
    }): Promise<EnvironmentSession>;
    private resolveEnvironmentImporter;
    private maybeRunEnvironmentImporter;
    private bindEnvironmentHandle;
    private bindWebSocketEnvironmentSession;
    private activateEnvironment;
    private getSandboxEffectMap;
    private serializeEffect;
    private publishSandboxEffectCatalog;
    private syncSandboxEffectCatalog;
    private recoverEffectHost;
    private startEffectHostHeartbeat;
    private stopEffectHostHeartbeat;
    private synchronizeEffectHost;
    private ensureSandboxEffectHost;
    private disconnectSandboxEffectHost;
    /**
     * Register an effect (tool) for a specific sandbox.
     *
     * @param sandboxNameOrId - The name or ID of the sandbox
     * @param effect - The tool definition and handler
     */
    registerEffect(sandboxNameOrId: string, effect: ToolWithHandler): Promise<void>;
    /**
     * Register multiple effects (tools) for a specific sandbox.
     *
     * batch version of `registerEffect`.
     */
    registerEffects(sandboxNameOrId: string, effects: ToolWithHandler[]): Promise<void>;
    /**
     * Unregister an effect from a sandbox.
     *
     * Removes it from the local sandbox registry and updates the
     * sandbox-scoped live catalog.
     */
    unregisterEffect(sandboxNameOrId: string, name: string): Promise<void>;
    /**
     * Disconnect one sandbox-scoped effect host, or all of them when no sandbox is provided.
     *
     * This is primarily useful for long-lived helper processes such as generated
     * `granular-effects.ts` scripts that need to shut down cleanly on SIGINT/SIGTERM.
     */
    disconnectEffects(sandboxNameOrId?: string): Promise<void>;
    /**
     * Unregister all effects for a sandbox.
     */
    unregisterAllEffects(sandboxNameOrId: string): Promise<void>;
    /**
     * Find a sandbox by name or create it if it doesn't exist
     */
    private findOrCreateSandbox;
    /**
     * Ensure a permission profile exists for a sandbox, creating it if needed.
     * If profileName matches an existing profile name, returns its ID.
     * Otherwise, creates a new profile with default allow-all rules.
     */
    private ensurePermissionProfile;
    /**
     * Ensure an assignment exists for a subject in a sandbox with a permission profile
     */
    private ensureAssignment;
    /**
     * Sandbox management API
     */
    get sandboxes(): {
        list: () => Promise<SandboxListResponse>;
        get: (id: string) => Promise<Sandbox>;
        create: (data: CreateSandboxData) => Promise<Sandbox>;
        update: (id: string, data: Partial<CreateSandboxData>) => Promise<Sandbox>;
        delete: (id: string) => Promise<DeleteResponse>;
    };
    /**
     * Permission Profile management for sandboxes
     */
    get permissionProfiles(): {
        list: (sandboxId: string) => Promise<PermissionProfile[]>;
        get: (sandboxId: string, profileId: string) => Promise<PermissionProfile>;
        create: (sandboxId: string, data: CreatePermissionProfileData) => Promise<PermissionProfile>;
        delete: (sandboxId: string, profileId: string) => Promise<DeleteResponse>;
    };
    /**
     * Environment management
     */
    get environments(): {
        list: (sandboxId: string) => Promise<EnvironmentData[]>;
        get: (environmentId: string) => Promise<EnvironmentData>;
        create: (sandboxId: string, data: CreateEnvironmentData) => Promise<EnvironmentData>;
        delete: (environmentId: string) => Promise<DeleteResponse>;
    };
    /**
     * Event stream operations: query, subscribe, and acknowledge stream events
     */
    get streams(): {
        getEvents: (params: {
            ontology: string;
            stream: string;
            environment?: string;
            session?: string;
            eventTypes?: string[];
            since?: Date;
            until?: Date;
            isAcked?: boolean;
            limit?: number;
            offset?: number;
        }) => Promise<StreamEvent[]>;
        subscribe: (params: {
            ontology: string;
            stream: string;
            environment?: string;
            session?: string;
            eventTypes?: string[];
            since?: Date;
            onEvent: (event: StreamEvent) => void;
            onError?: (err: Error) => void;
            pollIntervalMs?: number;
        }) => StreamSubscription;
        ack: (eventId: string) => Promise<void>;
        ackBatch: (eventIds: string[]) => Promise<void>;
        getStats: (params: {
            ontology: string;
            environment?: string;
        }) => Promise<StreamStats[]>;
    };
    /**
     * Subject management
     */
    get subjects(): {
        get: (subjectId: string) => Promise<Subject>;
        listAssignments: (subjectId: string) => Promise<AssignmentListResponse>;
    };
    /**
     * @deprecated Use recordUser() instead
     */
    get users(): {
        create: (data: {
            id: string;
            name?: string;
            email?: string;
        }) => Promise<Subject>;
        get: (id: string) => Promise<Subject>;
    };
    private _resolveSandboxId;
    /**
     * Make an authenticated API request
     */
    private request;
}

export { type SemanticVersionDiff as $, type AccessTokenProvider as A, type BuildPolicy as B, type ConnectOptions as C, type DomainState as D, type EndpointMode as E, type VersionTag as F, Granular as G, type EnvironmentData as H, type InstanceToolHandler as I, type CreateEnvironmentData as J, type EnvironmentListResponse as K, type Manifest as L, type ManifestEffectMetamodelSpec as M, type ManifestListResponse as N, OntologyHandle as O, type Prompt as P, type BuildStatus as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, type User as U, type VersionTracking as V, WSClient as W, type Build as X, type Version as Y, type BuildListResponse as Z, type SemanticVersionDiffEntry as _, type EffectHandlerContext as a, type EnvironmentImporterImportOptions as a$, type ResolvedEffectPostCondition as a0, type ResolvedEffectDryRun as a1, type ResolvedEffectReverse as a2, type ResolvedEffectApprovalRequired as a3, type EffectInvocationMode as a4, type EffectInvocationMetadata as a5, type EffectSchema as a6, type EffectWithHandler as a7, type PublishEffectsResult as a8, type EffectVersionSelector as a9, type SessionJobListOptions as aA, type SessionCollectionListResult as aB, type WSDisconnectInfo as aC, type WSReconnectErrorInfo as aD, type WSClientOptions as aE, type RPCRequest as aF, type RPCResponse as aG, type SyncMessage as aH, type RPCRequestFromServer as aI, type ToolInvokeParams as aJ, type ToolResultParams as aK, type ModelRef as aL, type RelationshipInfo as aM, type DefineRelationshipOptions as aN, type RecordObjectOptions as aO, type RecordObjectResult as aP, type RecordObjectsChunkInfo as aQ, type RecordObjectsOptions as aR, type RecordImportStatus as aS, type RecordImportItemStatus as aT, type RecordImportStats as aU, type RecordImportItem as aV, type RecordImport as aW, type EnvironmentRecordImportSummary as aX, type EnvironmentSetupTriggerReason as aY, type EnvironmentSetupLifecycleStatus as aZ, type EnvironmentSetupSummary as a_, type ToolInfo as aa, type EffectInfo as ab, type ToolsChangedEvent as ac, type EffectsChangedEvent as ad, type EffectHandler as ae, type InstanceEffectHandler as af, type JobStatus as ag, type JobFeedbackSentiment as ah, type JobFeedbackToolCall as ai, type JobFeedbackMetadata as aj, type JobFeedbackInput as ak, type JobFeedbackRecord as al, type EnvironmentFeedbackRecord as am, type JobSubmitResult as an, type Job as ao, type ConversationMessageShowRefs as ap, type ConversationMessageInput as aq, type ConversationAppendResult as ar, type SessionConversationMessage as as, type SessionTimelineEvent as at, type SessionJobRecord as au, type SessionHeapFieldType as av, type SessionHeapFieldValue as aw, type SessionHeapVariable as ax, type SessionDocumentResult as ay, type SessionCollectionListOptions as az, type SessionHeapList as b, type EnvironmentImporter as b0, type ManifestPropertySpec as b1, type ManifestValidationOperator as b2, type ManifestEnumRuleSpec as b3, type ManifestFilterBySpec as b4, type ManifestValidationRuleSpec as b5, type ManifestStateMachineStateSpec as b6, type ManifestStateMachineTransitionSpec as b7, type ManifestStateMachineSpec as b8, type ManifestPostConditionSpec as b9, type ManifestDryRunSpec as ba, type ManifestReverseSpec as bb, type ManifestApprovalRequiredSpec as bc, type ManifestRelationshipDef as bd, type ManifestEffectSchema as be, type ManifestEffectDeclaration as bf, type ManifestEventTypeDef as bg, type ManifestEventStreamDef as bh, type ManifestOperation as bi, type ManifestImport as bj, type ManifestVolume as bk, type ManifestContent as bl, type GraphQLResult as bm, type APIError as bn, type DeleteResponse as bo, type StreamEvent as bp, type StreamSubscription as bq, type StreamStats as br, type SessionHeapSnapshot as c, type SessionTranscriptEntry as d, Environment as e, EnvironmentSession as f, Session as g, type ToolSchema as h, type PublishToolsResult as i, type ToolHandler as j, type GranularOptions as k, type GranularAuth as l, type RecordUserOptions as m, type Subject as n, type OpenEnvironmentOptions as o, type CreateSessionOptions as p, type ConversationSessionInfo as q, type Sandbox as r, type CreateSandboxData as s, type SandboxListResponse as t, type PermissionRules as u, type PermissionProfile as v, type CreatePermissionProfileData as w, type PermissionProfileListResponse as x, type Assignment as y, type AssignmentListResponse as z };
