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 connecting to an ontology environment
 */
interface ConnectOptions {
    /** The ontology name or ID to connect to */
    ontology: string;
    /** Named environment slot such as `dev` or `prod` */
    environment: string;
    /** Advanced override for the version tag/channel to follow. In the common case, omit this. */
    tagName?: string;
    /**
     * External user identifier from your app. This is the primary input for
     * connecting to a sandbox and the only required user field in the common case.
     */
    userId?: string;
    /**
     * Internal Granular user identifier. Optional fallback when you only know
     * the Granular-side ID for an existing subject.
     */
    granularId?: string;
    /** Optional display name used when upserting the user */
    name?: string;
    /** Optional email used when upserting the user */
    email?: string;
    /** Permission profile IDs or names to ensure before connecting */
    permissions?: string[];
    /** Backwards-compatible user object returned from recordUser() */
    user?: User;
    /** Optional stable client ID. Defaults to `client_${Date.now()}`. Use a fixed
     *  value for long-lived effect hosts so tool catalogs don't accumulate. */
    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;
    versionId: string;
    subjectId: string;
    envName: string;
    environment?: string;
    permissionProfileId: string;
    tagId?: string | null;
    tag?: VersionTag | null;
    tracking?: BuildPolicy;
    buildPolicy: BuildPolicy;
    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;
    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;
    /** 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;
/**
 * 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;
    /** 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;
}
/**
 * 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>;
}
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 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;
    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;
}
/**
 * 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 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;
    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 authors = await Author.list({ limit: 10, saveAs: 'recent_authors' });
     * const tolkien = await Author.get({ path: 'author_tolkien' });
     * const bio = await tolkien.get_bio({ detailed: true });
     * const books = await tolkien.get_books();
     * ```
     *
     * 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>;
    /**
     * 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;
}

/**
 * Environment represents a connected session to a sandbox for a specific user.
 *
 * After connecting, you can:
 * 1. Define your domain ontology via `applyManifest()` (classes, properties, relationships)
 * 2. Record object instances via `recordObject()` (with fields and relationship attachments)
 * 3. Register sandbox-scoped effects via `granular.registerEffect()` / `granular.registerEffects()`
 * 4. Submit jobs via `submitJob()` that import auto-generated typed classes from `./sandbox-tools`
 * 5. Execute GraphQL queries via `graphql()` (authenticated automatically)
 * 6. List available effects via `getEffects()` and listen for updates via `onEffectsChanged()`
 *
 * Tool calls from the sandbox automatically invoke your handlers via reverse-RPC.
 *
 * Object IDs are unique per class. Internally, the graph path is `{className}_{id}`
 * (e.g., `author_tolkien`). Use `Environment.toGraphPath()` and
 * `Environment.extractIdFromGraphPath()` for conversions.
 */
declare class Environment extends Session {
    private envData;
    private _apiKey;
    private _apiEndpoint;
    constructor(client: WSClient, envData: EnvironmentData, clientId: string, 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 GraphQL API endpoint URL */
    get apiEndpoint(): string;
    /**
     * Return a plain JS snapshot of the synced session heap.
     *
     * The heap lives in the Automerge document, so this method does not perform
     * any extra network roundtrip.
     */
    getHeap(): SessionHeapSnapshot;
    private getRuntimeBaseUrl;
    private controlPlaneRequest;
    /**
     * 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>;
    /** The last known graph container status, updated by checkReadiness() or on heartbeat */
    graphContainerStatus: {
        lastKeepAliveAt: number;
        status: 'warming' | 'hot' | 'unknown';
    } | null;
    /**
     * Check if the graph container is ready and warm.
     *
     * Sends a lightweight heartbeat RPC to the Session DO which internally
     * pings the FalkorDB container. The response includes `graphContainerStatus`,
     * which is stored locally and emitted as a `readiness` event.
     *
     * Use this method to proactively warm the graph container before any
     * GraphQL query that requires it, or to poll the container's state in
     * the background.
     *
     * @returns The current graph container status object
     *
     * @example
     * ```typescript
     * const status = await env.checkReadiness();
     * console.log(status.status); // 'hot' | 'warming' | 'unknown'
     *
     * // Or listen for live updates
     * env.on('readiness', (status) => {
     *   console.log('Graph is now:', status.status);
     * });
     * ```
     */
    checkReadiness(): Promise<{
        lastKeepAliveAt: number;
        status: 'warming' | 'hot' | 'unknown';
    }>;
    /**
     * 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;
    }): 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>;
    /**
     * Removed: environment-scoped effect publication is no longer supported.
     */
    publishTools(tools: ToolWithHandler[], revision?: string): Promise<PublishToolsResult>;
    /**
     * Removed: environment-scoped effect publication is no longer supported.
     */
    publishEffect(effect: ToolWithHandler): Promise<PublishToolsResult>;
    /**
     * Removed: environment-scoped effect publication is no longer supported.
     */
    publishEffects(effects: ToolWithHandler[]): Promise<PublishToolsResult>;
    /**
     * Removed: environment-scoped effect publication is no longer supported.
     */
    unpublishEffect(name: string): Promise<PublishToolsResult>;
    /**
     * Removed: environment-scoped effect publication is no longer supported.
     */
    unpublishAllEffects(): Promise<PublishToolsResult>;
}
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 → 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;
    /**
     * Create a new Granular client
     * @param options - Client configuration
     */
    constructor(options: GranularOptions);
    /**
     * 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>;
    private resolveConnectUser;
    /**
     * Connect to an ontology environment and establish a real-time session.
     *
     * Effects are registered at the sandbox level via `granular.registerEffect()`
     * or `granular.registerEffects()`. Sessions pick up live availability from
     * the sandbox registry automatically.
     *
     * @param options - Connection options
     * @returns An active environment session
     *
     * @example
     * ```typescript
     * const environment = await granular.connect({
     *   ontology: 'my-ontology',
     *   environment: 'dev',
     *   userId: 'user_123',
     *   permissions: ['agent'],
     * });
     *
     * await granular.registerEffect('my-sandbox', {
     *   name: 'greet',
     *   description: 'Say hello',
     *   inputSchema: { type: 'object', properties: {} },
     *   handler: async () => 'Hello!',
     * });
     *
     * // Submit job
     * const job = await environment.submitJob(`
     *   import { tools } from './sandbox-tools';
     *   return await tools.greet({});
     * `);
     *
     * console.log(await job.result); // 'Hello!'
     * ```
    */
    connect(options: ConnectOptions): Promise<Environment>;
    /**
     * 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?: ConnectOptions['initialHeap'];
    }): Promise<Environment>;
    /**
     * Connect to an existing open session (same conversation thread) using a freshly minted WebSocket token.
     */
    connectSession(options: {
        sessionId: string;
        clientId?: string;
    }): Promise<Environment>;
    /**
     * 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?: Environment | 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<Environment>;
    private bindWebSocketEnvironment;
    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 EffectInvocationMode as $, type AccessTokenProvider as A, type BuildPolicy as B, type ConnectOptions as C, type DomainState as D, type EffectHandlerContext as E, type Manifest as F, Granular as G, type ManifestListResponse as H, type InstanceToolHandler as I, type BuildStatus as J, type Build as K, type Version as L, type ManifestEffectMetamodelSpec as M, type BuildListResponse as N, type SemanticVersionDiffEntry as O, type Prompt as P, type SemanticVersionDiff 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 ResolvedEffectPostCondition as X, type ResolvedEffectDryRun as Y, type ResolvedEffectReverse as Z, type ResolvedEffectApprovalRequired as _, type SessionHeapList as a, type ManifestContent as a$, type EffectInvocationMetadata as a0, type EffectSchema as a1, type EffectWithHandler as a2, type PublishEffectsResult as a3, type ToolInfo as a4, type EffectInfo as a5, type ToolsChangedEvent as a6, type EffectsChangedEvent as a7, type EffectHandler as a8, type InstanceEffectHandler as a9, type RecordObjectsOptions as aA, type RecordImportStatus as aB, type RecordImportItemStatus as aC, type RecordImportStats as aD, type RecordImportItem as aE, type RecordImport as aF, type EnvironmentRecordImportSummary as aG, type ManifestPropertySpec as aH, type ManifestValidationOperator as aI, type ManifestEnumRuleSpec as aJ, type ManifestFilterBySpec as aK, type ManifestValidationRuleSpec as aL, type ManifestStateMachineStateSpec as aM, type ManifestStateMachineTransitionSpec as aN, type ManifestStateMachineSpec as aO, type ManifestPostConditionSpec as aP, type ManifestDryRunSpec as aQ, type ManifestReverseSpec as aR, type ManifestApprovalRequiredSpec as aS, type ManifestRelationshipDef as aT, type ManifestEffectSchema as aU, type ManifestEffectDeclaration as aV, type ManifestEventTypeDef as aW, type ManifestEventStreamDef as aX, type ManifestOperation as aY, type ManifestImport as aZ, type ManifestVolume as a_, type JobStatus as aa, type JobFeedbackSentiment as ab, type JobFeedbackToolCall as ac, type JobFeedbackMetadata as ad, type JobFeedbackInput as ae, type JobFeedbackRecord as af, type JobSubmitResult as ag, type Job as ah, type SessionHeapFieldType as ai, type SessionHeapFieldValue as aj, type SessionHeapVariable as ak, type WSDisconnectInfo as al, type WSReconnectErrorInfo as am, type WSClientOptions as an, type RPCRequest as ao, type RPCResponse as ap, type SyncMessage as aq, type RPCRequestFromServer as ar, type ToolInvokeParams as as, type ToolResultParams as at, type ModelRef as au, type RelationshipInfo as av, type DefineRelationshipOptions as aw, type RecordObjectOptions as ax, type RecordObjectResult as ay, type RecordObjectsChunkInfo as az, type SessionHeapSnapshot as b, type GraphQLResult as b0, type APIError as b1, type DeleteResponse as b2, type StreamEvent as b3, type StreamSubscription as b4, type StreamStats as b5, Environment as c, Session as d, type ToolSchema as e, type PublishToolsResult as f, type ToolHandler as g, type EndpointMode as h, type GranularOptions as i, type GranularAuth as j, type RecordUserOptions as k, type Subject as l, type ConversationSessionInfo as m, type Sandbox as n, type CreateSandboxData as o, type SandboxListResponse as p, type PermissionRules as q, type PermissionProfile as r, type CreatePermissionProfileData as s, type PermissionProfileListResponse as t, type Assignment as u, type AssignmentListResponse as v, type VersionTag as w, type EnvironmentData as x, type CreateEnvironmentData as y, type EnvironmentListResponse as z };
