import * as z from 'zod';
import { z as z$1 } from 'zod';
import * as _slopus_happy_wire from '@slopus/happy-wire';
import { OrgSetupTokenDocument, OrgDeviceEnrollmentTranscript, StructuredOutputMissingReason, MachineSetupTokenBindingV2, RpcBindingCapability, OrgRequirementsAgentState, SessionEnvelope, InputRef, InputEvidenceV1, HubInputAdmissionV1, ProviderUsageEventV1, CreateEnvelopeOptions, SessionTurnEndStatus, OwnershipCallerBindingSchema, TerminalOutFrame, TerminalInFrame, AutomationRunHeartbeatRequest, SessionFollowupEvaluationTerminalCode, AutomationConversationDeliverRequest, SessionExecutionCreateBody, HappySessionExecutionProof } from '@slopus/happy-wire';
import nacl from 'tweetnacl';
import { EventEmitter } from 'node:events';
import { Socket } from 'socket.io-client';
import { ChildProcess as ChildProcess$1 } from 'child_process';
import { KeyObject } from 'node:crypto';
import { ChildProcess } from 'node:child_process';
import { Options, CanUseTool, AgentDefinition, SettingSource, SandboxSettings } from '@anthropic-ai/claude-agent-sdk';
import { ExpoPushMessage } from 'expo-server-sdk';

type UsageRecoverySession = {
    sessionId: string;
    key: Uint8Array;
    variant: 'legacy' | 'dataKey';
};

type DeviceKeys = {
    signing: nacl.SignKeyPair;
    recipient: nacl.BoxKeyPair;
};

type DeviceOrgPin = {
    publicKey: string;
    approval: OrgSetupTokenDocument;
};
/** Initial pins are immutable. Rotation/revocation require separate authenticated transitions.
 * Only the enrollment coordinator calls pin after both confirmations. No trust in remote flags.
 * The one replacement (aplus#5876) is a new approval for another kind of PC under the same organization key: the
 * coordinator names the pin it replaces, and only that exact pin is replaced.
 */
declare function createDeviceOrgPinStore(deps: {
    home: string;
    machineId: string;
    keys: DeviceKeys;
}): {
    get: (companyId: string) => Promise<{
        version: 1;
        policy: "signed-required";
        publicKey: string;
        approval: {
            body: {
                deviceSigningPublicKey: string;
                recipientPublicKey: string;
                enrollmentDigest: string;
                machineId: string;
                machineType: "dedicated" | "shared";
                ownerUserId: string | null;
                kind: "device-approval";
                approvalId: string;
                approvalRevision: number;
                version: 1;
                companyId: string;
                signingGeneration: number;
                signingKeyId: string;
                issuedAt: number;
            } | {
                kind: "ai-assignment";
                bindingId: string;
                assignmentRevision: number;
                credentialGroupId: string;
                credentialGroupRevision: number;
                target: {
                    kind: "user-group" | "machine";
                    id: string;
                };
                accounts: {
                    managedAccountId: string;
                    credentialGeneration: number;
                    credentialDigest: string;
                }[];
                version: 1;
                companyId: string;
                signingGeneration: number;
                signingKeyId: string;
                issuedAt: number;
            } | {
                kind: "device-revocation";
                approvalId: string;
                approvalRevision: number;
                machineId: string;
                recipientKeyId: string;
                version: 1;
                companyId: string;
                signingGeneration: number;
                signingKeyId: string;
                issuedAt: number;
            } | {
                kind: "org-signing-rotation";
                nextGeneration: number;
                nextPublicKey: string;
                nextKeyId: string;
                version: 1;
                companyId: string;
                signingGeneration: number;
                signingKeyId: string;
                issuedAt: number;
            } | {
                kind: "company-data-key-generation";
                generation: number;
                dataPublicKey: string;
                version: 1;
                companyId: string;
                signingGeneration: number;
                signingKeyId: string;
                issuedAt: number;
            };
            signature: string;
        };
    } | null>;
    pin(candidate: DeviceOrgPin, replaces?: DeviceOrgPin): Promise<void>;
};

declare const requestSchema: z$1.ZodObject<{
    companyId: z$1.ZodString;
    machineType: z$1.ZodEnum<{
        dedicated: "dedicated";
        shared: "shared";
    }>;
    ownerUserId: z$1.ZodNullable<z$1.ZodString>;
    orgSigningPublicKey: z$1.ZodString;
    signingGeneration: z$1.ZodNumber;
}, z$1.core.$strict>;
declare const confirmationSchema: z$1.ZodObject<{
    companyId: z$1.ZodString;
    machineId: z$1.ZodString;
    enrollmentDigest: z$1.ZodString;
}, z$1.core.$strict>;
type Approval = OrgSetupTokenDocument & {
    body: Extract<OrgSetupTokenDocument['body'], {
        kind: 'device-approval';
    }>;
};
type Pinned = NonNullable<Awaited<ReturnType<ReturnType<typeof createDeviceOrgPinStore>['get']>>>;
type Pending = {
    approval: Approval | null;
    readyToPin: boolean;
    pinned: boolean;
    transcript: OrgDeviceEnrollmentTranscript;
    digest: string;
    proof: string;
    locallyConfirmed: boolean;
    replaces?: Pinned;
};
/** Pending comparisons are ephemeral. Neither confirmation alone grants persistent trust.
 * Restarting the daemon loses the pending comparison; persisted pins are owned by the approval store.
 */
/** aplus specs/shared-machine-server-signing S6 (contract §20.5) — stands in for the local confirmation of a shared PC's
 * approval: true only when this PC is marked shared and the approval's key is the one its trusted Studio origin serves. */
type DeviceAutoConfirm = (input: {
    transcript: OrgDeviceEnrollmentTranscript;
    approval: Approval;
}) => Promise<boolean>;
type MachineTypeMarkerStore = {
    read(): Promise<'shared' | 'dedicated' | null>;
    record(type: 'shared' | 'dedicated'): Promise<'recorded' | 'exists'>;
};
declare const useAsSharedSchema: z$1.ZodObject<{
    companyId: z$1.ZodString;
    machineId: z$1.ZodString;
}, z$1.core.$strict>;
declare function createDeviceEnrollment(deps: {
    machineId: string;
    keys: DeviceKeys;
    now?: () => number;
    store?: ReturnType<typeof createDeviceOrgPinStore>;
    autoConfirm?: DeviceAutoConfirm;
    marker?: MachineTypeMarkerStore;
}): {
    machineId: string;
    /** Advertised as autoOrgPinVersion: Studio approves a shared PC without an administrator only if it confirms itself. */
    autoConfirms: boolean;
    begin(input: z$1.input<typeof requestSchema>): Promise<Pending>;
    approve(json: string): Promise<void>;
    /**
     * aplus specs/shared-machine-server-signing S6b·S6c — records this PC as shared and, if a server-signed shared
     * approval is waiting, confirms it automatically. 'local' is the PC's own loopback request and needs such an
     * approval; 'remote' is an administrator's customer-key request. Never rewrites an existing marker.
     */
    useAsShared(input: z$1.input<typeof useAsSharedSchema>, origin: "local" | "remote"): Promise<{
        accepted: true;
        confirmed: boolean;
        declined: boolean;
    }>;
    /** What the PC shows before asking its user to use it as the organization's shared PC. */
    sharedStatus(companyId: string): Promise<{
        machineType: "dedicated" | "shared" | null;
        awaitingSharedConfirmation: boolean;
    }>;
    /** The locally confirmed organization pin, which signed setup-token delivery trusts. */
    orgPin(companyId: string): Promise<{
        version: 1;
        policy: "signed-required";
        publicKey: string;
        approval: {
            body: {
                deviceSigningPublicKey: string;
                recipientPublicKey: string;
                enrollmentDigest: string;
                machineId: string;
                machineType: "dedicated" | "shared";
                ownerUserId: string | null;
                kind: "device-approval";
                approvalId: string;
                approvalRevision: number;
                version: 1;
                companyId: string;
                signingGeneration: number;
                signingKeyId: string;
                issuedAt: number;
            } | {
                kind: "ai-assignment";
                bindingId: string;
                assignmentRevision: number;
                credentialGroupId: string;
                credentialGroupRevision: number;
                target: {
                    kind: "user-group" | "machine";
                    id: string;
                };
                accounts: {
                    managedAccountId: string;
                    credentialGeneration: number;
                    credentialDigest: string;
                }[];
                version: 1;
                companyId: string;
                signingGeneration: number;
                signingKeyId: string;
                issuedAt: number;
            } | {
                kind: "device-revocation";
                approvalId: string;
                approvalRevision: number;
                machineId: string;
                recipientKeyId: string;
                version: 1;
                companyId: string;
                signingGeneration: number;
                signingKeyId: string;
                issuedAt: number;
            } | {
                kind: "org-signing-rotation";
                nextGeneration: number;
                nextPublicKey: string;
                nextKeyId: string;
                version: 1;
                companyId: string;
                signingGeneration: number;
                signingKeyId: string;
                issuedAt: number;
            } | {
                kind: "company-data-key-generation";
                generation: number;
                dataPublicKey: string;
                version: 1;
                companyId: string;
                signingGeneration: number;
                signingKeyId: string;
                issuedAt: number;
            };
            signature: string;
        };
    } | null>;
    getStatus(companyId: string): Promise<{
        companyId: string;
        machineId: string;
        deviceSigningPublicKey: string;
        recipientPublicKey: string;
        enrollment: {
            digest: string;
            expiresAt: number;
            orgSigningPublicKey: string;
            signingGeneration: number;
            locallyConfirmed: boolean;
            administratorApproved: boolean;
        } | null;
        pin: {
            publicKey: string;
            policy: "signed-required";
            signingGeneration: number;
            keyId: string;
            approvalId: string;
        } | null;
    }>;
    status(): Pending | null;
    confirm(input: z$1.input<typeof confirmationSchema>): Promise<void> | void;
};

/**
 * Where the child sits relative to the caller's session.
 *
 *  - `session` (default): the child starts or hosts sessions of its own, or
 *    belongs to none — the daemon and what it spawns, the channel host, a
 *    detached `happy` command, a terminal, a script. Every entry is dropped.
 *  - `in-session`: the child works inside the caller's session — the agent CLI
 *    a runner launches and the shells it runs. Only lineage and spawn seeds
 *    are dropped; the session's own scope stays.
 */
type ChildEnvBoundary = 'session' | 'in-session';
/**
 * Secret-free record of which managed setup-token generation a session was started on.
 * Daemon-written only: the HAPPY_AI_AUTH_ prefix is scrubbed from inherited and
 * requested environments, so neither can forge or carry it to another session.
 */
declare const SETUP_TOKEN_BINDING_ENV = "HAPPY_AI_AUTH_SETUP_TOKEN_BINDING";
/**
 * Secret-free record of which organization LLM endpoint target a session was started on
 * (aplus specs/org-llm-endpoints C5): `<bindingId>:<endpointId>:<targetId>:<generation>`.
 * Daemon-written only, scrubbed like the setup-token binding.
 */
declare const ORG_ENDPOINT_BINDING_ENV = "HAPPY_AI_AUTH_ORG_ENDPOINT_BINDING";
/** The personal relay binding is session-scoped, like the organization endpoint binding. */
declare const PERSONAL_ENDPOINT_BINDING_ENV = "HAPPY_AI_AUTH_PERSONAL_ENDPOINT_BINDING";
declare const ORG_SUBAGENT_LAUNCH_ENV = "HAPPY_ORG_LLM_SUBAGENT_LAUNCH_ID";
declare const ORG_SUBAGENT_OPERATION_ENV = "HAPPY_ORG_LLM_SUBAGENT_OPERATION_ID";
/**
 * `'1'` while the daemon's session-started report for an endpoint session has not reached Studio (r3). Kept in the
 * session's persisted record so a lost report is sent again before a resume; daemon-written only, scrubbed like the binding.
 */
declare const ORG_ENDPOINT_UNREPORTED_ENV = "HAPPY_AI_AUTH_ORG_ENDPOINT_UNREPORTED";

declare const PERSONAL_ENDPOINT_LEASE_ENV = "HAPPY_AI_AUTH_PERSONAL_ENDPOINT_LEASE";

type PersonalEndpointSelection = {
    kind: 'personal-endpoint';
    issuer: string;
    ownerUserId: string;
    endpointId: string;
    generation: number;
    ticket: string;
};
type PersonalEndpointMarker = {
    endpointId: string;
    generation: number;
    ownerUserId: string;
    issuer: string;
    machineId: string;
    name: string;
    model: string;
    workspace: Record<string, string>;
};

/**
 * Common RPC types and interfaces for both session and machine clients
 */
/**
 * Generic RPC handler function type
 * @template TRequest - The request data type
 * @template TResponse - The response data type
 */
type RpcHandler<TRequest = any, TResponse = any> = (data: TRequest, 
/** Passed only on the delegation lane; customer and server lane calls keep their one argument. */
context?: RpcCallContext) => TResponse | Promise<TResponse>;
interface RpcCallContext {
    lane: 'delegation';
    /** The machine whose link key opened the request. */
    peer: string;
}
/**
 * RPC request data from server
 */
interface RpcRequest {
    method: string;
    params: string;
    rpcLatency?: unknown;
}
/**
 * Configuration for RPC handler manager
 */
interface RpcHandlerConfig {
    scopePrefix: string;
    encryptionKey: Uint8Array;
    encryptionVariant: 'legacy' | 'dataKey';
    logger?: (message: string, data?: any) => void;
    /**
     * aplus-dev-studio specs/e2ee-machine-control-boundary R2/R3 — a second
     * key (AES-256-GCM) the server holds instead of the machine key. Requests
     * it opens run only methods `allows` accepts, and are answered with it.
     */
    serverLane?: ServerLaneConfig;
    /**
     * aplus-dev-studio specs/cross-machine-agent-delegation — keys (AES-256-GCM) another machine
     * holds because a person linked it to this one. Tried after the scope and server keys; requests
     * they open must be bound, run only methods `allows` accepts, and are answered with that key.
     */
    delegationLane?: DelegationLaneConfig;
    /**
     * aplus-dev-studio specs/e2ee-machine-control-boundary R19 — strict machine
     * control: a customer-lane request must be bound (R18). An unbound one is
     * refused before any handler runs.
     */
    requireBoundRequests?: boolean;
    /**
     * How many bound requests one scope remembers within the time window (default 10,000).
     * When full, strict refuses new ones and compat forgets its oldest.
     */
    maxBoundRequestsInWindow?: number;
}
interface ServerLaneConfig {
    encryptionKey: Uint8Array;
    /** Receives the method name without the scope prefix. */
    allows: (method: string) => boolean;
}
interface DelegationLink {
    /** The machine allowed to send through this key. */
    peer: string;
    key: Uint8Array;
}
interface DelegationLaneConfig {
    links: () => readonly DelegationLink[];
    /** Receives the method name without the scope prefix. */
    allows: (method: string) => boolean;
    /** A refusal for one call by its params, decided before the handler runs; null admits it. */
    admit?: (method: string, params: unknown, peer: string) => {
        error: string;
        code: string;
    } | null;
}

/**
 * Simplified schema that only validates fields actually used in the codebase
 * while preserving all other fields through passthrough()
 */

declare const UsageSchema: z$1.ZodObject<{
    input_tokens: z$1.ZodNumber;
    cache_creation_input_tokens: z$1.ZodOptional<z$1.ZodNumber>;
    cache_read_input_tokens: z$1.ZodOptional<z$1.ZodNumber>;
    output_tokens: z$1.ZodNumber;
    service_tier: z$1.ZodOptional<z$1.ZodString>;
}, z$1.core.$loose>;
declare const RawJSONLinesSchema: z$1.ZodDiscriminatedUnion<[z$1.ZodObject<{
    type: z$1.ZodLiteral<"user">;
    isSidechain: z$1.ZodOptional<z$1.ZodBoolean>;
    isMeta: z$1.ZodOptional<z$1.ZodBoolean>;
    uuid: z$1.ZodString;
    message: z$1.ZodObject<{
        content: z$1.ZodUnion<readonly [z$1.ZodString, z$1.ZodAny]>;
    }, z$1.core.$loose>;
}, z$1.core.$loose>, z$1.ZodObject<{
    uuid: z$1.ZodString;
    type: z$1.ZodLiteral<"assistant">;
    message: z$1.ZodOptional<z$1.ZodObject<{
        usage: z$1.ZodOptional<z$1.ZodObject<{
            input_tokens: z$1.ZodNumber;
            cache_creation_input_tokens: z$1.ZodOptional<z$1.ZodNumber>;
            cache_read_input_tokens: z$1.ZodOptional<z$1.ZodNumber>;
            output_tokens: z$1.ZodNumber;
            service_tier: z$1.ZodOptional<z$1.ZodString>;
        }, z$1.core.$loose>>;
        model: z$1.ZodOptional<z$1.ZodString>;
    }, z$1.core.$loose>>;
}, z$1.core.$loose>, z$1.ZodObject<{
    type: z$1.ZodLiteral<"summary">;
    summary: z$1.ZodString;
    leafUuid: z$1.ZodString;
}, z$1.core.$loose>, z$1.ZodObject<{
    type: z$1.ZodLiteral<"system">;
    uuid: z$1.ZodString;
}, z$1.core.$loose>], "type">;
type RawJSONLines = z$1.infer<typeof RawJSONLinesSchema>;

declare const SETUP_TOKEN_BINDING_TYPE = "claude-setup-token-binding-v1";
type SetupTokenBindingClaims = {
    v: 1;
    type: typeof SETUP_TOKEN_BINDING_TYPE;
    aud: string;
    keyId: string;
    companyId: string;
    groupScope: string;
    userId: string;
    machineId: string;
    managedAccountId: string;
    credentialGeneration: number;
    nonce: string;
    issuedAt: number;
    expiresAt: number;
    tokenProof?: string;
};
/** Verifier bound to this daemon's trusted origin and machine. Replay is the caller's (durable) concern. */
declare function createSetupTokenBindingVerifier(config: {
    origin: string;
    machineId: string;
    now?: () => number;
    fetch?: typeof fetch;
}): {
    available(): Promise<boolean>;
    verify(envelope: string): Promise<SetupTokenBindingClaims | null>;
};
type SetupTokenBindingVerifier = ReturnType<typeof createSetupTokenBindingVerifier>;

declare const MANUAL_PERSONAL_ENV = "HAPPY_AI_AUTH_MANUAL_PERSONAL";
declare const manualPersonalSelectionSchema: z$1.ZodObject<{
    version: z$1.ZodLiteral<1>;
    accountRef: z$1.ZodString;
    nonce: z$1.ZodString;
    launchId: z$1.ZodString;
    consentProof: z$1.ZodString;
}, z$1.core.$strict>;
type ManualPersonalSelection = z$1.infer<typeof manualPersonalSelectionSchema>;

/** The closed set the ledger understands. Anything else is `unknown`. */
declare const AI_AUTH_SOURCES: readonly ["personal-subscription", "personal-api-key", "org-bundle", "platform-glm", "platform-gateway", "platform-plan", "org-endpoint", "personal-endpoint", "unknown"];
type AiAuthSource = (typeof AI_AUTH_SOURCES)[number];

declare const ADDITIONAL_DIRECTORIES_ENV = "HAPPY_ADDITIONAL_DIRECTORIES";
declare const APPROVED_WRITE_ROOTS_ENV = "HAPPY_APPROVED_WRITE_ROOTS";

declare const OUTPUT_FORMAT_ENV = "HAPPY_INITIAL_OUTPUT_FORMAT";
type ClaudeOutputFormat = {
    type: 'json_schema';
    schema: Record<string, unknown>;
};
type StructuredOutputEnvelope = {
    v: 1;
    status: 'ok';
    value: unknown;
} | {
    v: 1;
    status: 'missing';
    reason: StructuredOutputMissingReason;
};

/** One session's launch option; never a daemon-wide inherited preference. */
declare const INPUT_EVIDENCE_ENV = "HAPPY_INPUT_EVIDENCE";

declare const SAYCODE_AGENT_ENV_KEYS: readonly ["SAYCODE_AGENT_ENV", "SAYCODE_AGENT_ROOT", "SAYCODE_AGENT_SCOPE", "SAYCODE_AGENT_DEPTH", "SAYCODE_AGENT_MAX_SPAWN", "SAYCODE_AGENT_ID", "SAYCODE_AGENT_DELEGATED_FROM"];
type SaycodeAgentEnvironmentKey = typeof SAYCODE_AGENT_ENV_KEYS[number];
/** Daemon-written provenance/rejection state, never admitted from a request or inherited by another session. */
declare const DAEMON_AGENT_GRANT_STATE_ENV = "HAPPY_DAEMON_AGENT_GRANT_STATE";
declare const CHECKPOINT_CONTEXT_KEY = "HAPPY_CHECKPOINT_SPAWN_CONTEXT";
/** Set from the spawn option `browserContinuation` only (request environment cannot carry HAPPY_AUTOMATION_*). */
declare const BROWSER_CONTINUATION_ENV = "HAPPY_AUTOMATION_BROWSER_CONTINUATION";
/**
 * aplus specs/org-agent-plan §6.3-4 — a plan session's spawn seeds, kept with the session so every resume
 * re-applies the same descriptor and grant (the server accepts the same session id again). They stay spawn
 * seeds in the child: the runner reads and deletes them and `HAPPY_INITIAL_` never reaches Codex. The record
 * lives in owner-only sessions.json beside the session's data key.
 */
declare const AGENT_PLAN_SEED_KEYS: readonly ["HAPPY_INITIAL_AGENT_PLAN_DESCRIPTOR", "HAPPY_INITIAL_AGENT_PLAN_SECRET", "HAPPY_INITIAL_AGENT_PLAN_THREADS_DIR"];
type AgentPlanSeedKey = typeof AGENT_PLAN_SEED_KEYS[number];
type SessionScopedEnvironmentKey = SaycodeAgentEnvironmentKey | typeof OUTPUT_FORMAT_ENV | typeof CHECKPOINT_CONTEXT_KEY | typeof SETUP_TOKEN_BINDING_ENV | typeof ORG_ENDPOINT_BINDING_ENV | typeof PERSONAL_ENDPOINT_BINDING_ENV | typeof PERSONAL_ENDPOINT_LEASE_ENV | typeof ORG_ENDPOINT_UNREPORTED_ENV | typeof ORG_SUBAGENT_LAUNCH_ENV | typeof ORG_SUBAGENT_OPERATION_ENV | 'HAPPY_WRITE_SCOPE_SESSION' | 'HAPPY_SANDBOX_POLICY_MODE' | 'HAPPY_PROJECT_SANDBOX_CONFIG' | typeof ADDITIONAL_DIRECTORIES_ENV | typeof APPROVED_WRITE_ROOTS_ENV | typeof BROWSER_CONTINUATION_ENV | typeof INPUT_EVIDENCE_ENV | typeof MANUAL_PERSONAL_ENV | AgentPlanSeedKey;
type SaycodeAgentEnvironment = Partial<Record<SessionScopedEnvironmentKey | typeof DAEMON_AGENT_GRANT_STATE_ENV, string>>;
/**
 * The immutable, signed facts a bound session keeps: who the server said may bind
 * which managed account at which generation. No token and no grant envelope.
 */
type UserSetupTokenBinding = {
    principalType?: 'user';
    managedAccountId: string;
    credentialGeneration: number;
    groupScope: string;
    companyId: string;
    userId: string;
    machineId: string;
    keyId: string;
    nonce: string;
    issuedAt: number;
    tokenProof?: string;
};
declare const executionSchema: z$1.ZodObject<{
    sessionId: z$1.ZodString;
    initialNonce: z$1.ZodString;
    issueOperationId: z$1.ZodString;
    sessionOwnerAccountId: z$1.ZodString;
    machineOwnerAccountId: z$1.ZodString;
}, z$1.core.$strict>;
type MachineSetupTokenBindingRecord = MachineSetupTokenBindingV2 & {
    execution: z$1.infer<typeof executionSchema>;
};
type SetupTokenBinding = UserSetupTokenBinding | MachineSetupTokenBindingRecord;
/**
 * `claude-setup-token` pins one new Claude session to an organisation-managed
 * setup-token slot. Older daemons reject the kind, so a client gates it on
 * `ai-credential:capabilities.newSessionProfileBinding`.
 */
type AiAuthSelection = {
    kind: 'machine-personal' | 'org-bundle';
}
/** `bindingGrant` is required on a new spawn; a resume rebuilds the selection from the recorded binding. */
 | {
    kind: 'claude-setup-token';
    managedAccountId: string;
    groupScope: string;
    credentialGeneration: number;
    bindingGrant?: string;
    credentialProofVersion?: 1;
    personalSelection?: ManualPersonalSelection;
}
/**
 * An organization LLM endpoint (aplus specs/org-llm-endpoints C5): the daemon tries `candidates` (target ids,
 * the server's order) against its locally stored entry. `resume` is daemon-internal — set only when a resume
 * rebuilds the recorded target — and never read from a request.
 */
 | PersonalEndpointSelection | {
    kind: 'org-endpoint';
    bindingId: string;
    endpointId: string;
    generation: number;
    candidates: string[];
    snapshotId?: string;
    resume?: true;
};

/**
 * Minimal persistence functions for happy CLI
 *
 * Handles settings and private key storage in ~/.happy/ or local .happy/
 */

declare const SandboxConfigSchema: z.ZodObject<{
    enabled: z.ZodDefault<z.ZodBoolean>;
    workspaceRoot: z.ZodOptional<z.ZodString>;
    sessionIsolation: z.ZodDefault<z.ZodEnum<{
        custom: "custom";
        strict: "strict";
        workspace: "workspace";
    }>>;
    customWritePaths: z.ZodDefault<z.ZodArray<z.ZodString>>;
    denyReadPaths: z.ZodDefault<z.ZodArray<z.ZodString>>;
    extraWritePaths: z.ZodDefault<z.ZodArray<z.ZodString>>;
    denyWritePaths: z.ZodDefault<z.ZodArray<z.ZodString>>;
    allowGitConfig: z.ZodOptional<z.ZodBoolean>;
    networkMode: z.ZodDefault<z.ZodEnum<{
        custom: "custom";
        blocked: "blocked";
        allowed: "allowed";
    }>>;
    allowedDomains: z.ZodDefault<z.ZodArray<z.ZodString>>;
    deniedDomains: z.ZodDefault<z.ZodArray<z.ZodString>>;
    allowLocalBinding: z.ZodDefault<z.ZodBoolean>;
    checkpointProtection: z.ZodOptional<z.ZodObject<{
        secretPatterns: z.ZodArray<z.ZodString>;
        maxFileBytes: z.ZodNumber;
        maxFiles: z.ZodNumber;
        maxTotalBytes: z.ZodNumber;
        readOnlyPassthroughPaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
    }, z.core.$strict>>;
}, z.core.$strip>;
type SandboxConfig = z.infer<typeof SandboxConfigSchema>;
type Credentials = {
    token: string;
    encryption: {
        type: 'legacy';
        secret: Uint8Array;
        /**
         * aplus §6-1 Phase 3b — legacy 활성 상태에서 병기된 dataKey 재료.
         * RPC 는 여전히 secret(legacy)로 동작하고, 이 재료는 머신 등록 시
         * wrap 된 dataEncryptionKey 를 서버에 올리는 데만 쓰인다. 컷오버
         * (secret 제거 → dataKey 활성)는 별도 phase 의 몫이다.
         */
        provisioned?: {
            publicKey: Uint8Array;
            machineKey: Uint8Array;
        };
    } | {
        type: 'dataKey';
        publicKey: Uint8Array;
        machineKey: Uint8Array;
        /**
         * aplus-dev-studio specs/e2ee-machine-control-boundary R4 — set only on a
         * key generated under strict machine control, which the server has never
         * been sent. Absent means the server may hold a copy.
         */
        neverEscrowed?: true;
    };
};

/**
 * Who started a session — written once into session metadata as `source` so every
 * client can tell automation-run conversations apart without device-local guesses
 * (aplus-dev-studio specs/session-source-metadata).
 *
 * An open string enum: a newer client may send a value this build does not list,
 * and it is still recorded. Readers treat an unknown value as "not known", never
 * as `user`.
 */
type SessionSource = 'user' | 'schedule' | 'autopilot' | 'github-trigger' | 'review' | 'channel' | 'fanout' | (string & {});

/**
 * Tool policy rule sources (aplus-dev-studio specs/agent-tool-policy R2, R3, R10, R14).
 *
 * - `builtin`: the data file `tables.v1.json` (app categories, cua-driver action table, system key
 *   combos, MCP verb dictionaries). Shipped in the package so Desktop's managed-extension broker can
 *   read the same table (plan.md "결정: 집행 위치" — one copy, never two).
 * - `machine`: `<HAPPY_HOME_DIR>/tool-policy.json`, written by Desktop and re-read when its mtime
 *   changes (at most every 2 seconds). It is a user-writable file, so it can only add `machine`
 *   rules — it can never lift a builtin `blocked` or `floor` (that is decided in evaluate.ts).
 *
 * A malformed rule or an unreadable file degrades to `ask`, never to `blocked` (R3): one typo in a
 * hand-edited file must not stop every tool, and must not silently open one either.
 */
type ToolPolicyDecision = 'allow' | 'ask' | 'blocked';
type AppCategory = 'browser' | 'terminal' | 'shell' | 'trading' | 'media' | 'self' | 'other';
type CuaAction = 'observe' | 'pointer' | 'pointer_full' | 'keyboard' | 'app_control' | 'clipboard_read' | 'clipboard_write';

/**
 * Pure tool-call decision (aplus-dev-studio specs/agent-tool-policy R1–R8, R12, R13).
 *
 * Input: the tool name, its arguments, the already-resolved target app (cua-driver only), the
 * machine rules and a view of the conversation's grants. Output: `allow | ask | blocked` with the
 * reason, the rule, the table version and — for `blocked` — the three-part message the model sees.
 * No I/O here: the gate (policyGate.ts) resolves targets, holds grants and asks people.
 *
 * Combination order (R2): fixed builtin blocks → machine rules (most restrictive wins, a builtin
 * `floor` turns their `allow` into `ask`) → builtin defaults → organization rules, as the strictest of
 * the two (aplus-dev-studio-desktop specs/codexcli-org-requirements R1, Q10 — they only ever tighten, so
 * an organization `ask` cannot turn a builtin `blocked` into a prompt) → a session grant turns `ask`
 * into `allow` (never `blocked`). An organization `ask` is human-only, and a grant answers it only when
 * it was made at or after the rule's `since` (R1a).
 *
 * The machine file is user-writable, so it is never trusted to open anything on its own (spec 제약
 * "보안"): past an app's grade it can at most turn the builtin `blocked` into a person's `ask`.
 */

interface PolicyTarget {
    category: AppCategory;
    appName: string;
    bundleIdOrExe: string;
}

/**
 * Tool policy audit (aplus-dev-studio specs/agent-tool-policy R9, R16).
 *
 * Every `ask`/`blocked`, and `allow` only where it matters (cua-driver actions other than
 * observing, and write tools), is appended to `<HAPPY_HOME_DIR>/logs/tool-policy.jsonl` — owner-only,
 * rotated at 5 MB, three files kept. `ask`/`blocked` are also kept as the 50 most recent records
 * for agentState `toolPolicy.recent`, which Desktop reads loosely (no new session event type: the
 * happy-wire session protocol is a strict union old clients cannot parse).
 *
 * R9 coverage gaps (`unlisted_tool`, `unlisted_write_tool`) go to the file only: they name tools a
 * server listed, not calls anyone made, so they are not shown as blocked calls.
 *
 * Never recorded: window titles, typed text, coordinates or any argument value.
 */

/** `terminal_prompt`: handed to Claude's own terminal prompt, whose answer the daemon never sees. */
type ToolPolicyOutcome = 'approved' | 'denied' | 'timeout' | 'aborted' | 'unattended' | 'terminal_prompt';
interface ToolPolicyAuditRecord {
    at: number;
    tool: string;
    server: 'cua-driver' | 'user';
    action?: string;
    targetCategory?: string;
    targetId?: string;
    decision: ToolPolicyDecision;
    reasonCode: string;
    ruleId: string;
    policyVersion: string;
    outcome?: ToolPolicyOutcome;
}

/**
 * One session's tool policy enforcement point (aplus-dev-studio specs/agent-tool-policy R3, R11, R13, R16).
 *
 * Adapters (the Claude PreToolUse hook, the cua-driver shadow proxy and the stdio bridge) hand a
 * pending call to `decide`. It resolves the target app, evaluates the call against the
 * current rules, and for `ask` raises an ordinary permission request through the session's
 * approver and waits — up to 30 minutes — for a person. Grants are created only from that answer.
 *
 * Failure direction: an evaluation error is `ask`; `ask` with nobody to ask is `blocked`. In local
 * (terminal) mode the person is at Claude's own prompt, so `ask` goes there instead (`terminalPrompt`;
 * measured 2026-10-22: a hook "ask" makes the Claude 2.1.285 TUI ask even under bypassPermissions,
 * and a persistent "don't ask again" rule does not skip it). That answer never reaches the daemon,
 * so it creates no grant and no R13 denial memory.
 */

/** Rides on `agentState.requests[id].policy` (R11). Clients that do not know it show a plain prompt. */
interface PermissionPolicyMeta {
    reasonCode: string;
    ruleId: string;
    humanOnly: boolean;
    target?: PolicyTarget;
    action?: CuaAction | 'session_meta';
    grantOffer: 'once' | 'session';
}

/**
 * How a permission request stopped being answerable (aplus-dev-studio
 * specs/codexcli-approval-session-binding plan §3.2·§3.4).
 *
 * Every path a request leaves by — answered, stopped, a turn or generation ending, a reset,
 * shutdown, the next process starting, or an unattended wait running out — writes one of these
 * into `completedRequests[id].resolution`. Clients read it to close the card on every screen and
 * to tell a late answer what happened; it never says who answered or what they chose.
 *
 * `auto-approved` marks a call the runtime approved itself (Codex `codex_apps`·`change_title`,
 * Gemini's always-allowed tools and yolo modes): it never waited, so clients skip it rather than
 * guess it from the record's shape (aplus-dev-studio I6k). Claude's own allow paths write no record.
 */
type PermissionResolution = 'answered' | 'aborted' | 'generation-ended' | 'turn-ended' | 'expired' | 'reset' | 'shutdown' | 'runtime-restart' | 'auto-approved';

type SetupTokenRotationState = 'switching' | 'switched' | 'exhausted' | 'apply-required' | 'forbidden' | 'unsupported' | 'retrying' | 'retry-expired' | 'failed' | 'resume-rebound';

/**
 * Permission mode type - includes both Claude and Codex modes
 * Must match MessageMetaSchema.permissionMode enum values
 *
 * Claude modes: default, acceptEdits, bypassPermissions, plan
 * Codex modes: read-only, safe-yolo, yolo
 *
 * When calling Claude SDK, Codex modes are mapped at the SDK boundary:
 * - yolo → bypassPermissions
 * - safe-yolo → default
 * - read-only → default
 */
type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'read-only' | 'safe-yolo' | 'yolo';
/**
 * Usage data type from Claude
 */
type Usage = z$1.infer<typeof UsageSchema>;
/**
 * Session information
 */
type Session = {
    id: string;
    seq: number;
    encryptionKey: Uint8Array;
    encryptionVariant: 'legacy' | 'dataKey';
    metadata: Metadata;
    metadataVersion: number;
    agentState: AgentState | null;
    agentStateVersion: number;
};
/**
 * Machine metadata - static information (rarely changes)
 */
declare const MachineMetadataSchema: z$1.ZodObject<{
    host: z$1.ZodString;
    platform: z$1.ZodString;
    happyCliVersion: z$1.ZodString;
    homeDir: z$1.ZodString;
    happyHomeDir: z$1.ZodString;
    happyLibDir: z$1.ZodString;
    cliAvailability: z$1.ZodOptional<z$1.ZodObject<{
        claude: z$1.ZodBoolean;
        codex: z$1.ZodBoolean;
        gemini: z$1.ZodBoolean;
        openclaw: z$1.ZodBoolean;
        detectedAt: z$1.ZodNumber;
    }, z$1.core.$strip>>;
    resumeSupport: z$1.ZodOptional<z$1.ZodObject<{
        rpcAvailable: z$1.ZodBoolean;
        requiresSameMachine: z$1.ZodBoolean;
        requiresHappyAgentAuth: z$1.ZodBoolean;
        happyAgentAuthenticated: z$1.ZodBoolean;
        detectedAt: z$1.ZodNumber;
    }, z$1.core.$strip>>;
    automationSupport: z$1.ZodOptional<z$1.ZodObject<{
        rpcAvailable: z$1.ZodBoolean;
        serverBacked: z$1.ZodOptional<z$1.ZodBoolean>;
        keyVersion: z$1.ZodOptional<z$1.ZodNumber>;
        sessionFollowup: z$1.ZodOptional<z$1.ZodLiteral<true>>;
        conversation: z$1.ZodOptional<z$1.ZodLiteral<true>>;
        protocolVersion: z$1.ZodOptional<z$1.ZodNumber>;
        contextIsolationVersion: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodLiteral<0>, z$1.ZodLiteral<1>]>>;
        hostCommands: z$1.ZodOptional<z$1.ZodBoolean>;
        scheduleKinds: z$1.ZodOptional<z$1.ZodArray<z$1.ZodString>>;
        delivery: z$1.ZodOptional<z$1.ZodLiteral<1>>;
        missedRunPolicy: z$1.ZodOptional<z$1.ZodLiteral<1>>;
        authenticatedEnvelopes: z$1.ZodOptional<z$1.ZodObject<{
            version: z$1.ZodLiteral<1>;
            automationPublicKey: z$1.ZodString;
            trustedSenderPublicKey: z$1.ZodString;
            required: z$1.ZodOptional<z$1.ZodBoolean>;
        }, z$1.core.$strip>>;
        scriptRuntime: z$1.ZodOptional<z$1.ZodObject<{
            state: z$1.ZodEnum<{
                ready: "ready";
                unavailable: "unavailable";
                disabled: "disabled";
            }>;
            code: z$1.ZodOptional<z$1.ZodString>;
            checkedAt: z$1.ZodNumber;
            imageSource: z$1.ZodOptional<z$1.ZodEnum<{
                env: "env";
                release: "release";
            }>>;
            imageFingerprint: z$1.ZodOptional<z$1.ZodString>;
        }, z$1.core.$strip>>;
    }, z$1.core.$strip>>;
    channelSupport: z$1.ZodOptional<z$1.ZodObject<{
        protocolVersion: z$1.ZodLiteral<1>;
        engines: z$1.ZodArray<z$1.ZodEnum<{
            claude: "claude";
            codex: "codex";
            gemini: "gemini";
            openclaw: "openclaw";
            opencode: "opencode";
            grok: "grok";
        }>>;
        approvals: z$1.ZodOptional<z$1.ZodObject<{
            protocolVersion: z$1.ZodLiteral<1>;
            engines: z$1.ZodArray<z$1.ZodEnum<{
                claude: "claude";
                codex: "codex";
                gemini: "gemini";
                openclaw: "openclaw";
                opencode: "opencode";
                grok: "grok";
            }>>;
        }, z$1.core.$strip>>;
    }, z$1.core.$strip>>;
    channelHost: z$1.ZodOptional<z$1.ZodObject<{
        protocolVersion: z$1.ZodLiteral<1>;
        custody: z$1.ZodLiteral<"available">;
        isolation: z$1.ZodEnum<{
            unavailable: "unavailable";
            available: "available";
        }>;
        providers: z$1.ZodArray<z$1.ZodString>;
        hostKey: z$1.ZodString;
        fingerprint: z$1.ZodString;
        deliver: z$1.ZodOptional<z$1.ZodLiteral<1>>;
    }, z$1.core.$strip>>;
    autonomousQualityGateSupport: z$1.ZodOptional<z$1.ZodObject<{
        apiVersion: z$1.ZodNumber;
        rpcAvailable: z$1.ZodBoolean;
    }, z$1.core.$strip>>;
    additionalDirectories: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
        maxDirectories: z$1.ZodLiteral<8>;
        agents: z$1.ZodTuple<[z$1.ZodLiteral<"claude">, z$1.ZodLiteral<"codex">], null>;
        access: z$1.ZodLiteral<"read-write">;
    }, z$1.core.$strip>>;
    difficultyRouting: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
        protocol: z$1.ZodLiteral<"org-shared-difficulty-routing.v1">;
        hostProcessKeyId: z$1.ZodString;
        hostProcessPublicKey: z$1.ZodString;
        ready: z$1.ZodOptional<z$1.ZodBoolean>;
        maxRelayTtlMs: z$1.ZodOptional<z$1.ZodNumber>;
        timingVersions: z$1.ZodOptional<z$1.ZodArray<z$1.ZodUnion<readonly [z$1.ZodLiteral<1>, z$1.ZodLiteral<2>]>>>;
        classifier: z$1.ZodObject<{
            kind: z$1.ZodLiteral<"transformers-binary">;
            modelMaxInputTokens: z$1.ZodLiteral<512>;
            maxInputChars: z$1.ZodLiteral<8000>;
            onnxSha256: z$1.ZodLiteral<"444c99b6f4d417e50859f73e1557db11943a2ad073ce4050a65f1b7d39403038">;
            tokenizerJsonSha256: z$1.ZodLiteral<"acadd7d076a55a97edf9fb0521a0a2e9cf8cbbdd62e4d793f2aa3d1900916356">;
            revision: z$1.ZodString;
        }, z$1.core.$strip>;
        limits: z$1.ZodObject<{
            concurrency: z$1.ZodLiteral<1>;
            queueSize: z$1.ZodLiteral<8>;
            requestDeadlineMs: z$1.ZodLiteral<1000>;
        }, z$1.core.$strip>;
    }, z$1.core.$strip>>;
    aiAuthSelection: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    agentDelegation: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    agentPlan: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
        claude: z$1.ZodOptional<z$1.ZodLiteral<1>>;
        claudeModels: z$1.ZodOptional<z$1.ZodArray<z$1.ZodString>>;
        codexModels: z$1.ZodOptional<z$1.ZodArray<z$1.ZodString>>;
    }, z$1.core.$strip>>;
    structuredOutput: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
        agents: z$1.ZodArray<z$1.ZodString>;
        maxSchemaBytes: z$1.ZodNumber;
    }, z$1.core.$strip>>;
    writeFileAttempt: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    listFilesPage: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    permissionGrants: z$1.ZodOptional<z$1.ZodObject<{
        bashPrefixMatcher: z$1.ZodLiteral<"plain-v1">;
    }, z$1.core.$strip>>;
    machineRun: z$1.ZodOptional<z$1.ZodObject<{
        protocolVersion: z$1.ZodLiteral<1>;
        supported: z$1.ZodBoolean;
        shell: z$1.ZodLiteral<false>;
        stdin: z$1.ZodLiteral<"none">;
        maxTimeoutMs: z$1.ZodNumber;
        maxOutputLimitBytes: z$1.ZodNumber;
    }, z$1.core.$strip>>;
    daemonSessionState: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    toolPolicy: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
        enforcement: z$1.ZodArray<z$1.ZodString>;
        policyVersion: z$1.ZodOptional<z$1.ZodString>;
    }, z$1.core.$strip>>;
    orgRequirements: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
        enforced: z$1.ZodArray<z$1.ZodString>;
    }, z$1.core.$strip>>;
    rpcBinding: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    sealedSpawnEnv: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    worktreeOps: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    projectPurge: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    workspaceSync: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    companyKeyReseed: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    terminalBinding: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodLiteral<1>;
    }, z$1.core.$strip>>;
    agentBrowser: z$1.ZodOptional<z$1.ZodObject<{
        desktopLogin: z$1.ZodOptional<z$1.ZodLiteral<1>>;
        profileId: z$1.ZodOptional<z$1.ZodString>;
        protocol: z$1.ZodNumber;
        tenancyMode: z$1.ZodEnum<{
            dedicated: "dedicated";
            shared: "shared";
        }>;
        hostMode: z$1.ZodOptional<z$1.ZodEnum<{
            "browser-only": "browser-only";
            "dedicated-host": "dedicated-host";
        }>>;
        sealedConsole: z$1.ZodOptional<z$1.ZodLiteral<1>>;
    }, z$1.core.$strip>>;
}, z$1.core.$strip>;
type MachineMetadata = z$1.infer<typeof MachineMetadataSchema>;
declare const DaemonRestartLifecycleSchema: z$1.ZodObject<{
    state: z$1.ZodUnion<readonly [z$1.ZodEnum<{
        running: "running";
        draining: "draining";
    }>, z$1.ZodString]>;
    intent: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodEnum<{
        restart: "restart";
        stop: "stop";
    }>, z$1.ZodString]>>;
    reason: z$1.ZodOptional<z$1.ZodString>;
    inTurnCount: z$1.ZodOptional<z$1.ZodNumber>;
    openTerminalCount: z$1.ZodOptional<z$1.ZodNumber>;
    busyTerminalCount: z$1.ZodOptional<z$1.ZodNumber>;
    deadlineAt: z$1.ZodOptional<z$1.ZodNumber>;
    terminals: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodEnum<{
        keep: "keep";
        close: "close";
    }>, z$1.ZodString]>>;
    terminalsCloseReason: z$1.ZodOptional<z$1.ZodString>;
    pendingHandoff: z$1.ZodOptional<z$1.ZodObject<{
        detectedAt: z$1.ZodNumber;
        busyTerminalCount: z$1.ZodNumber;
        forceAvailable: z$1.ZodBoolean;
    }, z$1.core.$strip>>;
}, z$1.core.$strip>;
type DaemonRestartLifecycle = z$1.infer<typeof DaemonRestartLifecycleSchema>;
/**
 * Daemon state - dynamic runtime information (frequently updated)
 */
declare const DaemonStateSchema: z$1.ZodObject<{
    status: z$1.ZodUnion<readonly [z$1.ZodEnum<{
        running: "running";
        "shutting-down": "shutting-down";
    }>, z$1.ZodString]>;
    pid: z$1.ZodOptional<z$1.ZodNumber>;
    httpPort: z$1.ZodOptional<z$1.ZodNumber>;
    startedAt: z$1.ZodOptional<z$1.ZodNumber>;
    shutdownRequestedAt: z$1.ZodOptional<z$1.ZodNumber>;
    shutdownSource: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodEnum<{
        unknown: "unknown";
        "mobile-app": "mobile-app";
        cli: "cli";
        "os-signal": "os-signal";
    }>, z$1.ZodString]>>;
    mcpCallerGrantPublicKey: z$1.ZodOptional<z$1.ZodString>;
    activity: z$1.ZodOptional<z$1.ZodObject<{
        activeSessionCount: z$1.ZodNumber;
        activeAutomationCount: z$1.ZodNumber;
        inTurnCount: z$1.ZodOptional<z$1.ZodNumber>;
        reportedAt: z$1.ZodNumber;
    }, z$1.core.$strip>>;
    lifecycle: z$1.ZodOptional<z$1.ZodObject<{
        state: z$1.ZodUnion<readonly [z$1.ZodEnum<{
            running: "running";
            draining: "draining";
        }>, z$1.ZodString]>;
        intent: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodEnum<{
            restart: "restart";
            stop: "stop";
        }>, z$1.ZodString]>>;
        reason: z$1.ZodOptional<z$1.ZodString>;
        inTurnCount: z$1.ZodOptional<z$1.ZodNumber>;
        openTerminalCount: z$1.ZodOptional<z$1.ZodNumber>;
        busyTerminalCount: z$1.ZodOptional<z$1.ZodNumber>;
        deadlineAt: z$1.ZodOptional<z$1.ZodNumber>;
        terminals: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodEnum<{
            keep: "keep";
            close: "close";
        }>, z$1.ZodString]>>;
        terminalsCloseReason: z$1.ZodOptional<z$1.ZodString>;
        pendingHandoff: z$1.ZodOptional<z$1.ZodObject<{
            detectedAt: z$1.ZodNumber;
            busyTerminalCount: z$1.ZodNumber;
            forceAvailable: z$1.ZodBoolean;
        }, z$1.core.$strip>>;
    }, z$1.core.$strip>>;
    terminalSurvival: z$1.ZodOptional<z$1.ZodObject<{
        version: z$1.ZodNumber;
        workers: z$1.ZodObject<{
            current: z$1.ZodNumber;
            draining: z$1.ZodNumber;
        }, z$1.core.$strip>;
        workerVersion: z$1.ZodOptional<z$1.ZodString>;
        lastAdoption: z$1.ZodOptional<z$1.ZodObject<{
            at: z$1.ZodNumber;
            adopted: z$1.ZodNumber;
            closed: z$1.ZodNumber;
            reaped: z$1.ZodNumber;
            failed: z$1.ZodNumber;
        }, z$1.core.$strip>>;
    }, z$1.core.$strip>>;
    launchMcpServers: z$1.ZodOptional<z$1.ZodLiteral<1>>;
}, z$1.core.$strip>;
type DaemonState = z$1.infer<typeof DaemonStateSchema>;
type Machine = {
    id: string;
    encryptionKey: Uint8Array;
    encryptionVariant: 'legacy' | 'dataKey';
    metadata: MachineMetadata;
    metadataVersion: number;
    daemonState: DaemonState | null;
    daemonStateVersion: number;
};
declare const UserMessageSchema: z$1.ZodObject<{
    role: z$1.ZodLiteral<"user">;
    content: z$1.ZodObject<{
        type: z$1.ZodLiteral<"text">;
        text: z$1.ZodString;
    }, z$1.core.$strip>;
    localKey: z$1.ZodOptional<z$1.ZodString>;
    meta: z$1.ZodOptional<z$1.ZodObject<{
        setupTokenCapacityActor: z$1.ZodOptional<z$1.ZodUnknown>;
        hubPrompt: z$1.ZodOptional<z$1.ZodUnknown>;
        sentFrom: z$1.ZodOptional<z$1.ZodString>;
        turnTrigger: z$1.ZodCatch<z$1.ZodOptional<z$1.ZodString>>;
        source: z$1.ZodCatch<z$1.ZodOptional<z$1.ZodString>>;
        delegatedAttendance: z$1.ZodCatch<z$1.ZodOptional<z$1.ZodEnum<{
            unattended: "unattended";
            attended: "attended";
        }>>>;
        permissionMode: z$1.ZodOptional<z$1.ZodEnum<{
            default: "default";
            acceptEdits: "acceptEdits";
            bypassPermissions: "bypassPermissions";
            plan: "plan";
            "read-only": "read-only";
            "safe-yolo": "safe-yolo";
            yolo: "yolo";
        }>>;
        model: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodString>>;
        modelSource: z$1.ZodCatch<z$1.ZodOptional<z$1.ZodEnum<{
            user: "user";
            auto: "auto";
        }>>>;
        fallbackModel: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodString>>;
        effort: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodString>>;
        customSystemPrompt: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodString>>;
        appendSystemPrompt: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodString>>;
        saycodeSystemPromptEnabled: z$1.ZodOptional<z$1.ZodBoolean>;
        turnOnlyPromptTokens: z$1.ZodCatch<z$1.ZodOptional<z$1.ZodArray<z$1.ZodString>>>;
        saycodePromptBlocks: z$1.ZodCatch<z$1.ZodOptional<z$1.ZodNullable<z$1.ZodObject<{
            agentOrchestration: z$1.ZodOptional<z$1.ZodBoolean>;
            coAuthoredCredit: z$1.ZodOptional<z$1.ZodBoolean>;
            workerDelegation: z$1.ZodOptional<z$1.ZodBoolean>;
            axBase: z$1.ZodOptional<z$1.ZodBoolean>;
            nextSteps: z$1.ZodOptional<z$1.ZodBoolean>;
            archiveRequest: z$1.ZodOptional<z$1.ZodBoolean>;
        }, z$1.core.$strip>>>>;
        allowedTools: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodArray<z$1.ZodString>>>;
        disallowedTools: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodArray<z$1.ZodString>>>;
        axStep: z$1.ZodCatch<z$1.ZodOptional<z$1.ZodEnum<{
            plan: "plan";
            design: "design";
            free: "free";
        }>>>;
        difficultyRoutingIntent: z$1.ZodCatch<z$1.ZodOptional<z$1.ZodObject<{
            version: z$1.ZodLiteral<1>;
            mode: z$1.ZodLiteral<"auto">;
            policy: z$1.ZodLiteral<"org-shared-difficulty-routing.v1">;
            clientRequestId: z$1.ZodString;
            clientRouteSource: z$1.ZodLiteral<"default-auto">;
        }, z$1.core.$strip>>>;
        difficultyRoutingPrompt: z$1.ZodOptional<z$1.ZodString>;
        difficultyRoutingAuthorization: z$1.ZodOptional<z$1.ZodString>;
        latencyTrace: z$1.ZodCatch<z$1.ZodOptional<z$1.ZodObject<{
            version: z$1.ZodLiteral<1>;
            id: z$1.ZodString;
        }, z$1.core.$strip>>>;
    }, z$1.core.$strip>>;
}, z$1.core.$strip>;
type UserMessage = z$1.infer<typeof UserMessageSchema> & {
    serverMessageId?: string;
    serverSeq?: number;
};
/**
 * File event message — sent by the app as a session envelope before the text message.
 * Contains a ref pointing to the encrypted blob on the server.
 */
declare const FileEventMessageSchema: z$1.ZodObject<{
    role: z$1.ZodLiteral<"session">;
    content: z$1.ZodObject<{
        type: z$1.ZodLiteral<"session">;
        data: z$1.ZodObject<{
            id: z$1.ZodString;
            time: z$1.ZodNumber;
            role: z$1.ZodLiteral<"user">;
            ev: z$1.ZodObject<{
                t: z$1.ZodLiteral<"file">;
                ref: z$1.ZodString;
                name: z$1.ZodString;
                size: z$1.ZodNumber;
                mimeType: z$1.ZodOptional<z$1.ZodString>;
                image: z$1.ZodOptional<z$1.ZodObject<{
                    width: z$1.ZodNumber;
                    height: z$1.ZodNumber;
                    thumbhash: z$1.ZodOptional<z$1.ZodString>;
                }, z$1.core.$strip>>;
            }, z$1.core.$strip>;
        }, z$1.core.$strip>;
    }, z$1.core.$strip>;
}, z$1.core.$strip>;
type FileEventMessage = z$1.infer<typeof FileEventMessageSchema>;
type Metadata = {
    /**
     * ACP session config option value (normalized for UI metadata consumers).
     */
    models?: Array<{
        code: string;
        value: string;
        description?: string | null;
    }>;
    currentModelCode?: string;
    operatingModes?: Array<{
        code: string;
        value: string;
        description?: string | null;
    }>;
    currentOperatingModeCode?: string;
    thoughtLevels?: Array<{
        code: string;
        value: string;
        description?: string | null;
    }>;
    currentThoughtLevelCode?: string;
    path: string;
    host: string;
    version?: string;
    setupTokenRotation?: {
        version: 1;
        principalType: 'machine';
        bindingVersion: 0 | 2;
    };
    /** Captured session opt-in, retained only when ON for resume/recovery. */
    inputEvidenceEnabled?: boolean;
    /** Immutable initial copy is retained on the automation run, outside mutable native metadata. */
    automationExecutionSeedManifest?: _slopus_happy_wire.AutomationExecutionSeedManifest;
    runtimeCapabilities?: {
        agentContact?: {
            v: 1;
            runtimeId: string;
            principal: 'account' | 'managed';
            prompt: boolean;
            steer: boolean;
            inputEvidence: 1 | null;
            guardedPrompt: 1 | null;
            mode: 'remote' | 'local' | 'transitioning';
            modeEpoch: number;
        };
        saycodeSystemPromptPreference?: boolean;
        /**
         * aplus-dev-studio specs/codexcli-approval-session-binding R15 — this runtime records every
         * resolution, declines unattended prompts after the wait and puts `expiresAt` on them. Absent:
         * an older runtime (or an agent without the wait), which never expires anything.
         */
        approvalLifecycle?: 1;
        /**
         * Published by the running Claude process, never inferred from machine metadata. Clients may
         * offer Bash(<prefix>:*) only when this session advertises plain-v1; absent means unsupported,
         * including an older session that survived a daemon upgrade.
         */
        permissionGrants?: {
            bashPrefixMatcher: 'plain-v1';
        };
        /**
         * aplus-dev-studio-desktop specs/linked-pull-requests R1-3 — this session's agent has the
         * `saycode_pr_link`/`saycode_pr_watch` tools. Clients use it only for that; reading and writing
         * `linkedPullRequests` does not depend on it.
         */
        linkedPullRequests?: 1;
        /**
         * aplus-dev-studio-desktop specs/agent-background-work-panel R2/R4 — this runtime answers
         * `background-task-stop` for the tasks it lists. Absent: an older runtime; clients show the list without Stop.
         */
        backgroundTaskStop?: 1;
    };
    /**
     * aplus-dev-studio-desktop specs/linked-pull-requests R1-1 — up to 20 `LinkedPullRequest` entries
     * (claude/utils/linkedPullRequestTools.ts), written by the agent's tools and by Saycode Desktop.
     * `unknown` for the reason `difficultyRoutingState` is: another client writes it, so every reader
     * goes through `readLinkedPullRequests` and every writer keeps what it cannot read.
     */
    linkedPullRequests?: unknown;
    /** aplus-dev-studio specs/e2ee-machine-control-boundary R18 — reads bound session-scope requests. */
    rpcBinding?: RpcBindingCapability;
    name?: string;
    os?: string;
    summary?: {
        text: string;
        updatedAt: number;
        /** English kebab-case slug for the task, supplied alongside the title for use as a git branch name. */
        branchSlug?: string;
    };
    /** Set after a browser task was successfully created in this Happy session. */
    agentBrowserUsed?: boolean;
    promptSuggestion?: {
        text: string;
        provider: string;
        updatedAt: number;
    } | null;
    machineId?: string;
    claudeSessionId?: string;
    codexThreadId?: string;
    acpSessionId?: string;
    tools?: string[];
    slashCommands?: string[];
    /**
     * Claude Code's live background tasks (`background_tasks_changed`), REPLACE on every publish. A turn starts
     * from `tasks: null` (no list yet; a reader that falls back to the transcript reads it from `startedAt`) unless
     * the last list still names live work, which stays until Claude Code replaces it. `available: false` is the
     * last list of a provider process that has ended.
     */
    claudeBackgroundTasks?: {
        startedAt: number;
        available: boolean;
        /**
         * `taskType` (the SDK `task_type`), `startedAt` (first listed) and, for a Bash/Monitor task, `command` and
         * `toolName` are aplus-dev-studio-desktop specs/agent-background-work-panel R1; readers treat them as optional.
         */
        tasks: Array<{
            taskId: string;
            label: string;
            kind: 'shell' | 'agent';
            taskType?: string;
            startedAt?: number;
            command?: string;
            toolName?: string;
        }> | null;
    };
    /** `startedAt`: when this runtime first saw the terminal (specs/agent-background-work-panel R1). */
    codexBackgroundTasks?: Array<{
        callId: string;
        command: string;
        processId?: string;
        status: 'running' | 'unknown';
        startedAt?: number;
    }>;
    /**
     * The Codex sub-agents (child threads) running now, the shape of `claudeBackgroundTasks`; REPLACE on every
     * publish. `taskId` is the child thread id, which is also the call id of its `CodexAgent` row.
     * `tasks` is null only with `available: false` (a Codex too old to report child threads).
     * aplus-dev-studio-desktop specs/subagent-running-indicator R11.
     */
    codexSubagentTasks?: {
        startedAt: number;
        available: boolean;
        tasks: Array<{
            taskId: string;
            label: string;
            kind: 'agent';
        }> | null;
    };
    mcpServers?: Array<{
        name: string;
        status: string;
        error?: string;
        checkedAt?: number;
    }>;
    skills?: string[];
    plugins?: Array<{
        name: string;
        path: string;
    }>;
    homeDir: string;
    happyHomeDir: string;
    happyLibDir: string;
    happyToolsDir: string;
    startedFromDaemon?: boolean;
    hostPid?: number;
    startedBy?: 'daemon' | 'terminal';
    lifecycleState?: 'running' | 'archiveRequested' | 'archived' | string;
    lifecycleStateSince?: number;
    archivedBy?: string;
    archiveReason?: string;
    flavor?: string;
    sandbox?: SandboxConfig | null;
    dangerouslySkipPermissions?: boolean | null;
    /**
     * The permission mode this session applies to its next turn, as the runtime resolved it
     * (validation, the ambient-default downgrade guard and the sandbox policy already applied).
     * Published at start and on every change — a client message that switches it, a turn-scoped
     * abort reset — so any client can read the session's *current* mode, not only the mode the
     * sender itself last sent or the creation-time `dangerouslySkipPermissions`
     * (aplus-dev-studio-desktop #2187). Absent on older runtimes; readers treat that as unknown.
     */
    permissionMode?: PermissionMode;
    /** When `permissionMode` was last published, on this runtime's clock (ms since epoch). */
    permissionModeUpdatedAt?: number;
    /** Lineage for sessions created via the fork / duplicate flow. */
    parentSessionId?: string;
    forkedFromMessageId?: string;
    /**
     * Identity of the account that requested this session's creation, as
     * reported by the client (e.g. desktop app). Additive — absent on
     * sessions created before this field existed and on any spawn that
     * doesn't supply it (specs/session-created-by).
     */
    createdBy?: {
        accountId: string;
        displayName?: string;
    };
    /**
     * The linked machine and its session this one was started for (aplus-dev-studio
     * specs/cross-machine-agent-delegation R9). Desktop shows the child under that parent only when the
     * parent's ledger names this session too.
     */
    delegatedFrom?: {
        machineId: string;
        sessionId: string;
    };
    /**
     * The session runs on an organization LLM endpoint (aplus specs/org-llm-endpoints r3): written once by the daemon's
     * spawn, non-secret — ids only, never an address, a target or a token. A client reads it to know the conversation is
     * tied to that endpoint (and must not be continued in a new session under another source); a recovery with no local
     * record refuses a new session when it is present. Absent on every other session and on older runtimes.
     */
    personalLlmEndpoint?: PersonalEndpointMarker;
    orgLlmEndpoint?: {
        version: 1;
        bindingId: string;
        endpointId: string;
        selectedModel?: string;
    };
    /**
     * Who started the session (`user`, `schedule`, `github-trigger`, …). An open
     * enum written once at creation; absent on older sessions and on spawns that
     * don't supply it, which readers treat as unknown — never as `user`
     * (aplus-dev-studio specs/session-source-metadata).
     */
    source?: SessionSource;
    /**
     * Auto-routing state. Deliberately `unknown`: the record may be the pre-v2
     * shape (`{ difficulty, hardTurns, updatedAt }`), the versioned v2 shape, or
     * one written by a newer CLI that this build cannot represent. Every reader
     * goes through `normalizeRoutingSessionState`, which validates it and reports
     * an unreadable record as an unknown floor rather than as an absent one — a
     * typed field here would invite exactly the unchecked cast that loses that
     * distinction.
     */
    difficultyRoutingState?: unknown;
};
type AgentGoalStatus = {
    source: 'claude' | 'codex';
    observedAt: number;
    sourceSessionId?: string;
    sourceRevision?: string | number;
} & ({
    status: 'unavailable';
    reason?: 'unsupported' | 'not_loaded' | 'stale' | 'malformed' | 'error' | 'unknown';
} | {
    status: 'inactive';
    reason?: 'none' | 'cleared' | 'completed' | 'unknown';
} | {
    status: 'active';
    sourceSessionId: string;
    text: string;
    /** Codex: why the goal is or is not running. Absent from older runtimes, which only report `active`. */
    phase?: 'active' | 'paused' | 'blocked' | 'usageLimited';
    capabilities?: {
        clear?: boolean;
        stop?: boolean;
        edit?: boolean;
        /** `goal-action {action:'resume'}` restarts a paused goal without changing its objective. */
        resume?: boolean;
    };
    progress?: {
        currentStep?: number;
        totalSteps?: number;
        steps?: Array<{
            text: string;
            status: 'pending' | 'in_progress' | 'completed';
        }>;
    };
});
type AgentState = {
    controlledByUser?: boolean | null | undefined;
    requests?: {
        [id: string]: {
            tool: string;
            arguments: any;
            createdAt: number;
            /** aplus-dev-studio specs/agent-tool-policy R11 — present only on a tool policy `ask`. */
            policy?: PermissionPolicyMeta;
            /**
             * aplus-dev-studio specs/codexcli-approval-session-binding R13 — when an unattended wait is
             * declined, on this process's clock. For display only: clients add `expiresAt - createdAt`
             * to the moment they first saw the request rather than comparing clocks.
             */
            expiresAt?: number;
        };
    };
    completedRequests?: {
        [id: string]: {
            tool: string;
            arguments: any;
            createdAt: number;
            completedAt: number;
            status: 'canceled' | 'denied' | 'approved';
            reason?: string;
            policy?: PermissionPolicyMeta;
            mode?: PermissionMode;
            decision?: 'approved' | 'approved_for_session' | 'denied' | 'abort';
            allowTools?: string[];
            /** codexcli-approval-session-binding plan §3.4 — which path settled it. Older clients ignore it. */
            resolution?: PermissionResolution;
        };
    };
    agentGoalStatus?: AgentGoalStatus;
    /** A turn waiting to retry after a temporary API failure; `null` once it ran or was cancelled. */
    transientRetry?: AgentTransientRetry | null;
    /** aplus-dev-studio specs/agent-tool-policy R16 — latest 50 `ask`/`blocked` decisions, no arguments. */
    toolPolicy?: {
        recent: ToolPolicyAuditRecord[];
    };
    /** aplus-dev-studio-desktop specs/codexcli-org-requirements R10.6, R16a — absent outside any organization. */
    orgRequirements?: OrgRequirementsAgentState;
    /**
     * Saycode specs/cli-usage-limits-snapshot R8 — the plan rate-limit windows Claude last reported for this
     * session. Clients must tolerate window ids they don't recognize; absent from older runtimes.
     */
    usageLimits?: UsageLimits;
};
type UsageLimitWindowStatus = 'allowed' | 'allowed_warning' | 'rejected';
type UsageLimitWindow = {
    /** Claude's window id (`five_hour`, `seven_day`, `seven_day_opus`, …), or `plan` when the provider did not say which. */
    id: string;
    status?: UsageLimitWindowStatus;
    /** Percent of the window used, 0-100. */
    utilization: number | null;
    /** ISO 8601 time the window resets. */
    resetsAt: string | null;
};
type UsageLimits = {
    /** Epoch ms of the last change published. */
    capturedAt: number;
    windows: UsageLimitWindow[];
};
/**
 * Saycode specs/claude-transient-retry — what a client needs to show a countdown. `retryAt` in the
 * past means a runtime that stopped while waiting left it behind; treat it as gone.
 */
type AgentTransientRetry = {
    provider: 'claude';
    attempt: number;
    maxAttempts: number;
    reason: 'overloaded' | 'server_error' | 'timeout' | 'network';
    /** HTTP status of the final failure; `null` when no response arrived (connection, timeout). */
    status: number | null;
    scheduledAt: number;
    retryAt: number;
};

type EvidenceBatch = {
    inputs: InputRef[];
    inputCount: number;
    continuation?: InputEvidenceV1;
    incompleteReasons?: string[];
};
type AdditionalKind = InputEvidenceV1['additional']['items'][number]['kind'];
type AttemptState = InputEvidenceV1['additional']['items'][number]['state'];
type ContinuationKind = InputEvidenceV1['continuation']['kind'];
type QueueInputEvidence = {
    ref: InputRef;
    guard?: unknown;
    continuation?: InputEvidenceV1;
};
/** Host state, never inferred from delayed metadata echoes. Calls and transitions are synchronous. */
declare class HubInputGate {
    readonly sessionId: string;
    readonly runtimeId: string;
    readonly managed: boolean;
    mode: 'remote' | 'local' | 'transitioning';
    modeEpoch: number;
    constructor(sessionId: string, runtimeId: string, managed: boolean);
    transition(mode: HubInputGate['mode']): boolean;
    check(input: QueueInputEvidence): HubInputAdmissionV1 | null;
}
declare class TurnInputEvidence {
    readonly runtimeId: string;
    private readonly emit;
    private pending;
    private readonly claimedContinuations;
    private background;
    private readonly attempts;
    private readonly turns;
    private current;
    private last;
    private carry;
    private readonly backgroundTurns;
    rememberBackground(id: string, turn: string): void;
    rearmBackground(ids: string[], incompleteReasons?: string[], nextTurn?: boolean): void;
    constructor(runtimeId: string, emit: (envelope: SessionEnvelope) => void);
    currentTurn(): string | null;
    /** A final without a routing turn has no provable turn identity or consumed inputs.
     * This snapshot is never registered as a turn, current/last witness or retry carry.
     */
    unmappedFinalEvidence(reason?: string): SessionEnvelope;
    setPending(batch: EvidenceBatch | null): void;
    /** Synchronous ownership transfer at the provider write; later input cannot cancel dispatched work. */
    commitPending(): boolean;
    /** Claim before provider dispatch; the receipt can wait in Claude's ordered transcript queue. */
    claimContinuation(value: InputEvidenceV1): InputEvidenceV1 | undefined;
    /** Settle a claimed dispatch with no mapped provider turn; never create a turn for it. */
    cancelPendingDispatch(missingTurnReason?: string): void;
    private clone;
    private settleAttempt;
    snapshot(turn?: string | null): InputEvidenceV1 | null;
    private fit;
    private publish;
    incomplete(reason: string, turn?: string | null): void;
    /** Called before the provider write. The returned token stays tied to that turn across awaits. */
    attempt(kind: AdditionalKind, turn?: string | null): {
        settle(state: Exclude<AttemptState, 'pending'>): void;
    };
    /** A decision to retry (or to wait for an account) must precede the failed terminal. */
    continuePending(kind: ContinuationKind): void;
    isContinuationCurrent(value: InputEvidenceV1): boolean;
    takeContinuation(): InputEvidenceV1 | undefined;
    cancelContinuation(state: 'cancelled' | 'replaced' | 'completed'): void;
    stamp(envelope: SessionEnvelope): SessionEnvelope;
}

/**
 * What one queued input says about its sender.
 * - `unattended`: an input nobody watches; a batch made only of these is an unattended turn.
 * - `automatic`: sent by something on a person's behalf; it makes the turn attended but is not a
 *   person arriving, so it does not lift a running wait.
 * - `human`: a person, here and now; it lifts the current turn's wait.
 */
type InputAttendance = 'unattended' | 'automatic' | 'human';

type PendingAttachment = {
    data: Uint8Array;
    mimeType: string;
    name: string;
};
/** An opt-in, daemon-local marker for one browser chat input. It never holds text or a session id. */
type QueueLatencyTrace = {
    id: string;
    receivedAt: number;
};
interface QueueItem<T> {
    evidence?: QueueInputEvidence;
    message: string;
    mode: T;
    modeHash: string;
    isolate?: boolean;
    /** Decoded image attachments owned by *this* message (per-message ownership). */
    attachments?: PendingAttachment[];
    latencyTrace?: QueueLatencyTrace;
    /**
     * Identifiers for whatever produced this message (auto-routing client request
     * ids today). They ride *beside* the mode rather than inside it: the mode is
     * hashed to decide batching, so putting per-message ids there would give every
     * message a unique hash and destroy the batching itself.
     */
    requestIds?: string[];
    /**
     * Core-minted handle for a turn that answers an external messenger request
     * (Saycode specs/desktop-messenger-channels). Kept apart from `requestIds`: those are
     * auto-routing ids that ordinary Desktop input carries too, and anything that reads "has an
     * id" as "came from a channel" would then put every routed Desktop message behind channel
     * execution approval and switch off its slash commands.
     */
    channelRequestId?: string;
    /**
     * Who sent this input (codexcli-approval-session-binding R10a). Beside the mode for the same
     * reason as `requestIds`: inside it, it would split batches. Absent means a person.
     */
    attendance?: InputAttendance;
}
type CollectedBatch<T> = {
    /** Original entries survive dequeue so a mode transition can remove only guarded inputs. */
    items?: QueueItem<T>[];
    inputs?: InputRef[];
    continuation?: InputEvidenceV1;
    message: string;
    mode: T;
    hash: string;
    isolate: boolean;
    attachments?: PendingAttachment[];
    /**
     * Every merged message's request ids, in batch order. A consumer that commits
     * per-execution state needs all of them: attributing a merged batch to its
     * first input alone loses the rest.
     */
    requestIds?: string[];
    inputCount: number;
    latencyTraces: QueueLatencyTrace[];
    /**
     * The channel request this batch answers. Channel turns are always pushed isolated, so a
     * batch carries at most one — and a batch with one carries nothing else.
     */
    channelRequestId?: string;
    /**
     * Every merged input was sent by something nobody watches. The batch is one turn, so a single
     * input from anyone else makes the whole turn attended (plan §3.4).
     */
    allUnattended: boolean;
};
/**
 * A mode-aware message queue that stores messages with their modes.
 * Returns consistent batches of messages with the same mode.
 */
declare class MessageQueue2<T> {
    queue: QueueItem<T>[];
    private waiter;
    private closed;
    private onMessageHandler;
    modeHasher: (mode: T) => string;
    private inputValidator;
    private inputAccepted;
    setInputValidator(validator: (input: QueueInputEvidence) => boolean, accepted?: (input: QueueInputEvidence) => void): void;
    private valid;
    discardInvalid(): void;
    revalidateBatch(batch: CollectedBatch<T>): CollectedBatch<T> | null;
    constructor(modeHasher: (mode: T) => string, onMessageHandler?: ((message: string, mode: T) => void) | null);
    /**
     * Set a handler that will be called when a message arrives
     */
    setOnMessage(handler: ((message: string, mode: T) => void) | null): void;
    /** Remove only a tagged channel request; ordinary Desktop input is never selected. */
    removeByRequestId(requestId: string): number;
    /**
     * Push a message to the queue with a mode and an optional list of
     * attachments that travel with this message.
     */
    push(message: string, mode: T, attachments?: PendingAttachment[], requestIds?: string[], latencyTrace?: QueueLatencyTrace, attendance?: InputAttendance, evidence?: QueueInputEvidence): void;
    /**
     * Push a message immediately without batching delay.
     * Does not clear the queue or enforce isolation.
     */
    pushImmediate(message: string, mode: T, latencyTrace?: QueueLatencyTrace, evidence?: QueueInputEvidence): void;
    /**
     * Push a message that must be processed in complete isolation.
     * Clears any pending messages and ensures this message is never batched with others.
     * Used for special commands that require dedicated processing.
     */
    /**
     * Returns the request ids of the messages this call discarded. They were
     * accepted but will never execute, so a consumer holding per-request state
     * needs to know they are dead — otherwise their decisions sit in the state
     * forever, indistinguishable from work still in flight.
     */
    pushIsolateAndClear(message: string, mode: T, attachments?: PendingAttachment[], latencyTrace?: QueueLatencyTrace, attendance?: InputAttendance, evidence?: QueueInputEvidence): string[];
    /**
     * Push a message that must be processed alone without discarding
     * already-queued user prompts.
     */
    pushIsolated(message: string, mode: T, attachments?: PendingAttachment[], requestIds?: string[], channelRequestId?: string, latencyTrace?: QueueLatencyTrace, evidence?: QueueInputEvidence): void;
    /**
     * Put a message at the front without allowing it to batch with messages
     * that were already queued. Used for an automation turn that wakes an
     * existing session while preserving subsequent user input.
     */
    unshiftIsolated(message: string, mode: T, latencyTrace?: QueueLatencyTrace, attendance?: InputAttendance, evidence?: QueueInputEvidence): void;
    /**
     * Push a message to the beginning of the queue with a mode.
     */
    unshift(message: string, mode: T, latencyTrace?: QueueLatencyTrace, evidence?: QueueInputEvidence): void;
    /**
     * Reset the queue - clears all messages and resets to empty state
     */
    reset(): void;
    /**
     * Close the queue - no more messages can be pushed
     */
    close(): void;
    /**
     * Check if the queue is closed
     */
    isClosed(): boolean;
    /**
     * Get the current queue size
     */
    size(): number;
    /**
     * Wait for messages and return all messages with the same mode as a single string
     * Returns { message: string, mode: T } or null if aborted/closed
     */
    waitForMessagesAndGetAsString(abortSignal?: AbortSignal, claim?: () => boolean, beforeDequeue?: () => Promise<boolean>): Promise<CollectedBatch<T> | null>;
    /**
     * Collect a batch of messages with the same mode, respecting isolation requirements
     */
    private collectBatch;
    /**
     * Wait for messages to arrive
     */
    private waitForMessages;
}

/**
 * Type definitions for Claude Code SDK integration
 * Re-exports from official @anthropic-ai/claude-agent-sdk with adapter types
 */

type CanCallToolCallback = CanUseTool;
/**
 * Adapter type for query options.
 * Maps to official SDK's Options type but preserves existing field names
 * used throughout the codebase. The query() wrapper handles the translation.
 */
interface QueryOptions {
    /** Internal run policy, derived from the authenticated Happy execution identity. */
    isolatedAutomationContext?: boolean;
    /** Process-local selected personal credential, delivered only over SDK stdin control. */
    personalClaudeAuth?: {
        oauthToken: string;
    };
    abort?: AbortSignal;
    allowedTools?: string[];
    appendSystemPrompt?: string;
    customSystemPrompt?: string;
    cwd?: string;
    additionalDirectories?: string[];
    disallowedTools?: string[];
    maxTurns?: number;
    /** Emit Claude's predicted next user prompt after completed turns. */
    promptSuggestions?: boolean;
    /**
     * 내장 도구 허용 목록. 빈 배열은 **전부 끈다**(`sdk.d.ts`: "Disable all
     * built-in tools"). 이 자리가 없으면 관리 실행의 도구 경계가 SDK 까지
     * 도달하지 못한다.
     */
    tools?: string[];
    mcpServers?: Record<string, unknown>;
    /** Local plugin directories to load, e.g. the session's `--plugin-dir` arguments (claude/utils/pluginsFromArgs.ts). */
    plugins?: Options['plugins'];
    permissionMode?: 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan';
    continue?: boolean;
    resume?: string;
    model?: string;
    fallbackModel?: string;
    /**
     * Session-scoped structured output (Saycode specs/claude-cli-benchmark-followups R2). Applies
     * to every turn of the query; see `src/claude/structuredOutput.ts`.
     */
    outputFormat?: ClaudeOutputFormat;
    strictMcpConfig?: boolean;
    canCallTool?: CanCallToolCallback;
    /** Path to a settings JSON file to pass to Claude via --settings */
    settingsPath?: string;
    /**
     * Effort level passed straight through to the Claude Agent SDK option
     * of the same name — controls how much thinking/reasoning Claude
     * applies on each turn ('low' | 'medium' | 'high' | 'xhigh' | 'max').
     * 'xhigh' is supported on the newest Opus generation (e.g. Opus 4.8);
     * the SDK silently downgrades it to 'high' on models without it.
     */
    effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
    /**
     * Programmatically-defined custom subagents, keyed by name, forwarded to the
     * SDK's `agents` option. Used for per-session orchestrator/worker delegation:
     * a cheaper `worker` agent the (expensive) main model delegates mechanical
     * work to. See orchestrator/workerAgents.ts.
     */
    agents?: Record<string, AgentDefinition>;
    /**
     * Which filesystem settings sources to load ('user' | 'project' | 'local').
     * Omit to keep the SDK default (all sources). See orchestrator/skillGovernance.ts
     * for the env-driven per-session/machine control that populates this.
     */
    settingSources?: SettingSource[];
    /**
     * Explicit skill allowlist for the main session ('all' or a name list).
     * Omit to keep the SDK default (CLI's own defaults, i.e. not restricted).
     * See orchestrator/skillGovernance.ts.
     */
    skills?: string[] | 'all';
    sandbox?: SandboxSettings;
    /**
     * CLI 권한 규칙의 deny 목록. sandbox 가 Bash 실행 경계를 담당하는 동안
     * Read/Edit 같은 도구 경로를 막는 층이다 (sandbox/claudeSdkSandbox.ts).
     */
    permissionsDeny?: string[];
    spawnClaudeCodeProcess?: Options['spawnClaudeCodeProcess'];
    /** False keeps a side query (e.g. off-turn titling) out of the session files and `--resume` list. */
    persistSession?: boolean;
    /**
     * Have the CLI report `session_state_changed`, whose `idle` is its own
     * signal that no turn is running or owed to queued background reports.
     */
    emitSessionStateEvents?: boolean;
}

/**
 * One coalesced slice of assistant text for a (message, content block).
 * `offset` is the number of characters of this block already sent before
 * `delta`, so a consumer can accept a frame only when it continues what it
 * has (or starts a block at 0) and otherwise hide the draft instead of showing
 * a sentence with a hole in it. The persisted assistant message that follows
 * is always authoritative; frames are best-effort preview only.
 */
type StreamDeltaFrame = {
    messageId: string;
    index: number;
    offset: number;
    delta: string;
    final: boolean;
};

type SandboxPolicyMode = 'mandatory' | 'owner-choice';

type StorageConfirmation = {
    stored: true;
    revision: number;
} | {
    stored: false;
    reason: 'unconfirmed-write' | 'unsupported' | 'deadline' | 'aborted' | 'disconnected' | 'closed' | 'sync-failed';
};

/** Only the operations this host actually calls. */
interface LessonHostService {
    recall(input: unknown): Promise<unknown>;
    get(input: unknown): Promise<unknown>;
    recordRead(input: unknown): Promise<unknown>;
    ackDelivery(input: unknown): Promise<unknown>;
    enqueueCandidate(input: unknown): Promise<unknown>;
    markReviewed(input: unknown): Promise<unknown>;
    approveCandidate(input: unknown): Promise<unknown>;
    rejectCandidate(input: unknown): Promise<unknown>;
    setRecallEnabled(input: unknown): Promise<unknown>;
    listCandidates(input: unknown): Promise<unknown>;
    listLessons(input: unknown): Promise<unknown>;
    reviewStatus(input: unknown): Promise<unknown>;
    /**
     * Persists this turn's redacted evidence and returns the real event ids.
     *
     * Optional on the type because an older installed build does not have it.
     * Its absence is `unsupported`, never a reason to invent ids: CML checks
     * every source ref exists and belongs to the project, so fabricated ones
     * are refused at the store — and would be a lie in the record if they were
     * not.
     */
    appendNormalEndEvidence?(input: unknown): Promise<unknown>;
}
interface LessonHostHandle {
    service: LessonHostService;
    projectHash: string;
    /**
     * The workspace this store was opened for — the path a lesson lookup must
     * name. Not the provider's cwd: a checkpoint-protected turn runs in its own
     * repository, which CML would not resolve onto this project's store.
     */
    projectPath?: string;
    hashCandidatePayload(payload: unknown): string;
    /** The installed store advertises `lessonUpdates`: a candidate may carry `updatesLesson`. Its schema is strict, so never send the field otherwise. */
    supportsLessonUpdates?: boolean;
    close(): Promise<void>;
}

/**
 * The only thing in this process that can produce a binding CML will act on.
 *
 * CML's contract says a request "cannot provide or override" the binding
 * fields, and it enforces that by calling a host-supplied `verifyBinding` at
 * every entry and again immediately before each write. A `verifyBinding` that
 * returns its argument satisfies the type and defeats the contract completely:
 * any object shaped like a binding — including one assembled from an
 * unverified RPC payload — becomes an identity, with whatever capabilities it
 * claims.
 *
 * So a binding never travels as data. `issue` mints an opaque handle, keeps
 * the real binding in a `WeakMap` keyed by that handle, and `verifier()`
 * resolves only handles this registry issued. A forged object has no entry and
 * is refused; a copy of a handle's own fields is a different object and is
 * refused too.
 *
 * Freshness is re-checked on every resolution, not once at issue:
 *
 *  - the handle must not have been released (the caller releases in `finally`,
 *    so a binding cannot outlive the request that earned it);
 *  - it must not have expired;
 *  - the runtime must still be open;
 *  - the generation must still match, so a settings change or a re-bound
 *    session fences work that began under the old one — which is precisely the
 *    "again immediately before each write" check CML relies on.
 *
 * `projectHash` is supplied by the registry from the store the runtime opened,
 * never by the caller. Two projects on one machine would otherwise be one
 * grant apart: a grant legitimately minted for project A carries A's id, and
 * without pinning, its binding could be handed to the store opened for B.
 */
type LessonCapability = 'lesson.read' | 'lesson.review' | 'lesson.manage';
interface VerifiedLessonHostBinding {
    projectHash: string;
    actorId: string;
    userId: string;
    machineId: string;
    sessionId: string;
    generation: number;
    capabilities: readonly LessonCapability[];
    /**
     * Sessions whose turn this host watched end normally.
     *
     * CML accepts evidence only for a session named here, so this is the host
     * asserting "I saw that turn finish" — an assertion no request may make
     * for itself. It is set by the review path alone, from the turn record it
     * just evaluated, and is never populated from RPC input.
     */
    normalEndSessionIds?: readonly string[];
}
/** Opaque. Carries no fields a caller could copy into a forgery. */
interface LessonBindingHandle {
    readonly __lessonBinding: unique symbol;
}
type LessonBindingIssue = {
    /** Pass this to CML as the binding; it is never the binding itself. */
    handle: LessonBindingHandle;
    /** Always called in a `finally`; a released handle stops resolving. */
    release(): void;
};
interface LessonBindingIssuer {
    /**
     * Mints a handle for an already-authenticated identity.
     *
     * `projectId` is the scope the caller proved — from verified grant claims
     * for a UI request, or from the runtime's own pinning for a turn. It must
     * equal the project this runtime opened, or nothing is issued.
     */
    issue(input: {
        projectId: string;
        userId: string;
        machineId: string;
        sessionId: string;
        capabilities: readonly LessonCapability[];
        ttlMs: number;
        /** Host-observed normal turn ends; see the field's own note. */
        normalEndSessionIds?: readonly string[];
    }): Promise<LessonBindingIssue>;
    /** The `verifyBinding` handed to CML. Resolves issued handles only. */
    verifier(): (binding: unknown) => Promise<VerifiedLessonHostBinding>;
    /** For callers that need the resolved fields (tracing, ack tickets). */
    resolve(handle: LessonBindingHandle): Promise<VerifiedLessonHostBinding>;
}

declare const settingsSchema: z$1.ZodObject<{
    revision: z$1.ZodNumber;
    recallEnabled: z$1.ZodBoolean;
    reviewEnabled: z$1.ZodBoolean;
    dailyMicroUsd: z$1.ZodNumber;
    dailyTokens: z$1.ZodNumber;
}, z$1.core.$strict>;
type LessonSettings = z$1.infer<typeof settingsSchema>;

/**
 * `glm` is API-key only: there is no GLM subscription login, and a GLM key is
 * spent by Claude Code (agent `claude`) against Z.AI's Anthropic-compatible
 * endpoint.
 */
declare const MANAGED_AI_AUTH_PROVIDERS: readonly ["claude", "codex", "glm"];
type ManagedAiAuthProvider = (typeof MANAGED_AI_AUTH_PROVIDERS)[number];
/** What a connection holds. One-to-one with the personal kinds. */
declare const MANAGED_AI_AUTH_CREDENTIAL_KINDS: readonly ["oauth", "api-key"];
type ManagedAiAuthCredentialKind = (typeof MANAGED_AI_AUTH_CREDENTIAL_KINDS)[number];
type ManagedAiAuthPersonalKind = 'personal-subscription' | 'personal-api-key';
type ManagedAiAuthSelection = {
    kind: 'platform-gateway';
} | {
    kind: 'platform-glm';
} | {
    kind: ManagedAiAuthPersonalKind;
    provider: ManagedAiAuthProvider;
    connectionId: string;
    connectionVersion: number;
};
declare const MANAGED_AI_AUTH_ACTIONS: readonly ["login-start", "login-complete", "login-cancel", "set-key", "logout", "status"];
type ManagedAiAuthAction = (typeof MANAGED_AI_AUTH_ACTIONS)[number];
type ManagedAiAuthRpcParams = {
    action: ManagedAiAuthAction;
    connectionId: string;
    provider: ManagedAiAuthProvider;
    /** login-start / logout: the version the marker records on success. */
    connectionVersion?: number;
    /** login-start: the pending login is discarded after this instant. */
    expiresAt?: number;
    /** login-complete (claude): the code the user pasted, `code#state` allowed. */
    code?: string;
    /**
     * set-key only. Lands in the auth home and nowhere else — never in a
     * reply, never in a log line, never in the parent's database.
     */
    apiKey?: string;
};
type ManagedAiAuthLoginMethod = 'paste-code' | 'device-code';
/**
 * What the daemon answers. Never a token, never a refresh token, never the
 * PKCE verifier: the parent stores this reply, and a reply that carried a
 * secret would put the secret in the parent's database.
 */
type ManagedAiAuthRpcResult = {
    state: 'absent' | 'pending' | 'connected' | 'failed';
    connectionVersion: number | null;
    /** On `connected`: what kind of credential is held. */
    credentialKind?: ManagedAiAuthCredentialKind;
    loginMethod?: ManagedAiAuthLoginMethod;
    loginUrl?: string;
    userCode?: string;
    expiresAt?: number;
    accountLabel?: string;
    failureCode?: string;
};

/** The agents this deployment actually runs, mirroring the parent's list. */
declare const MANAGED_SPAWN_AGENTS: readonly ["claude", "codex"];
type ManagedSpawnAgent = (typeof MANAGED_SPAWN_AGENTS)[number];
declare const MANAGED_SPAWN_WIRE_VERSION = 1;
type ManagedSpawnBootstrap = {
    version: typeof MANAGED_SPAWN_WIRE_VERSION;
    serverOrigin: string;
    sessionId: string;
    encryptionVariant: 'dataKey';
    rawKeyBase64: string;
    wrappedKeyBase64: string;
    scopedToken: string;
    tokenExpiresAt: number;
};
type ManagedSpawnGateway = {
    baseUrl: string;
    capability: string;
    provider: string;
    endpoint: string;
    model: string;
};
type ManagedSpawnEnvelope = {
    directory: string;
    agent: ManagedSpawnAgent;
    model: string;
    effort: string;
    initialPrompt: string;
    initialPromptLocalId: string;
    bootstrap: ManagedSpawnBootstrap;
    /**
     * Which AI authentication this run was admitted on.
     *
     * Absent on the wire means `platform-gateway`, the meaning every v1
     * envelope already had. It is not a hint: it decides whether this run has
     * a gateway capability to spend at all.
     */
    aiAuth: ManagedAiAuthSelection;
    /**
     * The approved gateway, or `null` for a personal subscription.
     *
     * `null` rather than optional, so every consumer has to say what it does
     * without one. A personal run has no capability, and falling back to a
     * gateway because a field was missing is precisely the compatibility
     * bypass R25 forbids.
     */
    gateway: ManagedSpawnGateway | null;
};

type ManagedAttachment = {
    session: Session;
    /** The credential mode every managed call must be made under. */
    managed: {
        serverOrigin: string;
    };
    scopedToken: string;
};

type CheckpointProvider = 'claude-remote' | 'codex' | string;

declare const checkpointAgentSchemas: {
    status: z$1.ZodObject<{}, z$1.core.$strict>;
    list: z$1.ZodObject<{
        limit: z$1.ZodOptional<z$1.ZodNumber>;
        offset: z$1.ZodOptional<z$1.ZodNumber>;
    }, z$1.core.$strict>;
    preview: z$1.ZodObject<{
        checkpointId: z$1.ZodString;
        limit: z$1.ZodOptional<z$1.ZodNumber>;
        offset: z$1.ZodOptional<z$1.ZodNumber>;
    }, z$1.core.$strict>;
    diff: z$1.ZodObject<{
        checkpointId: z$1.ZodString;
        path: z$1.ZodString;
    }, z$1.core.$strict>;
};
type CheckpointAgentOperation = keyof typeof checkpointAgentSchemas;
declare const listResult: z$1.ZodObject<{
    checkpoints: z$1.ZodArray<z$1.ZodObject<{
        checkpointId: z$1.ZodString;
        createdAt: z$1.ZodNumber;
    }, z$1.core.$strip>>;
}, z$1.core.$strip>;
declare const previewResult: z$1.ZodObject<{
    entries: z$1.ZodArray<z$1.ZodObject<{
        path: z$1.ZodString;
        action: z$1.ZodEnum<{
            restore: "restore";
            delete: "delete";
            skip: "skip";
            conflict: "conflict";
        }>;
        reason: z$1.ZodString;
    }, z$1.core.$strip>>;
    skipDetails: z$1.ZodOptional<z$1.ZodArray<z$1.ZodObject<{
        path: z$1.ZodString;
        detail: z$1.ZodString;
    }, z$1.core.$strip>>>;
}, z$1.core.$strip>;
declare const diffResult: z$1.ZodObject<{
    status: z$1.ZodEnum<{
        text: "text";
        binary: "binary";
        "too-large": "too-large";
    }>;
    diff: z$1.ZodString;
}, z$1.core.$strip>;
type Page = {
    schemaVersion: 1;
    total: number;
    nextOffset: number | null;
};
type ReadResults = {
    status: {
        schemaVersion: 1;
        supported: boolean;
        enabled: boolean;
        mode: 'local-history';
        reason?: string;
        restoreRequiresUserConfirmation: true;
    };
    list: Page & z$1.infer<typeof listResult>;
    preview: Page & z$1.infer<typeof previewResult> & {
        checkpointId: string;
        restoreRequiresUserConfirmation: true;
    };
    diff: z$1.infer<typeof diffResult> & {
        schemaVersion: 1;
        checkpointId: string;
        path: string;
        direction: 'current-to-checkpoint';
        truncated: boolean;
    };
};
/** Immutable launcher binding, current persisted state, and existing RPC ownership/coverage checks. */
declare function createCheckpointAgentReader(input: {
    provider: CheckpointProvider;
    platform: NodeJS.Platform;
    projectPath: string;
    sessionId: string;
    sandboxConfig?: SandboxConfig;
    env: Record<string, string | undefined>;
}): {
    status: () => Promise<ReadResults["status"]>;
    query: <O extends CheckpointAgentOperation>(operation: O, params: unknown) => Promise<ReadResults[O]>;
    guidance: () => Promise<"" | "Local file history is enabled for this session and records automatically before and after each turn. Use mcp__happy__checkpoint_status to check current availability, checkpoint_list to find records, checkpoint_preview to find changed files, and checkpoint_diff for read-only current-to-record comparisons when diagnosing changes or proposing a rollback. History may exclude files and returned pages/diffs may be truncated; inspect the response metadata. Restoring files requires the Desktop preview and the user’s explicit confirmation; these tools do not restore or create records.">;
};
type CheckpointAgentReader = ReturnType<typeof createCheckpointAgentReader>;

type CheckpointLocalHistoryTurn = {
    operationId: string;
    checkpointId: string;
    /** The folder the provider works in: the original one, never a copy. */
    providerPath: string;
};
type CheckpointLocalHistory = {
    /** The dispatch gate: records the folder and acknowledges the event before the turn may run. */
    beforeTurn(): Promise<CheckpointLocalHistoryTurn>;
    /** Records what the turn left, so a later restore can tell its changes from anyone else's. */
    afterTurn(): Promise<void>;
};

/** The isolated-turn apply outcome providers still type against; local history never produces one. */
type CheckpointTurnApplyResult = {
    status: 'completed' | 'partial';
};
type CheckpointTurnPreparation = {
    operationId: string;
    checkpointId: string;
    providerPath: string;
    sandboxConfig?: SandboxConfig;
    claudeSandbox?: QueryOptions['sandbox'];
};
type CheckpointSessionComposition = {
    agentReader?: CheckpointAgentReader;
    sandboxConfig: SandboxConfig | undefined;
    /** specs/checkpoint-local-history — turn-boundary records of the original folder. */
    localHistory?: CheckpointLocalHistory;
    providerPath?: string;
    beforeTurn?: () => Promise<CheckpointTurnPreparation>;
    completeTurn?: (quiesceWriters: () => Promise<void>) => Promise<CheckpointTurnApplyResult>;
    protectedBashCwd?: () => string | null;
    trackProtectedWriter?: (child: ChildProcess) => void;
    /** Removes a reserved-but-unused provider workspace; an active turn is left untouched. */
    dispose?: () => Promise<void>;
    /** Discards a turn that was opened but never dispatched, then rotates to a fresh workspace. */
    abortTurn?: () => Promise<void>;
    /** Marks the open turn as sent to the provider: its result is no longer discardable. */
    markTurnDispatched?: () => void;
    claudeSandbox?: QueryOptions['sandbox'];
};

/**
 * Whether this run's Claude login is one the organisation deployed — as far as
 * a run can **observe** it.
 *
 * The daemon cannot tell an organisation bundle from any other login on the
 * machine (both are just "the CLI's own login"), so it writes `unknown`. The
 * run itself can ask Claude Code which account it loaded (`accountInfo()`) and
 * compare that with what the daemon recorded when it applied the bundle
 * (`~/.happy/ai-credential-provenance.json`, fenced by the apply generation).
 *
 * That is still an observation, not proof that each request was billed to that
 * account: Claude Code reads its token and its account metadata from different
 * places, and the metadata can outlive a token swap. So the result is its own
 * source, `org-bundle-observed`, never `org-bundle` — that one stays reserved
 * for a spawn the daemon isolated to the bundle itself. And it travels
 * in-process to the usage events only; it must never reach
 * `HAPPY_AI_AUTH_SOURCE`, which is what approves an explicit selection.
 *
 * Every doubt resolves to "not observed", which reports `unknown`.
 */

declare const ORG_BUNDLE_OBSERVED = "org-bundle-observed";
type ObservedAiAuthSource = typeof ORG_BUNDLE_OBSERVED;

type ClaudeTurnLatencyInput = {
    attribution: 'exclusive' | 'coalesced';
    inputCount: number;
    traces: Array<{
        id: string;
        receivedAt: number;
        queueMs: number;
    }>;
};
type PreparationSpan = {
    stage: 'mcp-grant' | 'mcp-fetch' | 'mcp-compare' | 'mcp-apply' | 'mcp-sync' | 'before-turn' | 'mcp-recovery' | 'lesson-recall' | 'lesson-proposal';
    durationMs: number | null;
    outcome: 'resolved' | 'rejected';
};
type ClaudeTurnLatencyDiagnostic = {
    version: 1;
    type: 'turn-latency';
    id: string;
    attribution: ClaudeTurnLatencyInput['attribution'];
    inputCount: number;
    queueMs: number;
    sdkSubmitMs: number;
    firstSdkTextMs: number | null;
    outcome: 'text' | 'no-text';
    preparation?: PreparationSpan[];
};

type CodexLatencyStage = 'auth' | 'checkpoint' | 'mcp-sync' | 'thread-resume' | 'thread-start' | 'mcp-recovery' | 'mcp-inventory' | 'mcp-inventory-server' | 'mcp-reconnect' | 'mcp-backoff' | 'mcp-verification' | 'mcp-status' | 'images' | 'lesson-recall' | 'lesson-proposal';
type CodexLatencyPhase = 'received' | 'preparing' | 'submitted' | 'text' | 'completed' | 'failed' | 'cancelled' | 'control';
type CodexTurnLatencyProgress = {
    version: 1;
    type: 'turn-latency-progress';
    id: string;
    attribution: 'exclusive' | 'coalesced';
    inputCount: number;
    queueMs: number | null;
    sdkSubmitMs: number | null;
    firstSdkTextMs: number | null;
    firstActivityMs: number | null;
    elapsedMs: number | null;
    phase: CodexLatencyPhase;
    preparation: Array<{
        stage: CodexLatencyStage;
        startedMs: number | null;
        durationMs: number | null;
        outcome: 'pending' | 'resolved' | 'rejected';
    }>;
    droppedSpans: number;
    clockFailures: number;
    sequence: number;
};

/**
 * Generic RPC handler manager for session and machine clients
 * Manages RPC method registration, encryption/decryption, and handler execution
 */

declare class RpcHandlerManager {
    private handlers;
    private customerBound;
    /** Methods that remember their nonces apart, so their volume cannot refuse other bound requests. */
    private ownNonceGuards;
    private readonly scopePrefix;
    private readonly encryptionKey;
    private readonly encryptionVariant;
    private readonly serverLane;
    private delegationLane;
    /** Apart from the customer guards, so a linked machine's volume cannot refuse this machine's owner. */
    private readonly delegationNonceGuard;
    private readonly requireBoundRequests;
    private readonly nonceGuard;
    private readonly customerBoundNonceGuard;
    private readonly maxBoundRequestsInWindow;
    private readonly logger;
    private socket;
    /**
     * When set, only these methods are dispatched. Enforced here rather than at
     * registration so a handler registered later — or one this class gains in a
     * future change — cannot become a bypass simply by existing.
     * Null on every BYOS machine, which leaves dispatch exactly as it was.
     */
    private methodPolicy;
    private managedAllowlist;
    constructor(config: RpcHandlerConfig);
    /**
     * Register an RPC handler for a specific method
     * @param method - The method name (without prefix)
     * @param handler - The handler function
     */
    registerHandler<TRequest = any, TResponse = any>(method: string, handler: RpcHandler<TRequest, TResponse>, policy?: {
        customerBound?: boolean;
        ownNonceBudget?: boolean;
    }): void;
    /**
     * Restricts dispatch to `methods`. Irreversible for the life of the
     * manager: a managed runtime never returns to the unrestricted surface.
     */
    setManagedAllowlist(methods: readonly string[]): void;
    /**
     * Opens the delegation lane once the daemon has its link store. Never closed again for the life
     * of the manager; revoking a link empties `links` instead.
     */
    setDelegationLane(lane: DelegationLaneConfig): void;
    /** Internal host policy, independent of managed identity and enforced for late registrations too. */
    setMethodPolicy(policy: (method: string) => {
        error: string;
        code: string;
    } | null): void;
    /** Registered method names without the machine scope prefix. */
    listMethods(): string[];
    unregisterHandler(method: string): void;
    /**
     * Handle an incoming RPC request
     * @param request - The RPC request data
     * @param callback - The response callback
     */
    handleRequest(request: RpcRequest): Promise<any>;
    private executeRequest;
    /** Opens params with the scope key, then the server lane key, then each link key; null when none does. */
    private openParams;
    onSocketConnect(socket: Socket): void;
    onSocketDisconnect(): void;
    /**
     * Get the number of registered handlers
     */
    getHandlerCount(): number;
    /**
     * Check if a handler is registered
     * @param method - The method name (without prefix)
     */
    hasHandler(method: string): boolean;
    /**
     * Clear all handlers
     */
    clearHandlers(): void;
    /**
     * Get the prefixed method name
     * @param method - The method name
     */
    private getPrefixedMethod;
}

/**
 * Daemon-specific types (not related to API/server communication)
 */

interface SessionEncryptionData {
    encryptionKey: Uint8Array;
    encryptionVariant: 'legacy' | 'dataKey';
    seq: number;
    metadataVersion: number;
    agentStateVersion: number;
}
interface SessionRuntimeState {
    /** Monotonic sequence assigned by the session process to reject delayed reports. */
    reportSeq?: number;
    thinking: boolean;
    hasOpenToolCall: boolean;
    /**
     * True while the agent is blocked waiting on the user (AskUserQuestion or a
     * permission prompt). This is the opposite of idle, but historically the CLI
     * reports such a session as `thinking: false`, so the idle guard needs it as
     * a dedicated signal to avoid reaping a session that is waiting on a human.
     */
    pendingUserInput?: boolean;
    /**
     * Last time a user-originated action was observed for this session (a new
     * prompt starting a turn, or an AskUserQuestion being answered). Absent until
     * the first user interaction is seen. Unlike `updatedAt` this is not a
     * liveness/keep-alive timestamp — it only advances on real user activity.
     */
    lastUserInteractionAt?: number;
    /**
     * Last time the agent finished a turn and went fully idle (busy → not
     * thinking / no open tool call / not waiting on the user). Marks a safe
     * reclamation point — there is no in-flight work to lose — so the reaper can
     * clean a done-and-idle conversation well before the multi-day absolute cut.
     */
    lastTurnEndAt?: number;
    /** Cumulative assistant turns reported by this session process. */
    assistantTurns?: number;
    /** Cumulative provider-neutral billable tokens reported by this session process. */
    providerTokens?: number;
    /**
     * True once this conversation has launched a background job (e.g. a Bash tool
     * call with run_in_background). Such a session may look idle at turn end while
     * its detached work is still running, so it is exempted from the aggressive
     * turn-end reap and falls back to the conservative absolute idle cut.
     */
    launchedBackgroundJob?: boolean;
    /**
     * Last message seq the session process delivered to its agent loop. A resume
     * uses this as the skip baseline so messages that arrived while the session
     * had no process are replayed instead of being swallowed by the server-head
     * baseline. Absent for sessions running an older CLI.
     */
    lastProcessedSeq?: number;
    /** 'local' = a terminal is attached to this session; 'remote' = app-driven. */
    mode?: 'local' | 'remote';
    updatedAt: number;
}
/**
 * Session tracking for daemon
 */
interface TrackedSession {
    startedBy: 'daemon' | string;
    /** Absolute launch cwd, persisted before the session-start webhook arrives. */
    directory?: string;
    happySessionId?: string;
    /**
     * Session this child was spawned to resume. Unlike `happySessionId` it is set
     * at spawn time, so the resume guard can see that a child is already attached
     * during the window before the session webhook arrives — a window the spawn's
     * 60s webhook timeout ends without killing the child (2026-09-11 incident).
     */
    resumeTargetSessionId?: string;
    happySessionMetadataFromLocalWebhook?: Metadata;
    runtime?: SessionRuntimeState;
    encryption?: SessionEncryptionData;
    pid: number;
    childProcess?: ChildProcess$1;
    error?: string;
    directoryCreated?: boolean;
    message?: string;
    /**
     * Resume skip-baseline restored from disk after a daemon restart. While the
     * session's own child is alive, `runtime.lastProcessedSeq` is the
     * authoritative value; this field only carries it across daemon restarts for
     * sessions preserved on disk (runtime is deliberately not fabricated for
     * those — the idle guard's stale-runtime protection depends on its absence).
     */
    persistedLastProcessedSeq?: number;
    /** tmux session identifier (format: session:window) */
    tmuxSessionId?: string;
    /**
     * Absolute path to a tmp HAPPY_HOME_DIR staged for this session's child
     * process. Present only when the spawn request carried per-user Happy
     * credentials. The daemon removes this directory when the child exits or
     * sweeps it on next startup if cleanup was missed.
     */
    userHomeDir?: string;
    /** Per-session capability restored only when this daemon resumes the child. */
    agentEnvironment?: SaycodeAgentEnvironment;
    /**
     * The managed account this daemon handed an unbound shared-PC session at spawn, moved by an account switch
     * (Saycode specs/shared-pc-session-account-continuation). Kept in the daemon state file; a resume records it afresh.
     */
    sharedSetupTokenAccount?: string;
    /** Accounts this daemon moved that session off, oldest first: a session that missed a move still names one. */
    sharedSetupTokenAccountsLeft?: string[];
    /** Persistent file consumed only after the first explicit user turn is accepted. */
    deferredContinuationContextFile?: string;
}

/**
 * Serializes the latest server-owned session metadata for a single daemon
 * resume spawn. The payload is local-only and covered by the reconnect lineage
 * environment scrub, so it cannot leak into unrelated child sessions.
 */

interface ReconnectSessionEnvironment {
    HAPPY_RECONNECT_SESSION_ID: string;
    HAPPY_RECONNECT_ENCRYPTION_KEY: string;
    HAPPY_RECONNECT_ENCRYPTION_VARIANT: 'legacy' | 'dataKey';
    HAPPY_RECONNECT_SNAPSHOT: string;
}

type AgentPlanSpawnParam = {
    grantEnvelope: string;
};

/**
 * Local observation of whether a managed child's process group is still there.
 *
 * This module reports evidence and never a verdict. A child can call `setsid`
 * and leave the group, so an empty group says only "nothing of it is visible
 * from here" — not that nothing survived. Proving that requires cgroup
 * emptiness or a provider stop, and T09 owns both. `onChildExited` and a dead
 * leader pid are equally weak: the leader can exit while its children keep
 * writing to the workspace.
 *
 * Signal failures are classified, never swallowed. `EPERM` in particular means
 * the target is alive but owned by another uid — which is the normal case once
 * agents run under their own uid — and reading it as "gone" would let a new
 * writable generation open on top of a live writer.
 *
 * Nothing here terminates anything. A persisted pid is a number the kernel may
 * have reused, so it can support an observation but never authority to kill;
 * stopping a managed child belongs to the privileged launch backend.
 */
type ProcessGroupEvidence = 
/** Nothing from this group is visible here. Not proof that nothing runs. */
{
    kind: 'no-local-trace';
} | {
    kind: 'alive';
}
/** Alive, but this daemon may not signal it (different uid). */
 | {
    kind: 'alive-foreign';
}
/** The signal failed for a reason we cannot interpret. Never "gone". */
 | {
    kind: 'indeterminate';
    detail: string;
};
type ProcessGroupDeps = {
    /** Negative pid targets the whole group; that is the point of this module. */
    kill: (target: number, signal: NodeJS.Signals | 0) => void;
    sleep: (ms: number) => Promise<void>;
    now: () => number;
};

interface TypedMachineRunHandlerOptions {
    /** Override the platform in tests or an embedding host. */
    platform?: NodeJS.Platform;
    /** Environment owned by the adapter. Defaults to PATH only. */
    baseEnvironment?: Record<string, string>;
    /** A trusted profile may render its workspace root as an absolute argv value. */
    allowAbsoluteArguments?: boolean;
    /** A trusted structured profile may pass shell-looking text as argv data (shell remains false). */
    allowStructuredArguments?: boolean;
    /** Host-owned workspace admission, completed before any process is submitted. */
    admitSubprocess?: (roots: readonly string[]) => Promise<void>;
}

/**
 * Host-owned tools a machine.run profile may execute. The daemon downloads a
 * pinned release artifact itself, so an extension never chooses what binary
 * lands on the machine, and a profile for a managed tool runs only that
 * verified binary — never whatever happens to be on PATH.
 */
type ManagedMachineToolPlatform = 'darwin-arm64' | 'linux-x64';
interface ManagedMachineToolArtifact {
    /** A first-party GitHub release asset (.tar.gz). */
    url: string;
    /** SHA-256 of the downloaded archive. */
    sha256: string;
    /** Single top-level directory every archive entry must live under. */
    archiveRoot: string;
    /** SHA-256 of the extracted executable, re-checked before every run. */
    executableSha256: string;
}
interface ManagedMachineTool {
    id: string;
    version: string;
    /** Command name a profile uses; also the executable's file name in the archive root. */
    executable: string;
    artifacts: Partial<Record<ManagedMachineToolPlatform, ManagedMachineToolArtifact>>;
}

type MachineRunParameter = {
    type: 'string';
    maxLength: number;
    values?: string[];
} | {
    type: 'integer';
    min: number;
    max: number;
};
interface MachineRunProfile {
    id: string;
    executable: string;
    argv: string[];
    parameters: Record<string, MachineRunParameter>;
    cwd: 'workspaceRoot' | 'extensionData' | 'temp';
    envAllowlist: string[];
    timeoutMs: number;
    outputLimitBytes: number;
    stdin: 'none';
    writeScope?: 'none' | 'moai' | 'project';
    descendantAllowlist?: string[];
}
/** A profile after the daemon has validated and sealed its host-owned identity. */
interface TrustedMachineRunProfile extends MachineRunProfile {
    profileDigest: string;
}
interface MachineRunProfileResolver {
    resolve(profileId: string): TrustedMachineRunProfile | undefined;
    list(): readonly TrustedMachineRunProfile[];
}
/**
 * A profile resolver is the daemon's trust boundary. Extension input must not
 * be used to populate it at runtime; only a host-owned registry may do that.
 */
type TrustedMachineRunProfileRegistry = MachineRunProfileResolver;
interface MachineRunManagedTools {
    root: string;
    tools: readonly ManagedMachineTool[];
    /** Defaults to the daemon's own platform and architecture. */
    platform?: ManagedMachineToolPlatform | null;
}
interface MachineRunWriteScopePolicy {
    /** Validate the resolved workspace and reserve it for one active operation. */
    acquire(input: {
        profile: TrustedMachineRunProfile;
        workspaceRoot: string;
    }): Promise<() => void>;
}

type LaunchMcpServer = {
    transport: 'stdio';
    command: string;
    args?: string[];
    env?: Record<string, string>;
} | {
    transport: 'http';
    url: string;
    headers?: Record<string, string>;
};
type LaunchMcpDropReason = 'name-conflict' | 'invalid' | 'unsupported-agent';
type LaunchMcpDropped = {
    name: string;
    reason: LaunchMcpDropReason;
};
/** The request after the RPC boundary: the entries that passed validation and the ones that did not. */
type LaunchMcpRequest = {
    servers: Record<string, LaunchMcpServer>;
    dropped: LaunchMcpDropped[];
};

interface SpawnSessionOptions {
    machineId?: string;
    directory: string;
    sessionId?: string;
    approvedNewDirectoryCreation?: boolean;
    agent?: 'claude' | 'codex' | 'gemini' | 'grok' | 'openclaw' | 'opencode';
    /**
     * Initial model/effort seed for the spawned agent, delivered via
     * HAPPY_INITIAL_MODEL / HAPPY_INITIAL_EFFORT (per-spawn lineage envs,
     * scrubbed like HAPPY_INITIAL_PROMPT) and consumed exactly once by the
     * agent startup path. Invalid effort values are ignored by the agent.
     */
    model?: string;
    effort?: string;
    environmentVariables?: Record<string, string>;
    /** Internal RPC adapter choice; seed and record a missing root grant at the daemon environment boundary. */
    seedDefaultAgentGrant?: boolean;
    /** Existing, daemon-canonicalized read-write roots mounted for this session. */
    additionalDirectories?: string[];
    /** OAuth token for the agent CLI (e.g. CLAUDE_CODE_OAUTH_TOKEN). */
    token?: string;
    /**
     * Happy server auth credentials of the requesting user. When present, the
     * daemon writes them to a per-spawn access.key so the child CLI attributes
     * its session to that user instead of the daemon.
     */
    happyToken?: string;
    happySecret?: string;
    /**
     * Opaque caller grant encrypted to this daemon process's ephemeral public
     * key. The shared RPC layer may expose the envelope to company members, so
     * plaintext grants and personal Happy credentials must never replace it.
     */
    mcpCallerGrantEnvelope?: string;
    /** Project scope appended only to the daemon-owned MCP config URL. */
    mcpConfigProjectId?: string;
    personalChatId?: string;
    /** Connected provider names expected in the child MCP topology. */
    expectedConnectors?: string[];
    /**
     * If set, the daemon spawns the agent with `--resume <id>` so the new
     * Happy session continues from an existing Claude conversation file.
     * Used by the session fork / duplicate flow: the fork RPC produces a
     * new Claude JSONL on disk, the spawn RPC then attaches a fresh Happy
     * session to it.
     */
    resumeClaudeSessionId?: string;
    /**
     * If set, the daemon spawns Codex with `--resume <id>` so a fresh Happy
     * session attaches to a forked Codex app-server thread.
     */
    resumeCodexThreadId?: string;
    /** Prior transcript context applied to the first explicit user turn only. */
    deferredContinuationContext?: string;
    /**
     * The managed Cloud spawn envelope (specs/managed-cloud-byos §5.33).
     *
     * Accepted only from a verified managed dispatch on a runtime whose own
     * identity is active; a caller cannot turn managed mode on by supplying
     * this, and supplying it does not relax any of the ordinary guards.
     */
    bootstrap?: unknown;
    gateway?: unknown;
    /** Happy session id this fork was branched from (lineage). */
    parentSessionId?: string;
    /** Happy message id used as the rewind point (only set for "duplicate"). */
    forkedFromMessageId?: string;
    /**
     * Identity of the account that requested this spawn, as known by the
     * client (e.g. the desktop app). Threaded into the new session's
     * metadata as `createdBy` so shared-account orgs can approximate "my
     * conversations" (specs/session-created-by). Not lineage — re-supplied
     * on every spawn, never inherited from a previous process's env.
     */
    createdByAccountId?: string;
    createdByDisplayName?: string;
    /**
     * The linked machine and its session that asked for this one (aplus-dev-studio
     * specs/cross-machine-agent-delegation R9), recorded as metadata `delegatedFrom`. Set only by the
     * daemon's delegated spawn, never from a request. Not lineage — re-supplied on every spawn.
     */
    delegatedFrom?: {
        machineId: string;
        sessionId: string;
    };
    /** Who asked for this session, recorded as metadata `source` (see SessionSource). Not lineage. */
    sessionSource?: SessionSource;
    axStep?: 'plan' | 'design' | 'free';
    bootstrapFiles?: Array<{
        relativePath: string;
        content: string;
    }>;
    /**
     * First user prompt for the spawned session. Delivered via
     * HAPPY_INITIAL_PROMPT (a per-spawn lineage env, scrubbed like
     * HAPPY_FORK*) and consumed exactly once by supported agent startup
     * paths so the agent starts its first turn without waiting for app input.
     * Used by scheduled automations.
     */
    initialPrompt?: string;
    /** Web optimistic message id preserved on the initial prompt server row. */
    initialPromptLocalId?: string;
    /** User/project/operational prompt preserved for an atomically delivered first turn. */
    appendSystemPrompt?: string;
    /** Saycode-owned prompt policy applied to an atomically delivered initial prompt. */
    saycodeSystemPromptEnabled?: boolean;
    /** Per-block Saycode overrides seeded into the spawned session's first turn. */
    saycodePromptBlocks?: Record<string, boolean>;
    /** Exit cleanly after the spawned agent completes its first turn. */
    exitAfterFirstTurn?: boolean;
    /**
     * Run-once only: the host keeps the session parked while an Agent Browser task waits for the user
     * (Studio Chat(beta)), so the agent is told the chat continues after the console action.
     */
    browserContinuation?: boolean;
    /**
     * Shared Agent Browser machines: Studio's signed statement of who started this new chat (abp2
     * session-user). The daemon hands it to the Runtime broker only (never to the child's env); the broker
     * verifies it and binds the session to that user's browser profile.
     */
    browserAttestation?: string;
    /**
     * Internal only. Set by the daemon's managed dispatch wrapper, never read
     * from RPC params — a caller that supplied it would be choosing its own
     * delivery guarantees. Turns on confirmed delivery of the initial prompt
     * and nothing else; it conveys no identity or permission.
     */
    requireInitialPromptAck?: boolean;
    /**
     * Internal only. Attaches the child to a session the daemon already created (the channel host
     * spawn), with the key the daemon sealed it with — the same HAPPY_RECONNECT_* handoff a resume
     * uses. Never read from RPC params: `spawn-happy-session` names its fields, and a caller that
     * could set this would point a new child at somebody else's session.
     */
    reconnectEnvironment?: ReconnectSessionEnvironment;
    /** Remove inherited daemon credentials before applying the explicit spawn environment. */
    filterInheritedCredentials?: boolean;
    /** Restrict an unattended automation session to repository reads. */
    permissionMode?: PermissionMode;
    /**
     * Which credential the requester explicitly chose for this spawn.
     *
     * Only sent by a client that saw the daemon advertise
     * `MachineMetadata.aiAuthSelection`. Absent means "whatever the machine
     * would have used", which is the behaviour that predates the choice.
     */
    aiAuthSelection?: AiAuthSelection;
    /**
     * aplus specs/org-agent-plan §6.3-2 — the organization agent plan grant, sealed to this machine. Only sent
     * to a daemon advertising `MachineMetadata.agentPlan`, for Codex, never together with `aiAuthSelection`.
     */
    agentPlan?: AgentPlanSpawnParam;
    /** Session-scoped Claude structured output, validated at the RPC boundary (specs/claude-cli-benchmark-followups R2). */
    outputFormat?: ClaudeOutputFormat;
    /**
     * MCP servers a Desktop extension adds to this launch, checked at the RPC boundary
     * (aplus/launchMcpServers.ts). Only sent to a daemon advertising `daemonState.launchMcpServers`.
     */
    launchMcpServers?: LaunchMcpRequest;
}
type SpawnSessionResult = {
    type: 'success';
    sessionId: string;
    /**
     * Which credential the daemon actually applied, as the usage ledger
     * names it. Reported so a requester can tell what ran from what it
     * asked for; `unknown` is an answer, not a missing value.
     */
    appliedAiAuthSource?: AiAuthSource;
    personalLlmEndpoint?: PersonalEndpointMarker;
    /**
     * aplus specs/org-llm-endpoints C5 — the endpoint target the daemon actually pointed the session at,
     * present only for an `org-endpoint` selection. Studio records it as the session's URL binding.
     */
    appliedOrgLlmEndpoint?: {
        bindingId: string;
        targetId: string;
    };
    additionalDirectories?: {
        version: 1;
        accepted: string[];
        skipped: Partial<Record<'missing' | 'not-directory' | 'canonicalize-failed' | 'duplicate' | 'primary', number>>;
    };
    /** `launchMcpServers` entries this launch did not add, by name and reason. Absent when none. */
    launchMcpDropped?: LaunchMcpDropped[];
} | {
    type: 'requestToApproveDirectoryCreation';
    directory: string;
} | {
    type: 'error';
    errorMessage: string;
    /**
     * Machine-readable refusal. `daemon-restarting` (aplus codexcli-daemon-restart-drain R1·R6):
     * refused before anything ran, retryable once the daemon is back — `deadlineAt` (epoch ms)
     * is when the drain ends at the latest.
     */
    code?: string;
    deadlineAt?: number;
};
type ResumeSessionErrorCode = 
/** aplus codexcli-daemon-restart-drain R1 — refused before anything ran; retry after the restart. */
'daemon-restarting' | 'SESSION_LIVE' | 'SESSION_NOT_TRACKED' | 'SESSION_METADATA_MISSING' | 'SESSION_ENCRYPTION_MISSING' | 'SESSION_IDENTITY_MISMATCH' | 'SESSION_CURSOR_MISSING' | 'SESSION_SERVER_UNAVAILABLE' | 'SESSION_ALIVE_ELSEWHERE' | 'SESSION_DIRECTORY_MISMATCH' | 'SESSION_DIRECTORY_MISSING' | 'SESSION_NATIVE_SESSION_MISSING' | 'MCP_CALLER_GRANT_REJECTED'
/**
 * Saycode specs/claude-org-personal-coexistence I — the recorded binding cannot vouch for the process this resume would
 * use: no record of the required organization, another organization, or a live child. Nothing ran.
 */
 | 'CLAUDE_ORGANIZATION_RESUME_REQUIRED' | 'SESSION_RESUME_FAILED';
type ResumeSessionResult = {
    type: 'success';
    sessionId: string;
    launchMcpDropped?: LaunchMcpDropped[];
} | {
    type: 'requestToApproveDirectoryCreation';
    directory: string;
} | {
    type: 'error';
    code: ResumeSessionErrorCode;
    errorMessage: string;
    /** With `daemon-restarting`: when the drain ends at the latest (epoch ms). */
    deadlineAt?: number;
};
type RecoverSessionOptions = {
    initialPrompt: string;
    initialPromptLocalId?: string;
    appendSystemPrompt?: string;
    saycodeSystemPromptEnabled?: boolean;
    /** Per-block Saycode overrides for the recovered first turn (sanitized at the RPC boundary). */
    saycodePromptBlocks?: Record<string, boolean>;
    environmentVariables?: Record<string, string>;
    model?: string;
    permissionMode?: PermissionMode;
    mcpCallerGrantEnvelope?: string;
    mcpConfigProjectId?: string;
    expectedConnectors?: string[];
};
type RecoverSessionResult = {
    type: 'success';
    sessionId: string;
    previousSessionId: string;
    recovery: 'same-session' | 'new-session';
    initialPromptDelivered: boolean;
} | {
    type: 'error';
    code: ResumeSessionErrorCode;
    errorMessage: string;
};
/**
 * Register all RPC handlers with the session
 */
interface CommonHandlerOptions {
    /**
     * Where `bash` RPC commands sit relative to this scope's session: `in-session` for a
     * session's own handlers, `session` (default) for the machine scope (utils/childEnv).
     */
    childEnvBoundary?: ChildEnvBoundary;
    /** Internal run sessions have no interactive process RPC producer. Host-only, never RPC input. */
    processExecution?: 'disabled';
    /** Host-owned operation admission; never populated from RPC input. */
    withFilesystemMutation?: <T>(operation: () => Promise<T>) => Promise<T>;
    /** Persist an unknown process writer before submission; host-only, never an RPC field. */
    admitSubprocess?: TypedMachineRunHandlerOptions['admitSubprocess'];
    machineRun?: {
        /** Host-owned immutable registry. Extension input must never populate this. */
        profileRegistry: TrustedMachineRunProfileRegistry;
        extensionDataDirectory?: string;
        tempDirectory?: string;
        environment?: NodeJS.ProcessEnv;
        platform?: NodeJS.Platform;
        /** Explicit internal compatibility escape hatch; never enabled for extension RPCs. */
        allowLegacyRaw?: boolean;
        /** Host-owned write policy. Without it, write profiles are neither advertised nor run. */
        writeScopePolicy?: MachineRunWriteScopePolicy;
        /** Host-owned pinned tools; their profiles run only the verified install. */
        managedTools?: MachineRunManagedTools;
        /** Only the machine scope downloads and installs managed tools. */
        allowToolInstall?: boolean;
    };
    /** Tests lower it; production uses DIRECTORY_TREE_MAX_ENTRIES. */
    directoryTreeMaxEntries?: number;
    /**
     * Folders outside `workingDirectory` the machine owner approved (modules/common/approvedFolders),
     * asked on every check so an approval or revocation applies at once. Machine scope only.
     */
    approvedRoots?: () => readonly string[];
}

interface ProviderUsageStore {
    load(): ProviderUsageEventV1[];
    put(event: ProviderUsageEventV1): void;
    remove(sourceEventId: string): void;
}

/** Encrypted session-stream display data only; never a credential or selection command. */
type ClaudeRuntimeAccount = {
    type: 'runtime-account';
    version: 1 | 2;
    personalFallbackSupported?: true;
    personalFallbackGeneration?: number;
    sessionId: string;
    provider: 'claude';
    epoch: string;
    seq: number;
    observedAt: number;
} & ({
    kind: 'unknown';
} | {
    kind: 'personal';
    companyId: string;
    machineId: string;
    accountRef: string;
    label: string;
} | {
    kind: 'organization';
    companyId: string;
    machineId: string;
    managedAccountId: string;
    credentialGeneration: number;
});
declare class ClaudeRuntimeAccountPublisher {
    private readonly sessionId;
    private readonly emit;
    private readonly epoch;
    private current;
    private timer;
    constructor(sessionId: () => string, emit: (frame: ClaudeRuntimeAccount) => void);
    /** Called with the binding captured by the provider that actually started, never a future choice. */
    update(rawBinding: string | undefined, fallback?: {
        companyId: string;
        machineId: string;
        generation: number;
        personal: {
            accountRef: string;
            label: string;
        } | null;
    }): void;
    /** Repeat the whole state for late viewers and lost volatile frames; ordering is unchanged. */
    resend(): void;
    dispose(): void;
}

/** The SDK `Query` control request (`sideQuestionRequestOf`): resolves to the control_response body. */
type ClaudeControlRequest = (body: Record<string, unknown>, options: {
    signal: AbortSignal;
}) => Promise<unknown>;
/**
 * The transcript signals the tracker needs, as an `OutgoingMessageQueue` item: the queue drops
 * every `system` log message, and these must still land after the responses queued before them.
 * A turn result's breakdown request rides it too: a `compact_boundary` still waiting in the queue
 * would otherwise clear the answer to a request made after it.
 */
type ClaudeContextUsageSignal = {
    kind: 'provider-model';
    model: unknown;
} | {
    kind: 'compact-boundary';
} | {
    kind: 'breakdown-request';
    request: ClaudeControlRequest;
};

/**
 * ACP (Agent Communication Protocol) message data types.
 * This is the unified format for all agent messages - CLI adapts each provider's format to ACP.
 */
type ACPMessageData = {
    type: 'message';
    message: string;
    setupTokenRotation?: {
        version: 1;
        state: SetupTokenRotationState;
    };
} | {
    type: 'reasoning';
    message: string;
} | {
    type: 'thinking';
    text: string;
} | {
    type: 'tool-call';
    callId: string;
    name: string;
    input: unknown;
    id: string;
} | {
    type: 'tool-result';
    callId: string;
    output: unknown;
    id: string;
    isError?: boolean;
} | {
    type: 'file-edit';
    description: string;
    filePath: string;
    diff?: string;
    oldContent?: string;
    newContent?: string;
    id: string;
} | {
    type: 'terminal-output';
    data: string;
    callId: string;
} | {
    type: 'task_started';
    id: string;
} | {
    type: 'task_complete';
    id: string;
} | {
    type: 'turn_aborted';
    id: string;
} | {
    type: 'permission-request';
    permissionId: string;
    toolName: string;
    description: string;
    options?: unknown;
} | {
    type: 'token_count';
    [key: string]: unknown;
};
/**
 * Outcome of waiting for one message to be durably acknowledged.
 *
 * `ok: false` means the acknowledgement was not observed — **not** that the
 * message was lost. A 2xx whose body omits our row leaves durability unknown,
 * and a caller must treat it as "do not proceed", never as "it is gone".
 */
type MessageAckOutcome = {
    ok: true;
    id: string;
    seq: number;
} | {
    ok: false;
    reason: 'deadline' | 'closed' | 'sync-failed' | 'contradictory-ack';
};
type LocalImageAttachment = {
    data: Uint8Array;
    mimeType: string;
    name: string;
};
/**
 * How the usage on a Claude assistant row is treated.
 * - `final`: the row carries the usage its response ended on (a transcript line) — metered now.
 * - `streaming`: handed over by the SDK stream before its response ended — metered once the
 *   stream ends it (src/usage/claudeStreamedUsage.ts).
 * - `historical`: replayed history — never metered.
 */
type ClaudeMessageUsage = 'final' | 'streaming' | 'historical';
/**
 * The managed relay contract, as the child must enforce it.
 *
 * `serverOrigin` is the exact origin every managed attachment URL must be on.
 * A scoped bearer is only ever sent there, and never through a redirect.
 */
type ManagedCredentialMode = {
    serverOrigin: string;
};
interface ApiSessionClientOptions {
    providerUsageStore?: ProviderUsageStore;
    trackShutdownStorage?: boolean;
    storageHighWaterBytes?: number;
    storageHighWaterWrites?: number;
    /** Live host dependency; never part of a session snapshot or RPC payload. */
    withFilesystemMutation?: CommonHandlerOptions['withFilesystemMutation'];
    admitSubprocess?: CommonHandlerOptions['admitSubprocess'];
}
declare class ApiSessionClient extends EventEmitter {
    private readonly options;
    private readonly token;
    readonly sessionId: string;
    /**
     * Identity of *this process's* attachment to the session, minted per client instance
     * (Saycode specs/desktop-messenger-channels).
     *
     * A caller that proved a runtime's capability names it when it later hands that runtime work.
     * If the process has been replaced in between — a restart, a downgrade — the id no longer
     * matches and the work is refused instead of being run by a runtime whose capability was
     * never checked. A session id cannot do this job: it survives the process.
     */
    readonly runtimeId: string;
    readonly inputEvidence: TurnInputEvidence;
    readonly inputGate: HubInputGate;
    private inputEvidenceSupported;
    private contactSteer;
    private invalidateGuardedInputs;
    private rejectedInputs;
    private acceptedInputs;
    private readonly inputToolTurns;
    configureInputQueue<T>(queue: MessageQueue2<T>, mode: 'local' | 'remote', evidence: boolean): void;
    setInputMode(mode: 'remote' | 'local' | 'transitioning'): void;
    setInputSteerAvailable(available: boolean): void;
    queueInput(message: UserMessage): QueueInputEvidence;
    admitInput(input: QueueInputEvidence, publishAccepted?: boolean): boolean;
    setPendingInputEvidence(batch: EvidenceBatch | null): void;
    startClaudeInputEvidence(batch: EvidenceBatch): void;
    continueClaudeInputEvidence(kind: Parameters<TurnInputEvidence['continuePending']>[0]): void;
    /** Tool membership, rather than the mutable current turn, binds a permission answer. */
    recordPermissionInput(id: string, tool: string, response: unknown, turn?: string): (state?: 'accepted' | 'rejected' | 'unknown') => void;
    /** Permission prompts waiting for their tool call's turn to be mapped. */
    private readonly pendingChannelPermissionBinds;
    private metadata;
    private metadataVersion;
    private summarySent;
    private agentState;
    private agentStateVersion;
    private socket;
    private pendingMessages;
    private pendingMessageCallback;
    private pendingFileEvents;
    private pendingFileEventCallback;
    private blobKey;
    /**
     * In-flight attachment download promises that belong to the *current*
     * (not-yet-drained) batch. Each promise resolves to the decoded blob (or
     * null on failure), so per-message ownership is intrinsic — there is no
     * shared push-array between batches that a late download could leak into.
     */
    private pendingDownloads;
    readonly rpcHandlerManager: RpcHandlerManager;
    private readonly agentStateWrites;
    private readonly metadataWrites;
    private encryptionKey;
    private encryptionVariant;
    /** 예약된 다음 dial. non-null 이면 재연결 cadence 가 돌고 있다는 뜻이다. */
    private reconnectInterval;
    /** 마지막 성공 연결 이후 연속 dial 횟수. 백오프 계산용. */
    private reconnectAttempts;
    /**
     * 응답을 기다리는 `socket.connect()` 가 발사된 시각. 대기 중인 dial 이 없으면 null.
     *
     * specs/machine-socket-duplicate-registration/ — apiMachine 과 같은 결함이다.
     * 기존 cadence 는 직전 dial 의 성패와 무관하게 3초마다 connect() 를 다시 불렀고,
     * 핸드셰이크가 느린 구간에서 여러 dial 이 겹쳐 성립해 서버가 같은 세션의 소켓을
     * 여러 개 들고 있게 됐다.
     */
    private reconnectDialStartedAt;
    /**
     * close() 로 의도적으로 끝낸 세션인가.
     *
     * 2026-09-05 프로덕션 — 리뷰 워커가 turn 을 끝내고 정리까지 마쳤는데
     * (sendSessionDeath → flush → close → client.disconnect → happyServer.stop)
     * 프로세스가 2시간 11분 살아남았다. close() 의 socket.close() 가 'disconnect'
     * 핸들러를 깨우고, 그 핸들러가 startSmartReconnect() 를 걸어 1초 뒤 소켓이 다시
     * 붙는다. 살아있는 소켓이 이벤트 루프를 붙잡아 run-once 세션이 끝나지 못했고,
     * 그 프로세스가 worktree 를 점유해 그 저장소의 리뷰 큐가 통째로 멈췄다.
     */
    private closed;
    private ignoreArchiveSignal;
    private syncFatalHandled;
    private sessionEndSeqBaseline;
    private hasConnectedOnce;
    private archiveRecheckPending;
    private skipInitialMessages;
    private skipExistingMessagesThroughSeq;
    private skippedInitialMessageSeqs;
    private claudeSessionProtocolState;
    private lastSeq;
    private shutdownReceiveSeq;
    private inputDeliveryDepth;
    private runtimeProcessedSeqCap;
    private pendingOutbox;
    private readonly storageBarrier;
    private unconfirmedOutbox;
    private outboxRequest;
    private outboxInFlightCount;
    private outboxPaused;
    private outboxRetryTimer;
    private outboxRetryDelayMs;
    private stateWritesPaused;
    private stateRetryDelayMs;
    private stateRetryTimer;
    private shutdownStorageDeadline;
    private shutdownStorageFlush;
    private readonly sendSync;
    /**
     * Callers waiting for a specific message to be acknowledged. Registered
     * before the message is enqueued, because a flush can start immediately
     * afterwards and a waiter added later would miss its own acknowledgement.
     */
    private readonly messageAckWaiters;
    private readonly receiveSync;
    private receivePollInterval;
    private receivePollDelayMs;
    private receivePollTicksRemaining;
    private currentThinking;
    private openToolCallIds;
    private openAskUserQuestionIds;
    private openAskUserQuestionTurnIds;
    private lastDaemonRuntimeReport;
    private daemonRuntimeReportSeq;
    private daemonRuntimeReportsInFlight;
    private daemonRuntimeReportOwed;
    private currentMode;
    private lastUserInteractionAt;
    private lastTurnEndAt;
    /** aplus-dev-studio-desktop#2111 — which turn a background process belongs to (see sessionBackgroundProcesses). */
    private readonly turns;
    private assistantTurns;
    private providerTokens;
    private providerUsageEventIds;
    private readonly claudeTurnUsage;
    private readonly claudeStreamedUsage;
    private readonly providerUsageDelivery;
    private readonly runtimeAccount;
    private personalClaudeFallback;
    setPersonalClaudeFallback(value: Parameters<ClaudeRuntimeAccountPublisher['update']>[1]): void;
    setClaudeRuntimeAccount(binding: string | undefined): void;
    private readonly contextUsage;
    private contextUsageResendTimer;
    private contextUsageTakeDownRepeats;
    private lastClaudeTurnResultUuid;
    private inputObservedForNextTurn;
    private launchedBackgroundJob;
    /** The turn answering a daemon-delivered scheduled prompt (Saycode specs/_archive/automation-result-delivery). */
    private readonly automationTurns;
    /** A temporary API failure is waiting to be retried by the engine (specs claude-transient-retry). */
    private transientRetryPending;
    /** The waiting retry was just dispatched, so its turn answers a carried scheduled run. */
    private transientRetryDispatched;
    /**
     * Set only when the caller says so.
     *
     * Never inferred from the shape of the token or the key: a mode guessed
     * from a credential is a mode that changes when the credential format
     * does, and this one decides whether redirects are followed.
     */
    private readonly managed;
    /** The origin this client is allowed to talk to, when it is a managed one. */
    getManagedOrigin(): string | null;
    /**
     * Desktop P0a §4.5 owner-relay-v1 call over the existing rpc-call protocol, sealed with this
     * session's key (T1c-b2 H2). One attempt, 20s deadline; the key and remote errors stay here.
     */
    callOwnerRelay(method: string, request: unknown, signal: AbortSignal): Promise<unknown>;
    constructor(token: string, session: Session, managed?: ManagedCredentialMode, options?: ApiSessionClientOptions);
    /** Pure admission check; accepted async callbacks and turns need their own runtime gate. */
    canFreezeInboundMessagesForShutdown(): boolean;
    /** Permanent for this API instance. Stops durable input, not ACKs, state updates or control RPCs. */
    freezeInboundMessagesForShutdown(): boolean;
    private deliverInput;
    onUserMessage(callback: (data: UserMessage) => void): void;
    onFileEvent(callback: (data: FileEventMessage) => void): void;
    /**
     * Derive (and cache) the blob decryption key for this session.
     * Legacy sessions use deriveKey(masterSecret, 'Happy Blobs', ['master']).
     * DataKey sessions use deriveKey(dataKey, 'Happy Blobs', ['session']).
     */
    getBlobKey(): Promise<Uint8Array>;
    private requestAttachmentUpload;
    private uploadEncryptedAttachmentBlob;
    uploadLocalImageAttachmentEnvelope(attachment: LocalImageAttachment, opts?: Pick<CreateEnvelopeOptions, 'id' | 'time' | 'claudeUuid' | 'codexItemId'>): Promise<SessionEnvelope>;
    /**
     * Download an encrypted attachment blob via the request-download flow:
     * POST /request-download → { downloadUrl } → GET downloadUrl. Local mode
     * downloadUrl points back at our server (Bearer required); S3 mode is a
     * presigned URL that does not accept extra headers.
     */
    downloadAttachment(ref: string): Promise<Uint8Array>;
    /**
     * Download and decrypt an attachment blob.
     * Returns the decrypted binary data or null if decryption fails.
     */
    downloadAndDecryptAttachment(ref: string): Promise<Uint8Array | null>;
    /**
     * Track an attachment download whose promise resolves to the decoded blob
     * (or null on failure). The download stays in the current batch until the
     * next drainAttachmentsForUserMessage call swaps the bucket out — file
     * events that arrive after the swap go into a fresh bucket bound to the
     * next user-text message.
     */
    trackAttachmentDownload(promise: Promise<{
        data: Uint8Array;
        mimeType: string;
        name: string;
    } | null>): void;
    /**
     * Atomically claim every download started before this call, wait for them
     * to resolve, and return the successful ones. The swap-then-await order
     * guarantees that a late-arriving file event cannot leak into this batch.
     */
    drainAttachmentsForUserMessage(): Promise<Array<{
        data: Uint8Array;
        mimeType: string;
        name: string;
    }>>;
    private authHeaders;
    private routeIncomingMessage;
    private fetchMessages;
    private static readonly MAX_OUTBOX_BATCH_SIZE;
    private static readonly RECEIVE_POLL_INTERVAL_MS;
    private startReceivePolling;
    private stopReceivePolling;
    /**
     * A message sync (send/receive) hit a permanently non-retryable error —
     * almost always a 404 after the session was deleted/archived server-side.
     * The InvalidateSync has already stopped itself; tear the whole session down
     * (same path as the archive signal) rather than leaving the process alive
     * with one dead sync direction silently dropping messages.
     */
    private onSyncFatal;
    /**
     * Capture the newest durable session-end event seq at startup. Everything
     * at or below this seq predates this process (previous runs' graceful
     * deaths, an old archive before a resume) and must not trigger an exit.
     * Anything above it appeared while THIS process is alive — and since we
     * only send our own session-end during cleanup, a newer event means an
     * external archive/kill happened while our socket was down.
     * (specs/followups/session-archive-ephemeral-miss.md)
     */
    private initSessionEndBaseline;
    /**
     * After a reconnect, decide whether the session was archived/killed while
     * our socket was down (the transient 'archived' ephemeral would have been
     * missed). A session-end event newer than our baseline says someone ended
     * the session during our lifetime; `active === false` confirms it stayed
     * dead (an active session means it was legitimately revived — e.g. control
     * transfer — and the event is stale). Keepalives are gated via
     * archiveRecheckPending so our own presence pings can't flip active=true
     * back on mid-decision.
     */
    private recheckArchivedWhileDisconnected;
    private flushOutbox;
    /**
     * Waits for one enqueued message to be acknowledged by the server.
     *
     * Register before enqueuing. The returned promise always resolves: an
     * unobserved acknowledgement is an outcome, not an exception, and a
     * rejected promise nobody awaited would surface as an unhandled rejection.
     */
    awaitMessageAck(localId: string, deadlineMs: number): Promise<MessageAckOutcome>;
    private resolveMessageAcks;
    private settleAllMessageAcks;
    private enqueueMessage;
    private enqueueSessionProtocolEnvelopes;
    private reportClaudeAssistantUsage;
    private applyClaudeSessionMessageSideEffects;
    /**
     * Send message to session
     * @param body - Message body (can be MessageContent or raw content for agent messages)
     */
    /**
     * Declares that the next turn to open answers an external messenger request
     * (Saycode specs/desktop-messenger-channels).
     *
     * Called by the launcher at the moment it takes a batch off the queue, which is the only
     * point where "this work" and "that request" are both known. The mapper consumes it on the
     * `turn-start` it stamps, so an id set for a turn that never opens cannot leak onto a later
     * unrelated one. Passing null clears it, which is what an in-app batch does.
     */
    setPendingTurnRequestId(requestId: string | null): void;
    /**
     * Binds a permission prompt to the turn **that contains its tool call**, whenever both facts
     * are known (Saycode specs/desktop-messenger-channels — R9).
     *
     * Order-independent on purpose. The SDK reads the assistant message and the permission
     * `control_request` off one transport loop but puts them on different paths —
     * `handleControlRequest` is dispatched without being awaited, and the message is enqueued into
     * a separate input stream our own loop drains — so either can be observed first. "Which turn
     * is current" would therefore sometimes name the previous turn, and a binding against the
     * previous turn accepts an answer aimed at it while refusing the right one.
     *
     * So this waits for membership rather than reading a moving value: whichever of the two
     * arrives second triggers the bind. Nothing is bound until then, which is the fail-closed
     * direction — an answer arriving early is refused as `unknown-request`.
     */
    bindChannelPermissionWhenKnown(toolCallId: string, apply: (context: {
        turnId: string;
        channelRequestId: string | null;
        runtimeId: string;
    }) => void): void;
    /** Resolves waiters whose tool call has since been mapped to a turn. */
    private drainChannelPermissionBinds;
    /**
     * Publishes the engine's authoritative final answer for an open or pending channel turn
     * (Saycode specs/desktop-messenger-channels — R14).
     *
     * A result with no preceding transcript opens its pending channel turn first. An in-app turn shows its
     * answer in the transcript, and adding a duplicate envelope for it would be noise on every
     * ordinary session. Silently does nothing otherwise, which is why callers can hand it every
     * result without checking first.
     */
    private reportAutomationTurn;
    /**
     * Whether the engine is waiting to retry a temporary API failure by itself. A wait that ends
     * without the retry being dispatched (stopped, replaced, given up) leaves a carried scheduled
     * run with no turn to settle it, so it is settled as the failure it was.
     */
    setTransientRetryPending(pending: boolean): void;
    /**
     * The engine has no input waiting (Claude after a turn with an empty queue, Codex when idle).
     * Until it says so, a scheduled prompt behind other input is not tracked — see AutomationTurnTracker.
     */
    noteInputQueueEmpty(): void;
    /** The waiting retry is being sent now; its turn settles any carried scheduled run. */
    noteTransientRetryDispatched(): void;
    sendFinalAnswerForChannelTurn(text: string): void;
    /** Every later turn of this session closes with a verdict, filled in as `missing` if none came. */
    enableStructuredOutputVerdicts(): void;
    /** A structured-output session's verdict on the turn (specs/claude-cli-benchmark-followups R2). */
    sendStructuredOutput(envelope: StructuredOutputEnvelope): void;
    /**
     * `observedAiAuthSource` is the remote run's own observation of its login
     * (src/claude/aiAuthObservation.ts), captured when the SDK message arrived.
     * It is an argument so that nothing else — a local-mode transcript line,
     * a later run — can pick it up.
     */
    sendClaudeSessionMessage(body: RawJSONLines, localId?: string, observedAiAuthSource?: ObservedAiAuthSource, usage?: ClaudeMessageUsage): void;
    sendClaudeSessionMessageFromLocalTranscript(body: RawJSONLines, options?: {
        historical?: boolean;
    }): Promise<void>;
    private claudeUsageTranscript;
    private claudeUsageReconciliation;
    setClaudeUsageTranscript(projectDir: string, sessionId: string): void;
    reconcileClaudeTranscriptUsage(): Promise<void>;
    finishClaudeUsageExecution(): Promise<void>;
    /** The SDK's partial stream: where the usage a response ended on arrives (src/usage/claudeStreamedUsage.ts). */
    noteClaudeStreamEvent(message: {
        parent_tool_use_id: string | null;
        event: unknown;
    }): void;
    observeClaudeBackgroundInput(message: RawJSONLines): void;
    /** A launch that died before its first message: fail its turn, opening one if none is open. */
    failClaudeLaunchTurn(): void;
    closeClaudeSessionTurn(status?: SessionTurnEndStatus, options?: {
        opensTurn: true;
    }): void;
    closeOpenAskUserQuestionsAsCancelled(): void;
    sendCodexMessage(body: any): void;
    private enqueueSessionProtocolEnvelope;
    private applySessionProtocolRuntimeSideEffects;
    sendSessionProtocolMessage(envelope: SessionEnvelope, localId?: string): void;
    /**
     * Send a generic agent message to the session using ACP (Agent Communication Protocol) format.
     * Works for any agent type (Gemini, Codex, Claude, etc.) - CLI normalizes to unified ACP format.
     *
     * @param provider - The agent provider sending the message (e.g., 'gemini', 'codex', 'claude')
     * @param body - The message payload (type: 'message' | 'reasoning' | 'tool-call' | 'tool-result')
     */
    sendAgentMessage(provider: 'gemini' | 'codex' | 'claude' | 'opencode' | 'openclaw', body: ACPMessageData): void;
    sendSessionEvent(event: {
        type: 'switch';
        mode: 'local' | 'remote';
    } | {
        type: 'message';
        message: string;
        setupTokenRotation?: {
            version: 1;
            state: SetupTokenRotationState;
        };
        /** This notice is why the turn failed; clients report it as the failure reason. */
        isError?: true;
    } | {
        type: 'permission-mode-changed';
        mode: 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan';
    } | {
        type: 'ready';
    }, id?: string): void;
    /**
     * Relay one coalesced slice of streaming assistant text. Volatile on
     * purpose: a dropped frame costs nothing because the persisted assistant
     * message that follows is authoritative, and the consumer detects the gap
     * via `seq`.
     */
    sendStreamDelta(frame: StreamDeltaFrame): void;
    /**
     * Context-window occupancy for Saycode Desktop (specs/desktop-chat-context-window-meter).
     *
     * Read here, on the ordered transcript path, so a compaction boundary lands after the
     * responses that came before it. Main agent only: a subagent's request (`isSidechain`) and the
     * `/compact` summary measure a different prompt. Remote mode only: a local terminal session
     * never gets a turn result, so it could never name the window.
     */
    private noteClaudeContextUsage;
    /**
     * `system`/`init` and `compact_boundary`, in their transcript position. They come as their own
     * queue items from the launcher because the outgoing queue never forwards `system` messages.
     */
    noteContextUsageSignal(signal: ClaudeContextUsageSignal): void;
    /**
     * Asks the running Claude process what fills its window (`get_context_usage`, `detail: 'summary'`:
     * local estimates, no token-count API calls) and adds the answer to the frame. Best effort: a
     * runtime that fails, times out or answers in another shape leaves the frame as it was.
     */
    refreshContextUsageBreakdown(request: ClaudeControlRequest): void;
    /** `/clear` or another Claude session id: the new conversation may run under other settings. */
    resetContextUsage(): void;
    /** Local terminal mode: nothing to show, but the same conversation keeps its windows. */
    hideContextUsage(): void;
    /** Something shown, or a take-down still owed its repeats. */
    private contextUsageOwed;
    /** The latest snapshot again, same seq — for a reconnect and a turn result. */
    private resendContextUsage;
    private tickContextUsageResend;
    private syncContextUsageResend;
    /** A bounded, opt-in daemon duration record sent through the existing opaque stream relay. */
    sendTurnLatency(diagnostic: ClaudeTurnLatencyDiagnostic | CodexTurnLatencyProgress): void;
    /**
     * The opaque, unpersisted relay to the session's viewers: encrypted with the session key, and
     * volatile, so every frame on it must be safe to lose. One envelope for every frame type —
     * a consumer that cannot read one drops the frame silently.
     */
    private emitSessionStream;
    /**
     * Send a ping message to keep the connection alive
     */
    keepAlive(thinking: boolean, mode: 'local' | 'remote'): void;
    /** The turn running now, or null between turns (aplus-dev-studio-desktop#2111). */
    currentTurnId(): number | null;
    /**
     * Called first thing by a runtime's abort handler, before it awaits anything, so the
     * interrupted turn is marked by the time the abort RPC answers and Desktop sends
     * `clean-background-processes`. Between turns there is nothing to mark.
     */
    markCurrentTurnAborted(): void;
    /**
     * Exempts the conversation from the daemon's turn-end reap, as a Claude `run_in_background` launch does: a Codex
     * sub-agent keeps running after the main turn ends, and its `CodexAgent` tool call carries no background flag.
     * Called by runCodex when the running sub-agent list holds a child. Sticky like the tool-call path; the next
     * runtime report carries it (keep-alive resends an unchanged report within 30 s).
     */
    markLaunchedBackgroundJob(): void;
    private reportDaemonRuntime;
    /** Sends the state lastDaemonRuntimeReport holds, or owes it while the in-flight slots are full. */
    private sendDaemonRuntimeReport;
    /**
     * Send session death message
     */
    sendSessionDeath(): void;
    /**
     * Send usage data to the server
     */
    /**
     * 턴 종료 result 메시지. Z.AI 호환 경로처럼 assistant usage 가 0 으로 온 턴은 result 의
     * 토큰으로 한 번 보정한다 (src/usage/claudeTurnUsage.ts). 이미 계량된 턴은 건드리지 않는다.
     */
    applyClaudeTurnResult(result: {
        uuid?: unknown;
        usage?: unknown;
        modelUsage?: unknown;
    }, observedAiAuthSource?: ObservedAiAuthSource): void;
    /**
     * `/btw` 곁질문 사용량 (src/claude/claudeSideQuestion.ts). transcript 에 assistant 메시지가
     * 남지 않아 위 경로로는 잡히지 않는다 — 곁질문마다 고유 id 로 한 번 보고한다.
     */
    reportSideQuestionUsage(input: {
        requestId: string;
        usage: Usage;
        model: string | null;
        quality: 'exact' | 'estimated';
    }, observedAiAuthSource?: ObservedAiAuthSource): void;
    sendUsageData(usage: Usage, model?: string, sourceEventId?: string): void;
    sendProviderUsageEvent(event: ProviderUsageEventV1): void;
    /**
     * Returns the latest session metadata known to the client.
     */
    getMetadata(): Metadata | null;
    /**
     * Whether this session already has a title. True if a summary message was
     * sent this run (tracked synchronously, so it's reliable even before the
     * async metadata round-trip lands) or if the loaded metadata already
     * carries a non-empty summary (e.g. a resumed session titled earlier).
     */
    hasTitle(): boolean;
    /**
     * Update session metadata
     * @param handler - Handler function that returns the updated metadata
     */
    suppressNextArchiveSignal(): void;
    skipExistingMessages(throughSeq?: number): void;
    /**
     * Keep a one-turn automation resume from acknowledging user input that
     * arrived while its privileged turn was running. The next normal resume
     * replays everything after this baseline once the automation process and
     * its scoped credentials have exited.
     */
    capRuntimeProcessedSeq(throughSeq: number): void;
    private clearOutboxRetry;
    private scheduleOutboxRetry;
    private clearStateRetry;
    private scheduleStateRetry;
    private resumeStateWrites;
    private canWriteSessionState;
    private stateAckTimeout;
    private runStateWrite;
    /**
     * With storage tracking enabled, handlers must be pure and safe to replay against newer state (idempotent).
     * `skipUnchanged`: a handler that returns the document it was given sends nothing, also on a replay.
     * `onStored` runs once the server has the result (or, with `skipUnchanged`, already had it).
     */
    updateMetadata(handler: (metadata: Metadata) => Metadata, options?: {
        skipUnchanged?: boolean;
        onStored?: () => void;
    }): void;
    /**
     * Update session agent state
     * @param handler - Pure update; with storage tracking enabled it must be idempotent under replay against newer state.
     */
    updateAgentState(handler: (metadata: AgentState) => AgentState): void;
    /**
     * Wait for socket buffer to flush
     */
    flush(): Promise<void>;
    /** Call only after input dispatch and provider output/resume producers have quiesced. */
    flushForShutdown(budgetMs: number, signal?: AbortSignal): Promise<StorageConfirmation>;
    get tracksShutdownStorage(): boolean;
    /** Confirm the frozen resume cursor before a launch coordinator releases this runtime. */
    confirmShutdownCursor(): Promise<boolean>;
    /** High-water flow control, not a reservation or a hard bound for uncooperative producers. */
    waitForStorageCapacity(signal?: AbortSignal): Promise<void>;
    markStorageOutputIncomplete(): void;
    /** Recheck immediately before the runtime's final exit receipt; any later write invalidates it. */
    isStorageConfirmationCurrent(proof: StorageConfirmation): boolean;
    close(): Promise<void>;
    private startSmartReconnect;
    /** cadence 를 끝내고 기다리던 dial 도 잊는다. */
    private stopSmartReconnect;
    /**
     * `connect` 나 `connect_error` 를 아직 기다리는 dial 이 있는가.
     *
     * 스스로 만료된다 — 둘 중 아무것도 못 받는 핸드셰이크가 single-flight 가드를
     * "영원히 재연결 안 함"으로 바꿔 버리면 안 된다.
     */
    private isReconnectDialInFlight;
    private scheduleReconnectDial;
}

/** Daemon-owned policy; customer RPC callers cannot use PID aliases or fabricate liveness. */

declare function createSessionRetention(deps: {
    home: string;
    children(): readonly TrackedSession[];
    now?: () => number;
}): {
    record(sessionId: string): {
        policy: {
            mode: "default";
        } | {
            mode: "idle";
            durationMs: 3600000 | 14400000 | 28800000 | 86400000;
        } | {
            mode: "keep-alive";
        };
        configuredAt: number;
        revision: number;
    } | undefined;
    get(raw: unknown): Promise<{
        version: 1;
        capability: "session-retention-v1";
        sessionId: string;
        policy: {
            mode: "default";
        } | {
            mode: "idle";
            durationMs: 3600000 | 14400000 | 28800000 | 86400000;
        } | {
            mode: "keep-alive";
        };
        configuredAt: number;
        revision: number;
        processState: "running";
    }>;
    set(raw: unknown): Promise<{
        version: 1;
        capability: "session-retention-v1";
        sessionId: string;
        policy: {
            mode: "default";
        } | {
            mode: "idle";
            durationMs: 3600000 | 14400000 | 28800000 | 86400000;
        } | {
            mode: "keep-alive";
        };
        configuredAt: number;
        revision: number;
        processState: "running";
    }>;
};
type SessionRetention = ReturnType<typeof createSessionRetention>;

/** One journal file: its record, or why it could not be read and the session it claims, if any is legible. */
type OwnedSpawnJournalEntry = {
    record: OwnedSpawnRecord;
} | {
    error: unknown;
    sessionId: string | null;
};
interface OwnedSpawnJournal {
    list(): Promise<OwnedSpawnRecord[]>;
    entries(): Promise<OwnedSpawnJournalEntry[]>;
    read(id: string): Promise<OwnedSpawnRecord | null>;
    write(record: OwnedSpawnRecord): Promise<void>;
}

declare const ownedSnapshotSchema: z$1.ZodObject<{
    body: z$1.ZodObject<{
        tag: z$1.ZodString;
        metadata: z$1.ZodString;
        agentState: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodString>>;
        dataEncryptionKey: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodString>>;
    }, z$1.core.$strict>;
    encryptionKey: z$1.ZodString;
    encryptionVariant: z$1.ZodEnum<{
        legacy: "legacy";
        dataKey: "dataKey";
    }>;
    executionProof: z$1.ZodOptional<z$1.ZodObject<{
        ticket: z$1.ZodObject<{
            body: z$1.ZodObject<{
                issuedAt: z$1.ZodNumber;
                expiresAt: z$1.ZodNumber;
                sessionTagHash: z$1.ZodString;
                sessionCreateBodyHash: z$1.ZodString;
                machineOwnerAccountId: z$1.ZodString;
                sessionOwnerAccountId: z$1.ZodString;
                initialNonce: z$1.ZodString;
                operationId: z$1.ZodString;
                deviceSigningPublicKey: z$1.ZodString;
                companyId: z$1.ZodString;
                machineId: z$1.ZodString;
                approvalId: z$1.ZodString;
                deviceKeyId: z$1.ZodString;
                launchId: z$1.ZodString;
                version: z$1.ZodLiteral<1>;
                type: z$1.ZodLiteral<"saycode-session-execution">;
                audience: z$1.ZodString;
                studioOrigin: z$1.ZodString;
                keyId: z$1.ZodString;
            }, z$1.core.$strict>;
            signature: z$1.ZodString;
        }, z$1.core.$strict>;
        deviceProof: z$1.ZodObject<{
            body: z$1.ZodObject<{
                issuedAt: z$1.ZodNumber;
                expiresAt: z$1.ZodNumber;
                sessionTagHash: z$1.ZodString;
                sessionCreateBodyHash: z$1.ZodString;
                version: z$1.ZodLiteral<1>;
                type: z$1.ZodLiteral<"happy-session-create-proof">;
                audience: z$1.ZodString;
                method: z$1.ZodLiteral<"POST">;
                path: z$1.ZodLiteral<"/v1/sessions">;
                ticketDigest: z$1.ZodString;
                sessionOwnerAccountId: z$1.ZodString;
            }, z$1.core.$strict>;
            signature: z$1.ZodString;
        }, z$1.core.$strict>;
    }, z$1.core.$strict>>;
    runtimeState: z$1.ZodOptional<z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>>;
}, z$1.core.$strict>;
declare const ownedCreatedSchema: z$1.ZodObject<{
    sessionId: z$1.ZodString;
    ownershipBindingId: z$1.ZodOptional<z$1.ZodString>;
    registrationState: z$1.ZodOptional<z$1.ZodEnum<{
        pending: "pending";
        confirmed: "confirmed";
    }>>;
    createDigest: z$1.ZodString;
}, z$1.core.$strict>;
declare const ownedSpawnRecordSchema: z$1.ZodObject<{
    version: z$1.ZodLiteral<1>;
    intent: z$1.ZodObject<{
        intentId: z$1.ZodString;
        operationId: z$1.ZodString;
        creationRequestId: z$1.ZodString;
        ownershipPolicy: z$1.ZodEnum<{
            "prefer-owned": "prefer-owned";
            "require-owned": "require-owned";
        }>;
        subject: z$1.ZodObject<{
            issuer: z$1.ZodString;
            userId: z$1.ZodString;
        }, z$1.core.$strict>;
        companyId: z$1.ZodNullable<z$1.ZodString>;
        projectId: z$1.ZodNullable<z$1.ZodString>;
        machineId: z$1.ZodString;
        machineAccountId: z$1.ZodString;
        sessionAccountId: z$1.ZodString;
        parentHubSessionId: z$1.ZodNullable<z$1.ZodString>;
        spawnDigest: z$1.ZodString;
        type: z$1.ZodLiteral<"saycode-session-ownership-intent">;
        version: z$1.ZodLiteral<1>;
        issuer: z$1.ZodString;
        audience: z$1.ZodString;
        keyId: z$1.ZodString;
        issuedAt: z$1.ZodNumber;
        expiresAt: z$1.ZodNumber;
        signature: z$1.ZodString;
    }, z$1.core.$strict>;
    spawn: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
    preparationId: z$1.ZodString;
    intentDigest: z$1.ZodString;
    state: z$1.ZodEnum<{
        failed: "failed";
        prepared: "prepared";
        started: "started";
        preparing: "preparing";
        created: "created";
        committing: "committing";
        starting: "starting";
    }>;
    snapshot: z$1.ZodOptional<z$1.ZodObject<{
        body: z$1.ZodObject<{
            tag: z$1.ZodString;
            metadata: z$1.ZodString;
            agentState: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodString>>;
            dataEncryptionKey: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodString>>;
        }, z$1.core.$strict>;
        encryptionKey: z$1.ZodString;
        encryptionVariant: z$1.ZodEnum<{
            legacy: "legacy";
            dataKey: "dataKey";
        }>;
        executionProof: z$1.ZodOptional<z$1.ZodObject<{
            ticket: z$1.ZodObject<{
                body: z$1.ZodObject<{
                    issuedAt: z$1.ZodNumber;
                    expiresAt: z$1.ZodNumber;
                    sessionTagHash: z$1.ZodString;
                    sessionCreateBodyHash: z$1.ZodString;
                    machineOwnerAccountId: z$1.ZodString;
                    sessionOwnerAccountId: z$1.ZodString;
                    initialNonce: z$1.ZodString;
                    operationId: z$1.ZodString;
                    deviceSigningPublicKey: z$1.ZodString;
                    companyId: z$1.ZodString;
                    machineId: z$1.ZodString;
                    approvalId: z$1.ZodString;
                    deviceKeyId: z$1.ZodString;
                    launchId: z$1.ZodString;
                    version: z$1.ZodLiteral<1>;
                    type: z$1.ZodLiteral<"saycode-session-execution">;
                    audience: z$1.ZodString;
                    studioOrigin: z$1.ZodString;
                    keyId: z$1.ZodString;
                }, z$1.core.$strict>;
                signature: z$1.ZodString;
            }, z$1.core.$strict>;
            deviceProof: z$1.ZodObject<{
                body: z$1.ZodObject<{
                    issuedAt: z$1.ZodNumber;
                    expiresAt: z$1.ZodNumber;
                    sessionTagHash: z$1.ZodString;
                    sessionCreateBodyHash: z$1.ZodString;
                    version: z$1.ZodLiteral<1>;
                    type: z$1.ZodLiteral<"happy-session-create-proof">;
                    audience: z$1.ZodString;
                    method: z$1.ZodLiteral<"POST">;
                    path: z$1.ZodLiteral<"/v1/sessions">;
                    ticketDigest: z$1.ZodString;
                    sessionOwnerAccountId: z$1.ZodString;
                }, z$1.core.$strict>;
                signature: z$1.ZodString;
            }, z$1.core.$strict>;
        }, z$1.core.$strict>>;
        runtimeState: z$1.ZodOptional<z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>>;
    }, z$1.core.$strict>>;
    creationMode: z$1.ZodOptional<z$1.ZodEnum<{
        signed: "signed";
        unsigned: "unsigned";
    }>>;
    commitIssued: z$1.ZodBoolean;
    ownershipOutcome: z$1.ZodEnum<{
        pending: "pending";
        confirmed: "confirmed";
        unproven: "unproven";
    }>;
    unprovenReason: z$1.ZodOptional<z$1.ZodString>;
    proof: z$1.ZodOptional<z$1.ZodObject<{
        nonce: z$1.ZodString;
        tagHash: z$1.ZodString;
        createBodyHash: z$1.ZodString;
        intentId: z$1.ZodString;
        operationId: z$1.ZodString;
        creationRequestId: z$1.ZodString;
        ownershipPolicy: z$1.ZodEnum<{
            "prefer-owned": "prefer-owned";
            "require-owned": "require-owned";
        }>;
        subject: z$1.ZodObject<{
            issuer: z$1.ZodString;
            userId: z$1.ZodString;
        }, z$1.core.$strict>;
        companyId: z$1.ZodNullable<z$1.ZodString>;
        projectId: z$1.ZodNullable<z$1.ZodString>;
        machineId: z$1.ZodString;
        machineAccountId: z$1.ZodString;
        sessionAccountId: z$1.ZodString;
        parentHubSessionId: z$1.ZodNullable<z$1.ZodString>;
        spawnDigest: z$1.ZodString;
        type: z$1.ZodLiteral<"saycode-session-ownership">;
        version: z$1.ZodLiteral<1>;
        issuer: z$1.ZodString;
        audience: z$1.ZodString;
        keyId: z$1.ZodString;
        issuedAt: z$1.ZodNumber;
        expiresAt: z$1.ZodNumber;
        signature: z$1.ZodString;
    }, z$1.core.$strict>>;
    created: z$1.ZodOptional<z$1.ZodObject<{
        sessionId: z$1.ZodString;
        ownershipBindingId: z$1.ZodOptional<z$1.ZodString>;
        registrationState: z$1.ZodOptional<z$1.ZodEnum<{
            pending: "pending";
            confirmed: "confirmed";
        }>>;
        createDigest: z$1.ZodString;
    }, z$1.core.$strict>>;
    confirmedReceipt: z$1.ZodOptional<z$1.ZodObject<{
        type: z$1.ZodLiteral<"saycode-session-ownership-receipt">;
        requestId: z$1.ZodString;
        operationId: z$1.ZodString;
        creationRequestId: z$1.ZodString;
        ownershipPolicy: z$1.ZodEnum<{
            "prefer-owned": "prefer-owned";
            "require-owned": "require-owned";
        }>;
        preparationId: z$1.ZodString;
        sessionId: z$1.ZodString;
        bindingId: z$1.ZodString;
        subject: z$1.ZodObject<{
            issuer: z$1.ZodString;
            userId: z$1.ZodString;
        }, z$1.core.$strict>;
        createDigest: z$1.ZodString;
        parentHubSessionId: z$1.ZodNullable<z$1.ZodString>;
        spawnDigest: z$1.ZodString;
        state: z$1.ZodLiteral<"confirmed">;
        version: z$1.ZodLiteral<1>;
        issuer: z$1.ZodString;
        audience: z$1.ZodString;
        keyId: z$1.ZodString;
        issuedAt: z$1.ZodNumber;
        expiresAt: z$1.ZodNumber;
        signature: z$1.ZodString;
    }, z$1.core.$strict>>;
    providerRuntimeId: z$1.ZodOptional<z$1.ZodString>;
    caller: z$1.ZodOptional<z$1.ZodObject<{
        callerBindingId: z$1.ZodString;
        sessionId: z$1.ZodString;
        runtimeId: z$1.ZodString;
        machineId: z$1.ZodString;
        happyAccountId: z$1.ZodString;
        scope: z$1.ZodString;
        depth: z$1.ZodNumber;
        hostEpoch: z$1.ZodString;
        callerPublicKey: z$1.ZodString;
    }, z$1.core.$strict>>;
    callerCustody: z$1.ZodOptional<z$1.ZodLiteral<"host">>;
}, z$1.core.$strict>;
type OwnedSpawnRecord = z$1.infer<typeof ownedSpawnRecordSchema>;
type OwnedSpawnSnapshot = z$1.infer<typeof ownedSnapshotSchema>;
type OwnedCreated = z$1.infer<typeof ownedCreatedSchema>;
interface OwnedSpawnDependencies {
    journal: OwnedSpawnJournal;
    now(): number;
    /** Verifies issuer/audience/key/signature using daemon configuration, never a key supplied in an RPC. */
    verify(document: unknown): Promise<boolean>;
    scope(spawn: Record<string, unknown>): Promise<{
        machineId: string;
        machineAccountId: string;
        sessionAccountId: string;
    }>;
    prepare(record: OwnedSpawnRecord, publish: (snapshot: OwnedSpawnSnapshot) => Promise<void>): Promise<OwnedSpawnSnapshot>;
    failed?(record: OwnedSpawnRecord): Promise<void>;
    commit(record: OwnedSpawnRecord): Promise<OwnedCreated>;
    /** Read-only recovery, including expired proof. Never creates a new tag or re-encrypts. */
    discover(record: OwnedSpawnRecord): Promise<OwnedCreated | null>;
    prepareStart?(record: OwnedSpawnRecord): Promise<void>;
    start(record: OwnedSpawnRecord): Promise<StartedProvider>;
    observeStart(record: OwnedSpawnRecord): Promise<StartedProvider | null>;
    /** null: the child host holds its own key and its binding arrives with the started provider (T1c-b2 H3). */
    caller(record: OwnedSpawnRecord): Promise<z$1.infer<typeof OwnershipCallerBindingSchema> | null>;
}
/** caller: the binding of the started runtime, held by the child host (host custody) or the daemon. */
type StartedProvider = {
    providerRuntimeId: string;
    caller: z$1.infer<typeof OwnershipCallerBindingSchema>;
};
declare function createOwnedSpawn(deps: OwnedSpawnDependencies): {
    prepare(raw: unknown): Promise<{
        preparationId: string;
        operationId: string;
        intentDigest: string;
        sessionCreateBodyHash: string;
        sessionTagHash: string;
    }>;
    commit(raw: unknown): Promise<{
        caller?: {
            callerBindingId: string;
            sessionId: string;
            runtimeId: string;
            machineId: string;
            happyAccountId: string;
            scope: string;
            depth: number;
            hostEpoch: string;
            callerPublicKey: string;
        } | undefined;
        providerRuntimeId?: string | undefined;
        sessionId?: string | undefined;
        createDigest?: string | undefined;
        ownershipBindingId?: string | undefined;
        registrationState?: "pending" | "confirmed" | undefined;
        unprovenReason?: string | undefined;
        version: 1;
        creationRequestId: string;
        operationId: string;
        preparationId: string;
        ownershipPolicy: "prefer-owned" | "require-owned";
        state: "failed" | "prepared" | "started" | "preparing" | "created" | "committing" | "starting";
        commitIssued: boolean;
        ownershipOutcome: "pending" | "confirmed" | "unproven";
    }>;
    start(raw: unknown): Promise<{
        caller?: {
            callerBindingId: string;
            sessionId: string;
            runtimeId: string;
            machineId: string;
            happyAccountId: string;
            scope: string;
            depth: number;
            hostEpoch: string;
            callerPublicKey: string;
        } | undefined;
        providerRuntimeId?: string | undefined;
        sessionId?: string | undefined;
        createDigest?: string | undefined;
        ownershipBindingId?: string | undefined;
        registrationState?: "pending" | "confirmed" | undefined;
        unprovenReason?: string | undefined;
        version: 1;
        creationRequestId: string;
        operationId: string;
        preparationId: string;
        ownershipPolicy: "prefer-owned" | "require-owned";
        state: "failed" | "prepared" | "started" | "preparing" | "created" | "committing" | "starting";
        commitIssued: boolean;
        ownershipOutcome: "pending" | "confirmed" | "unproven";
    }>;
    status(raw: unknown): Promise<{
        caller?: {
            callerBindingId: string;
            sessionId: string;
            runtimeId: string;
            machineId: string;
            happyAccountId: string;
            scope: string;
            depth: number;
            hostEpoch: string;
            callerPublicKey: string;
        } | undefined;
        providerRuntimeId?: string | undefined;
        sessionId?: string | undefined;
        createDigest?: string | undefined;
        ownershipBindingId?: string | undefined;
        registrationState?: "pending" | "confirmed" | undefined;
        unprovenReason?: string | undefined;
        version: 1;
        creationRequestId: string;
        operationId: string;
        preparationId: string;
        ownershipPolicy: "prefer-owned" | "require-owned";
        state: "failed" | "prepared" | "started" | "preparing" | "created" | "committing" | "starting";
        commitIssued: boolean;
        ownershipOutcome: "pending" | "confirmed" | "unproven";
    }>;
};

/** The existing encrypted machine RPC binding is the only public entry to this coordinator. */

interface OwnedSpawnRpc {
    capabilities(raw: unknown): Promise<{
        ownedSpawnPrepareV1: boolean;
        ownedChildOwnerContactV1?: boolean;
    }>;
    prepare: ReturnType<typeof createOwnedSpawn>['prepare'];
    commit: ReturnType<typeof createOwnedSpawn>['commit'];
    start: ReturnType<typeof createOwnedSpawn>['start'];
    status: ReturnType<typeof createOwnedSpawn>['status'];
    callerBinding(raw: unknown): Promise<unknown>;
}

declare const resultSchema: z$1.ZodObject<{
    version: z$1.ZodLiteral<1>;
    type: z$1.ZodEnum<{
        error: "error";
        success: "success";
    }>;
    sessionId: z$1.ZodOptional<z$1.ZodString>;
    launchId: z$1.ZodString;
    additionalDirectories: z$1.ZodOptional<z$1.ZodUnknown>;
    launchMcpDropped: z$1.ZodOptional<z$1.ZodUnknown>;
    code: z$1.ZodOptional<z$1.ZodString>;
    errorMessage: z$1.ZodOptional<z$1.ZodString>;
}, z$1.core.$strict>;
type OrgSubagentRootResult = z$1.infer<typeof resultSchema>;

declare const selectionSchema: z$1.ZodObject<{
    kind: z$1.ZodLiteral<"org-endpoint">;
    bindingId: z$1.ZodString;
    endpointId: z$1.ZodString;
    generation: z$1.ZodNumber;
    candidates: z$1.ZodArray<z$1.ZodString>;
}, z$1.core.$strict>;
type OrgSubagentSelection = z$1.infer<typeof selectionSchema>;
type OrgSubagentResult = {
    ok: boolean;
    state: string;
    operationId: string;
    sessionId?: string;
    endpointId?: string;
    error?: string;
    reason?: string;
    displayName?: string;
    warnings?: Array<'ORG_LLM_ENDPOINT_BUSY'>;
    next?: {
        command: string;
    };
};

interface OrgSubagentPersisted {
    metadata: Metadata;
    agentEnvironment?: SaycodeAgentEnvironment;
}
interface Dependencies {
    home: string;
    endpointStorePath: string;
    machineId: string;
    studioOrigin: string;
    happyOrigin: string;
    keys: DeviceKeys;
    strict(): boolean;
    pin(companyId: string): Promise<unknown>;
    records(): Record<string, OrgSubagentPersisted>;
    registration(): Promise<{
        machineId: string;
        credentials: Credentials;
        happyAccountId: string;
    }>;
    metadata(options: SpawnSessionOptions): Metadata;
    sync(raw: unknown): Promise<unknown>;
    environment(selection: OrgSubagentSelection): Promise<Record<string, string>>;
    persist(session: Session, environment: SaycodeAgentEnvironment): Promise<boolean>;
    start(options: SpawnSessionOptions): Promise<SpawnSessionResult>;
    reportParent?(sessionId: string): Promise<void>;
    warn?(message: string): void;
}
declare function createOrgSubagentRuntime(deps: Dependencies): {
    spawn: (raw: unknown) => Promise<OrgSubagentResult>;
    status: (raw: unknown) => Promise<OrgSubagentResult>;
    context: (raw: unknown) => Promise<{
        orgEndpointSubagentVersion: 1;
        proofAvailable: boolean;
        serverStatus: "unknown" | "supported";
        source: {
            endpointId: string;
            generation: number;
            kind: "org-endpoint";
        } | {
            kind: "default";
        };
    }>;
    checkResume: (query: {
        bindingId: string;
        sessionId: string;
        endpointId: string;
        targetId: string;
        generation: number;
    }) => Promise<{
        ok: true;
        reason?: undefined;
        code?: undefined;
    } | {
        ok: false;
        reason: "REFUSED";
        code?: undefined;
    } | {
        ok: false;
        reason: "REFUSED" | "UNREACHABLE";
        code: string;
    }>;
    hasAuthority: (sessionId: string) => boolean;
    capabilities: (raw: unknown) => Promise<{
        orgEndpointSubagentVersion: 1;
        rootProofVersion: number;
        rootAgents: string[];
    }>;
    prepareRoot: (raw: unknown) => Promise<{
        version: 1;
        launchId: `${string}-${string}-${string}-${string}-${string}`;
        companyId: string;
        request: {
            machineId: string;
            launchId: string;
            initialNonce: string;
            sessionTagHash: string;
            sessionCreateBodyHash: string;
        };
    }>;
    startRoot: (raw: unknown) => Promise<OrgSubagentRootResult>;
    statusRoot: (raw: unknown) => Promise<{
        version: 1;
        type: "error" | "success";
        launchId: string;
        sessionId?: string | undefined;
        additionalDirectories?: unknown;
        launchMcpDropped?: unknown;
        code?: string | undefined;
        errorMessage?: string | undefined;
    }>;
};

type WorkspaceTurnAdmissionResult = {
    acquired: true;
} | {
    acquired: false;
    reason: 'workspace-busy' | 'workspace-owner-unconfirmed' | 'registry-busy';
    sessions: string[];
};
type LegacyDispatchReservation = Exclude<WorkspaceTurnAdmissionResult, {
    acquired: true;
}> | {
    acquired: true;
    finish(): Promise<void>;
};

interface SerializedTerminalBinding {
    terminalId: string;
    terminalKey: string;
    daemonNonce: string;
    lastInSeq: number;
}

interface AdoptionSummary {
    at: number;
    adopted: number;
    closed: number;
    reaped: number;
    failed: number;
}

/**
 * Spawns a PTY-backed interactive shell on behalf of the web-ui remote
 * terminal panel. Mirrors startServer.ts's pure-utility shape — no logger,
 * no globals — so callers (apiMachine.ts terminal-* RPC, future
 * controlServer endpoints) can wire it into their own envelope shapes.
 *
 * Unlike startServer.ts the child stays alive under daemon supervision —
 * we hold the IPty handle so write/resize/kill can hit it. node-pty creates
 * the child as the leader of a fresh process group via setsid, so
 * `process.kill(-pid, signal)` reaches grandchildren too (e.g. the browser
 * launcher that `gh auth login` spawns). See specs/remote-terminal/.
 */
interface TerminateOpts {
    /** ms to wait for a graceful SIGHUP exit before escalating to SIGKILL. */
    graceMs?: number;
    /** ms to wait for the process to disappear after SIGKILL. */
    killGraceMs?: number;
}
/**
 * What `terminate()` actually had to do. Reported rather than swallowed: a
 * teardown API that claims a guarantee must let the caller see when the
 * guarantee did not hold — silence is what let the original leak run for
 * months (specs/remote-terminal-close-leak/).
 */
type TerminateOutcome = 
/** Process was already gone before we signalled anything. */
'already-gone'
/** Exited on SIGHUP within the graceful window. The normal case. */
 | 'exited'
/** Ignored/trapped SIGHUP; reaped by the SIGKILL escalation. */
 | 'killed'
/** Still alive after SIGKILL — must never happen, must never be silent. */
 | 'escaped';
interface PtySession {
    readonly id: string;
    readonly userId: string;
    readonly pid: number;
    readonly cols: number;
    readonly rows: number;
    write(data: string): void;
    resize(cols: number, rows: number): void;
    /**
     * Raw signal delivery to the child's process group. Prefer `terminate()`
     * for close paths — a bare signal is never a termination guarantee.
     */
    kill(signal?: NodeJS.Signals): void;
    /** True while the child process still exists (has not been reaped). */
    isAlive(): boolean;
    /**
     * Guaranteed teardown: SIGHUP, then SIGKILL if the process is still there
     * after `graceMs`. Never rejects, and is safe to call twice.
     *
     * Why this exists and why callers must not hand-roll it: closing a remote
     * terminal used to send a bare SIGTERM, which an interactive shell ignores
     * outright (bash(1): "When Bash is interactive, in the absence of any
     * traps, it ignores SIGTERM"), so every closed terminal leaked a live
     * `/bin/bash -l` plus its pty descriptors. See
     * specs/remote-terminal-close-leak/.
     *
     * The escalation timer closes over `pid`/`child` rather than reading any
     * registry, so dropping the session from a bookkeeping map cannot cancel
     * the guarantee — which is exactly how the original leak became permanent.
     */
    terminate(opts?: TerminateOpts): Promise<TerminateOutcome>;
    onData(cb: (chunk: string) => void): () => void;
    onExit(cb: (code: number, signal: number | null) => void): () => void;
}

/** What `daemonState.terminalSurvival` carries (spec HR4·HR10). Counts only — no pid, path or secret. */
interface TerminalSurvivalState {
    version: 1;
    workers: {
        current: number;
        draining: number;
    };
    workerVersion?: string;
    lastAdoption?: AdoptionSummary;
}

type DaemonSessionStateResponse = {
    version: 1;
    state: 'present' | 'missing' | 'unknown';
};

type SetupTokenUsageObservation = {
    observationId?: string;
    observedAt: number;
    windows: Array<{
        kind: 'unified5h' | 'unified7d';
        pct: number | null;
        resetsAt: number | null;
    }>;
    reason: 'ok' | 'rate-limited' | 'authentication-failed';
    retryAt: number | null;
};

/**
 * Resume authority for a setup-token-bound session whose recorded account left this PC
 * (Saycode specs/managed-account-session-continuation).
 *
 * A group sync removes the slots of accounts no longer assigned to the member, including the one an idle
 * conversation was bound to. That conversation stays the same session: it moves onto an account Studio
 * still assigns, through the same rebind a used-up account takes mid-session, and resumes on it.
 */

/** Saycode specs/claude-org-personal-coexistence I: resume only on the organization this daemon recorded. */
type ResumeAuthRequirement = {
    version: 1;
    kind: 'organization';
    companyId: string;
};

/**
 * Decides whether this daemon is a managed Cloud runtime, and refuses to guess.
 *
 * The only admissible evidence is a provisioning file the runtime's own code
 * cannot write: owned by uid 0, not writable by group or other, reached without
 * following a symlink. An environment variable is not evidence — the daemon
 * passes its whole `process.env` to agent children on the default spawn path,
 * so anything there is attacker-controlled once the first agent turn runs. A
 * signed-token echo is not evidence either: the verifier key is public, so any
 * process can perform that exchange.
 *
 * Three outcomes, and the middle one carries the weight:
 *   - absent    → no marker. An ordinary BYOS machine; nothing changes for it.
 *                 Only ENOENT produces this. A marker we cannot read (EACCES,
 *                 EIO, ELOOP) is a refusal, and so is ENOTDIR — a file sitting
 *                 where a directory belongs is producible by anyone who can
 *                 write the parent, so treating it as "not managed" would be a
 *                 switch for turning managed mode off. On Linux the directory
 *                 the marker would live in is walked before absence is granted;
 *                 off Linux, where no managed runtime can exist, a missing
 *                 marker is absence outright.
 *   - refused   → a marker exists but cannot be trusted. Managed RPCs are not
 *                 served AND legacy spawn is not restored.
 *   - active    → verified provisioning, verified state directory, and an
 *                 isolation backend that actually answered.
 *
 * Isolation is not a declaration. `isolation.backend` names a trusted launch /
 * fencing mechanism and the daemon asks that backend whether it is wired. As of
 * T04/T09 no backend is implemented, so `probeIsolationBackend` reports
 * unavailable and `active` is unreachable — by construction, not by comment.
 */

declare const MANAGED_ISOLATION_BACKENDS: readonly ["privileged-launch-supervisor"];
type ManagedIsolationBackend = (typeof MANAGED_ISOLATION_BACKENDS)[number];
type ManagedRuntimeIdentity = {
    runtimeId: string;
    workspaceId: string;
    projectId: string;
    keyId: string;
    /**
     * The **Happy** machine this runtime is reachable at.
     *
     * A different axis from the provider's machine id, and the only one that
     * is an address. Using a provider id in its place asks a daemon that does
     * not exist, or publishes to somebody else's machine — so it is written by
     * the provisioner and read from here, never derived.
     */
    happyMachineId: string;
    /** The provisioning operation that created this runtime. */
    provisioningOperationId: string;
    /** The configuration this runtime was created for, as the parent computes it. */
    configDigest: string;
    /** The provider resources this runtime actually runs on. */
    providerMachineId: string;
    providerInstanceId: string;
    /**
     * The volume the provider attached, by the provider's own id.
     *
     * The runtime cannot derive this. `/proc/self/mountinfo` speaks in device
     * numbers and mount sources; a `vol_…` id lives in the provider's API and
     * appears nowhere the kernel can be asked. So it is written by whoever did
     * the attaching and read from here — a runtime that named its own volume
     * would be agreeing with itself.
     */
    providerVolumeId: string;
    /** The parent's statement that this operation created the volume; see the marker. */
    volumeCreatedByOperation: boolean;
    verifier: KeyObject;
    /** Directory the receipt store owns. Never inside the agent workspace. */
    stateDir: string;
    /**
     * The two uids this runtime runs code under, and they are **two**.
     *
     * The provider holds the gateway capability and the session key; the tool
     * executor runs code the model chose. Under one uid the executor can read
     * `/proc/<provider pid>/environ` and the provider's descriptors, and the
     * separation stops meaning anything — which is why `planToolExecutorIsolation`
     * refuses a shared uid outright. The marker is where that split is decided,
     * so it carries both and a marker naming one uid twice does not activate.
     */
    isolation: {
        backend: ManagedIsolationBackend;
        provider: {
            uid: number;
            gid: number;
        };
        executor: {
            uid: number;
            gid: number;
        };
        cgroupRoot: string;
    };
    /**
     * The ceilings the parent approved for this runtime's tool use.
     *
     * `grantTtlMs` bounds a broker grant — the window in which this run may use
     * tools at all — and `callTimeoutMs` bounds one invocation. Neither has a
     * default here: a runtime that invented one would be running under a policy
     * nobody approved, and the two vary by workspace and plan, so they arrive
     * in the marker rather than being baked into the image.
     */
    toolPolicy: {
        grantTtlMs: number;
        callTimeoutMs: number;
    };
    /**
     * How long a checkpoint waits for writes already in flight before it seals.
     *
     * The same kind of axis as the ceilings above, and with no default for the
     * same reason: sealing after a budget nobody approved either cuts writes
     * that were still landing or holds the runtime for a window nobody chose.
     */
    checkpoint: {
        drainBudgetMs: number;
    };
    /**
     * The tenant axis (`company:<id>` / `user:<id>`) this runtime's work
     * belongs to.
     *
     * Sealing material: the checkpoint archive binds it into the AEAD's
     * additional data, so an archive sealed under one tenant does not open
     * under another. That is why it arrives in the marker and is never derived
     * — a runtime that guessed it could neither checkpoint nor restore.
     */
    tenant: string;
    /**
     * How often this runtime checkpoints, and whether a turn boundary is
     * itself a reason.
     *
     * A policy the parent approves, never one this runtime invents: a cadence
     * nobody chose seals the volume on its own schedule, and silently taking
     * none leaves the user believing work is being saved while nothing is.
     */
    checkpointSchedule: {
        periodMs: number;
        onTurnBoundary: boolean;
        failureBackoffMs?: number;
    };
};

/**
 * What the kernel says about where the project root lives.
 *
 * ## Why a provider volume id cannot be read from here
 *
 * `/proc/self/mountinfo` describes mounts in the kernel's terms: a device as
 * `major:minor`, the source that was mounted, and where it landed. A provider
 * volume id (`vol_…`) exists in the provider's API and nowhere in this file.
 * A source string that happens to spell one is a string, not evidence.
 *
 * So the id is never derived from a mount line, and it is never echoed back
 * from what the caller expected either — echoing would make the check a
 * tautology. It is reported only when the device the root actually sits on
 * matches the mapping root recorded at provisioning time, and the filesystem
 * identity on that device matches too: a reattached volume can reuse a device
 * number without being the same filesystem.
 *
 * Pure. The mountinfo text, the identity reader and the device check are
 * inputs, so the decision runs everywhere rather than only where `/proc`
 * exists — and the device check itself is a real `O_NOFOLLOW` open in
 * `managedRuntimeDurability`.
 */

type ManagedFilesystemFacts = {
    ok: true;
    projectRoot: string;
    mountedVolumeId: string;
    rootOnExpectedVolume: true;
} | {
    ok: false;
    reason: 'mountinfo-unreadable' | 'root-not-mounted' | 'root-on-other-device' | 'mount-ambiguous' | 'mount-not-whole-device' | 'volume-identity-mismatch' | 'volume-evidence-unavailable';
};

/**
 * The wire values the parent already understands.
 *
 * `pending` and `failed` are different answers, and collapsing them loses the
 * distinction the parent needs: nothing recorded yet may still become ready,
 * while a record that exists and does not hold will not.
 */
type ManagedRestoreStatus = 'empty-initialized' | 'restored' | 'pending' | 'failed';
type ManagedRestoreState = {
    status: ManagedRestoreStatus;
    checkpointId: string | null;
    manifestDigest: string | null;
};

/**
 * The runtime's answer to "are you ready?", assembled for the parent.
 *
 * Every field comes from something the runtime cannot talk itself into: the
 * protected provisioning marker, the kernel's own view of where the project
 * root is mounted, the completion record only root can write, and the
 * isolation backend's own answer. Nothing here is taken from the request.
 *
 * Reading changes nothing. The parent polls this — including on a runtime
 * whose lease has expired — and a reading that renewed a lease or advanced a
 * sequence would make asking the way to stay alive.
 */

declare const MANAGED_RUNTIME_STATUS_VERSION = 1;
type ManagedRuntimeStatus = {
    version: typeof MANAGED_RUNTIME_STATUS_VERSION;
    identity: {
        runtimeId: string;
        workspaceId: string;
        projectId: string;
        happyMachineId: string;
        provisioningOperationId: string;
        configDigest: string;
        providerMachineId: string;
        providerInstanceId: string;
    };
    epoch: number;
    renewalSeq: number;
    leaseRemainingMs: number;
    filesystem: {
        projectRoot: string;
        mountedVolumeId: string;
        rootOnExpectedVolume: boolean;
    };
    restore: ManagedRestoreState;
    isolation: {
        verified: boolean;
        backend: string;
    };
    /**
     * What this runtime's children can do beyond the admitted prompt. The
     * parent opens a surface only when the runtime says it is there — an
     * older image answers a relayed `follow-up` with a refusal at best and
     * silence at worst, and the parent must not offer what it cannot deliver.
     */
    capabilities: readonly ManagedRuntimeCapability[];
};
type ManagedRuntimeCapability = 'follow-up';

/**
 * Durable state for managed dispatch: one receipt per request, plus the lease
 * pointer that fencing reads.
 *
 * Every write lands before the answer goes out. A receipt is created with
 * `link()` rather than `open(..., 'wx')` because `link` publishes a file that
 * is already complete — with `wx` a crash between create and write leaves a
 * zero-byte file that a later reader cannot distinguish from a real claim, and
 * "unreadable so let's start over" is how a request gets executed twice.
 *
 * What is deliberately *not* stored: prompts, tokens, environment, directory
 * contents. A receipt holds identifiers and lifecycle, nothing a leak would
 * make interesting.
 *
 * Nothing here decides that a session stopped. The store records what the
 * daemon observed locally; proving that no process survived is the job of
 * cgroup emptiness or a provider stop, neither of which this process can see.
 */
/**
 * `claimed` a request was accepted and nothing has been started.
 * `spawning` about to spawn; the pid is not known yet.
 * `spawned`  a pid exists; the session id is not known yet.
 * `running`  the child reported its session.
 * `stopping` a stop was requested and signalled.
 * `tombstone` a stop arrived before any spawn; later spawns must refuse.
 */
declare const MANAGED_RECEIPT_STATES: readonly ["claimed", "spawning", "spawned", "running", "stopping", "stopped", "failed", "tombstone"];
type ManagedReceiptState = (typeof MANAGED_RECEIPT_STATES)[number];
type ManagedReceipt = {
    version: 1;
    requestKey: string;
    runId: string;
    attemptId: string;
    epoch: number;
    /** Scope the operation was signed for; a duplicate must match it. */
    workspaceId: string;
    projectId: string;
    /**
     * Digest of the signed spawn params. Not the params — a digest is enough to
     * detect a conflicting duplicate and carries no request content.
     * A stop carries its own digest and is never compared against this one.
     */
    spawnPayloadDigest: string | null;
    state: ManagedReceiptState;
    pid: number | null;
    pgid: number | null;
    sessionId: string | null;
    /** Set when a stop lands while the spawn is still in flight. */
    stopRequestedAt: number | null;
    failureReason: string | null;
    /**
     * Observation axes (T07-L1b). Each is `null` until observed; an older
     * receipt file without them parses as all-null. They are separate facts
     * and **none of them changes `state`**: `stopped` keeps meaning "the
     * generation is proven stopped", which no child observation can assert.
     * The parent combines them with its own knowledge (why it asked for a
     * stop, whether a turn had ended) — this file does not judge outcomes.
     */
    /** The first stop intent recorded, never overwritten: the parent's `managed:stop` (or a tombstone) or lease maintenance. */
    stopIntent: 'parent-stop' | 'lease-expired' | null;
    /** From the child's verified runtime reports, monotonic: turns that went busy→idle, when the last one ended. Not a success count. */
    turnCount: number | null;
    lastTurnEndAt: number | null;
    /** The last verified report's raw flags. `pendingUserInput` means waiting on a permission/question. */
    reportThinking: boolean | null;
    reportOpenToolCall: boolean | null;
    reportPendingUserInput: boolean | null;
    /** This daemon probed the recorded pid and found no such process (ESRCH). An observation of the leader only — not a generation proof. */
    childExitAt: number | null;
    childExitProof: 'pid-absent' | null;
    claimedAt: number;
    spawnAt: number | null;
    /** When this receipt's launch took `pid` (registration, before its waits). Orders incarnations of a reused pid; `claimedAt` cannot. */
    pidRecordedAt: number | null;
    updatedAt: number;
    rev: number;
};
type ManagedLeaseRecord = {
    version: 1;
    epoch: number;
    renewalSeq: number;
    updatedAt: number;
};
type ManagedClaimResult = {
    kind: 'created';
    receipt: ManagedReceipt;
} | {
    kind: 'exists';
    receipt: ManagedReceipt;
}
/** Present but unreadable. Never re-created — that would re-run the request. */
 | {
    kind: 'corrupt';
    requestKey: string;
};
/**
 * Absence and doubt are different answers and callers act on them differently:
 * `absent` permits a first dispatch, `unknown` must block one.
 */
type ManagedReceiptLookup = {
    kind: 'absent';
} | {
    kind: 'unknown';
    detail: string;
} | {
    kind: 'ok';
    receipt: ManagedReceipt;
};
type ManagedLeaseLookup = {
    kind: 'absent';
} | {
    kind: 'unknown';
    detail: string;
} | {
    kind: 'ok';
    record: ManagedLeaseRecord;
};
type ManagedReceiptListing = {
    receipts: ManagedReceipt[];
    /** Entries present on disk that could not be parsed. Never dropped. */
    unknown: Array<{
        file: string;
        detail: string;
    }>;
    /** Set when the directory itself could not be read. */
    listError?: string;
};
type ManagedStoreLock = {
    assertHeld: (action: string) => void;
};
declare function createManagedReceiptStore(root: string, lock: ManagedStoreLock): {
    read: (requestKey: string) => ManagedReceiptLookup;
    exists: (requestKey: string) => {
        kind: "absent";
    } | {
        kind: "present";
    } | {
        kind: "unknown";
        detail: string;
    };
    /** Accept a request exactly once. Never re-runs an existing one. */
    claim(input: {
        requestKey: string;
        runId: string;
        attemptId: string;
        epoch: number;
        workspaceId?: string;
        projectId?: string;
        spawnPayloadDigest?: string | null;
        now: number;
    }): ManagedClaimResult;
    /**
     * Records a stop for a request that was never claimed, so a dispatch
     * that arrives afterwards has something durable to refuse against. The
     * server's outbox can emit a stop before a dispatch reaches the runtime.
     */
    tombstone(input: {
        requestKey: string;
        runId: string;
        attemptId: string;
        epoch: number;
        workspaceId?: string;
        projectId?: string;
        now: number;
    }): ManagedClaimResult;
    update(requestKey: string, patch: Partial<Omit<ManagedReceipt, "version" | "requestKey" | "rev">>, now: number): ManagedReceipt;
    /**
     * Fencing reads this list to decide what may still be running. An entry
     * that cannot be parsed, or a directory that cannot be read, is
     * reported rather than skipped — a silent omission would look like
     * "nothing is running" and let a new writable generation open over a
     * live child.
     */
    list(): ManagedReceiptListing;
    /**
     * A corrupt or unreadable lease is never reported as a fresh one.
     * Treating it as epoch 0 / seq 0 would accept a renewal token that was
     * already spent and re-open the runtime's write deadline after a
     * restart, which is exactly what the sequence exists to prevent.
     */
    readLease(): ManagedLeaseLookup;
    /**
     * Persists epoch and renewal sequence only. The usable deadline is
     * never written: after a restart the runtime must obtain a freshly
     * signed lease before it may execute anything.
     */
    writeLease(record: Omit<ManagedLeaseRecord, "version">): ManagedLeaseRecord;
};
type ManagedReceiptStore = ReturnType<typeof createManagedReceiptStore>;

/**
 * Verification of server-signed managed dispatch tokens.
 *
 * The runtime holds only a public verifier key, so a token cannot be minted
 * inside the runtime even by code that reads every byte of the daemon's memory.
 * That is the whole reason this is asymmetric: an HMAC secret placed here would
 * be inherited by every agent child (see `resolveInheritedSpawnEnvironment`,
 * which passes the daemon's entire `process.env` through on the default path)
 * and would hand arbitrary project code the authority to dispatch runs.
 *
 * This module verifies a signature and a set of bounded claims. It is not an
 * attestation of runtime identity — anyone holding the public key can verify
 * the same token. Runtime identity comes from provisioning (see
 * `managedRuntimeIdentity.ts`) and from the transport the token arrived on.
 */

type ManagedTokenFailure = 'malformed' | 'bad-signature' | 'wrong-audience' | 'wrong-workspace' | 'wrong-op' | 'wrong-operation' | 'expired' | 'clock-skew' | 'ttl-too-long' | 'stale-epoch' | 'epoch-mismatch' | 'payload-mismatch';

/**
 * specs/managed-cloud-byos §5.36 — the credential a managed daemon runs as.
 *
 * ## Why a managed daemon cannot use the ordinary path
 *
 * `authAndSetupMachineIfNeeded` does two things that are right for BYOS and
 * wrong here. It runs an **interactive** authentication when no credential is
 * on disk — there is nobody at a terminal in a cloud runtime — and it invents a
 * machine id with `randomUUID()`. The parent has already registered this
 * runtime's Machine and holds its id; a daemon that generated its own would
 * publish readiness for a machine nobody is listening on, and the marker check
 * would refuse the boot anyway.
 *
 * So the managed path consumes a credential the trusted parent issued, and
 * consumes it from a place the agent cannot write.
 *
 * ## What is in it, and why each part
 *
 *  - `machineId` — the Machine the parent registered. An address, not a name
 *    this process may choose.
 *  - `token` — a bearer of the **daemon's own purpose**. Never the account
 *    bearer: that one reaches every session on the account, and this process
 *    runs code the customer's agent can influence.
 *  - `machineKey` — the raw 32 bytes the parent wrapped for this Machine.
 *    Without it the daemon cannot read anything encrypted for the machine. It
 *    is a secret, which is exactly why it lives here and not in the boot input
 *    file: this record is rewritable on renewal, and root-only.
 *  - `expiresAt` — the daemon credential is short-lived by design. It is
 *    recorded so an expired one is *known* to be expired rather than discovered
 *    when the server refuses it.
 *  - `serverOrigin` — which Happy this credential is for. A credential is only
 *    valid against the server that issued it, and sending it elsewhere is
 *    sending a bearer token to a host of somebody else's choosing.
 *
 * ## Never a fallback
 *
 * Every failure to read this is a refusal. There is no path from "the managed
 * credential is missing or expired" to "authenticate as a person instead" —
 * that path ends with a cloud runtime holding an account bearer.
 */

/**
 * Why a renewal was not applied. Each is a different next move for the parent:
 * stop sending this one, send a later one, look at the runtime's disk, or
 * finish provisioning first.
 */
type ManagedCredentialReplaceRefusal = 'credential-not-mine' | 'credential-not-newer' | 'credential-unreadable' | 'credential-unwritable' | 'credential-durability-unknown';
type ManagedCredentialReplaceOutcome = {
    ok: true;
    expiresAt: number;
} | {
    ok: false;
    reason: ManagedCredentialReplaceRefusal;
};
type ManagedCredentialReceiverOutcome = ManagedCredentialReplaceOutcome | {
    ok: false;
    reason: `token-${ManagedTokenFailure}` | 'token-wrong-project' | 'token-unknown-key' | 'malformed-request' | 'credential-expired' | 'credential-busy' | 'credential-clock-invalid';
};
type ManagedCredentialReplacement = {
    token: string;
    machineId: string;
    serverOrigin: string;
    expiresAt: number;
};
/** Original signed material, before replacement-field normalization. */
type ManagedCredentialEnvelope = {
    token: string;
    params: unknown;
};
/** Closed callback contract for the later IPC relay; no transport is activated here. */
type ManagedCredentialRelayOutcome = ManagedCredentialReceiverOutcome | {
    ok: false;
    reason: 'capability-unavailable' | 'shutting-down' | 'credential-request-too-large' | 'credential-delivery-unknown' | 'live-adoption-unknown';
};

/** The store, as the RPC surface uses it. */
type ManagedAiAuthStore = {
    run: (params: ManagedAiAuthRpcParams) => Promise<ManagedAiAuthRpcResult>;
    /**
     * Whether this runtime holds the exact login a run was admitted on (R24).
     *
     * Read at spawn, not at admission: the parent fixed the version when it
     * accepted the Run, and between then and now the user may have logged out
     * and back in. A run started against a different login would be work done
     * on an account nobody agreed to spend, so this is a refusal rather than a
     * reason to fall back to anything.
     */
    holdsConnection: (input: {
        connectionId: string;
        provider: ManagedAiAuthProvider;
        connectionVersion: number;
        /**
         * Which of the two personal kinds the run was admitted on.
         *
         * Checked, not inferred: a connection that was a login when the Run was
         * accepted and is a key now is a different credential against a
         * different account, and the environment the child would be given for
         * one is not the one the other needs.
         */
        credentialKind: ManagedAiAuthCredentialKind;
    }) => boolean;
    /** Drops pending logins and kills their children. For daemon teardown. */
    close: () => void;
};

type ManagedSpawnRequest = {
    directory: string;
    agent?: string;
    environmentVariables?: Record<string, string>;
    initialPrompt?: string;
    initialPromptLocalId?: string;
};
type ManagedSpawnOutcome = {
    type: 'success';
    sessionId: string;
    pid: number;
    /** When the launch took the pid, before its readiness waits. Orders incarnations of a reused pid. */
    pidRegisteredAt?: number;
}
/**
 * `started: false` is the only evidence that lets a run be recorded as
 * failed. Without it the child may already exist, so the receipt stays
 * uncertain and reconcilable rather than closed.
 */
 | {
    type: 'error';
    errorMessage: string;
    started: false;
} | {
    type: 'error';
    errorMessage: string;
    started?: undefined;
};
/**
 * What the launcher is told about the request, taken from the verified token
 * and never from the caller-supplied params. A privileged launcher (T09) needs
 * this to check the in-flight epoch and any stop tombstone atomically with the
 * exec it performs; `request` alone cannot be trusted for that.
 */
type ManagedSpawnContext = {
    operationKey: string;
    runId: string;
    attemptId: string;
    epoch: number;
    workspaceId: string;
    projectId: string;
    /** Monotonic instant after which this runtime may no longer write. */
    leaseExpiresMonotonic: number;
    /**
     * The envelope, validated here and **re-serialized from what was parsed**.
     *
     * The launcher parses it again on its own side — it does not trust this
     * process — and re-serializing the parsed value is what makes the two
     * parses see the same document: a field this runtime did not validate
     * cannot ride along inside the bytes that cross that boundary.
     */
    bootstrapEnvelope: Buffer;
    /** The same content, parsed. For routing decisions here; never logged. */
    envelope: ManagedSpawnEnvelope;
};
type ManagedRuntimeFacts = {
    filesystem: ManagedFilesystemFacts;
    restore: ManagedRestoreState;
    isolation: {
        verified: boolean;
        backend: string;
    };
};
type ManagedRuntime = {
    identity: ManagedRuntimeIdentity;
    store: ManagedReceiptStore;
    /** Performs the actual spawn. Must return the child's pid on success. */
    spawn: (request: ManagedSpawnRequest, context: ManagedSpawnContext) => Promise<ManagedSpawnOutcome>;
    isPidAlive: (pid: number) => boolean;
    now: () => number;
    /** Monotonic clock. Wall-clock jumps must not extend a write lease. */
    monotonicNow: () => number;
    processGroupDeps?: ProcessGroupDeps;
    /**
     * What the runtime can say about itself, gathered from things it cannot
     * talk itself into: the kernel's mount view, the root-protected completion
     * record, and the isolation backend's own answer.
     *
     * Absent until the boot producer has run, and then a status read reports
     * what it found rather than guessing.
     */
    /**
     * Told when a verified renewal has moved this runtime's write deadline.
     *
     * The launcher holds the generations and enforces the lease against them;
     * this module holds the deadline. Without the call the two drift apart on
     * the first renewal, and what enforces the lease keeps using the deadline
     * the run started with.
     *
     * Called **after** the renewal is verified and persisted, never before: a
     * refused renewal must not move anything.
     */
    /**
     * Withdraws whatever a generation was allowed to do, when it is ending.
     *
     * Called on every path that ends one — the stop RPC, the fence a promotion
     * performs, the lease-expiry handler — and called **before** the stop is
     * requested, so a report already in flight cannot land after the child is
     * gone and re-register state for a generation that no longer exists.
     */
    onGenerationTerminated?: (input: {
        runId: string;
        attemptId: string;
        epoch: number;
    }) => void;
    onLeaseRenewed?: (input: {
        epoch: number;
        /** Absent on a runtime-scoped lease, which is granted before any run. */
        runId?: string;
        attemptId?: string;
        leaseExpiresMonotonic: number;
        /**
         * The sequence this grant committed at. Absent when the grant carried
         * none, and then nothing may re-arm on its behalf.
         *
         * The supervisor refuses a renewal that does not advance it, so a
         * caller re-arming a generation has to carry the one that was written
         * rather than inventing a number.
         */
        renewalSeq?: number;
        /**
         * The parent's statement **exactly as it arrived**: the signed token and
         * the params it covers.
         *
         * Present on the runtime-scoped path only. Everything else this
         * callback receives is derived - numbers this daemon computed - and a
         * supervisor holding the marker and the verifier key cannot check a
         * number against a signature. Carried verbatim: a re-mint or a
         * re-serialisation here would make the daemon the issuer of the very
         * authority the supervisor is meant to be verifying.
         *
         * Absent on the run-scoped `managed:lease`, which is a different op
         * with a different claim shape and is unchanged by this increment.
         */
        grant?: {
            token: string;
            params: unknown;
        };
    }) => void | Promise<{
        enforced: boolean;
        detail?: string;
    } | void>;
    /**
     * Called **after** the renewed lease is on disk, and only then.
     *
     * Anything that widens what this runtime may do — a report capability, a
     * longer admission — belongs here rather than in `onLeaseRenewed`: the
     * enforcement call has to happen before the write (so a renewal nobody
     * enforces is refused), and the write can still fail. A capability published
     * between the two outlives a record that was never written, which is the
     * runtime granting itself something no store agrees to.
     */
    onLeaseCommitted?: (input: {
        epoch: number;
        runId?: string;
        attemptId?: string;
        leaseExpiresMonotonic: number;
    }) => void;
    /**
     * Puts a renewed bearer on the disk and starts using it.
     *
     * Injected rather than done here: this module decides *whether* the request
     * is well-formed and authorised, and the writing belongs to the daemon that
     * owns the credential file and the socket.
     *
     * `machineId` and `serverOrigin` travel with it so the runtime can compare
     * them against what it holds. They are signed into the token's payload
     * digest, so a mismatch is not a badly-shaped request — it is a credential
     * that was issued for somebody else.
     *
     * `original` preserves the dispatch token and params before normalization,
     * so the eventual privileged receiver can authenticate what was signed.
     */
    replaceCredential?: (replacement: ManagedCredentialReplacement, original: ManagedCredentialEnvelope) => Promise<ManagedCredentialRelayOutcome>;
    /**
     * Takes a checkpoint target the parent issued, for the checkpoint it names.
     *
     * Injected rather than acted on here: this module decides whether the
     * request is authorised and whether this runtime may still write, and what
     * to do with the destinations belongs to the checkpoint session that owns
     * the drain, the archive and the pointer.
     */
    /**
     * Drives personal AI logins in this runtime's auth home.
     *
     * Injected rather than done here: this module decides whether a request is
     * authorised and well-formed, and what touches `/workspace/.auth` belongs
     * to the store that owns those paths and the provider uid they are given
     * to. Absent means no login capability is wired, which is reported rather
     * than treated as "there is no login" — a parent told a connection is
     * absent would keep offering a login that can never complete.
     */
    aiAuth?: ManagedAiAuthStore;
    acceptCheckpointTarget?: (target: Record<string, unknown>, dispatchToken: string) => Promise<{
        accepted: boolean;
        /**
         * What the inbox did with it, when it accepted.
         *
         * `queued` / `replaced-unconsumed` mean an archive follows from this
         * delivery. `in-flight` means that id is already running, and
         * `already-completed` means it published its pointer — both are
         * acceptances of the *hop* and neither produces an archive, which is
         * the distinction the parent needs and must never guess.
         */
        state?: string;
        /** A fixed classifier from the runtime. Never a URL and never the key. */
        detail: string;
    }>;
    runtimeFacts?: () => ManagedRuntimeFacts | Promise<ManagedRuntimeFacts>;
    /**
     * The privileged launch backend. It is the only thing that can prove a
     * previous generation is gone, and the only thing that can stop a child
     * running under the agent uid. T09 provides it; until then it is absent and
     * every path that needs it fails closed.
     */
    fencingBackend?: {
        proveGenerationStopped: (input: {
            belowEpoch: number;
        }) => Promise<{
            proven: boolean;
            detail: string;
        }>;
        /**
         * Addressed by the identifiers that outlive this process. A pgid is a
         * number that the kernel may have reused, and means nothing to a
         * backend that survives a daemon restart.
         */
        requestStop: (input: {
            runId: string;
            attemptId: string;
            epoch: number;
            pgid: number | null;
        }) => Promise<BackendStopResult>;
    };
};
/** Whether the trusted backend accepted the stop. `false` is never discarded. */
type BackendStopResult = {
    requested: boolean;
    detail: string;
};
/**
 * What `noteChildExited` did with the observation: `present` — the kernel
 * still answers for that pid, nothing to record; `recorded` — written on at
 * least one receipt that holds that pid; `deferred` — absence was seen but no
 * receipt could be written now (none names the pid so far, the store could not
 * be read, or the write failed). Every sighting is the handlers' own
 * obligation either way: it is retried on every maintenance tick and consulted
 * when a spawn commits the pid, until `PENDING_EXIT_TTL_MS` after the last
 * sighting.
 */
type ManagedChildExitNote = 'recorded' | 'present' | 'deferred';
declare function createManagedRpcHandlers(runtime: ManagedRuntime): {
    /**
     * Drives one step of a personal AI login.
     *
     * Tracked like every other write entry, so teardown waits for a login
     * that is already mid-flight rather than finishing beside it.
     */
    'ai-auth': (params: unknown) => Promise<ManagedAiAuthRpcResult>;
    /**
     * A verified runtime report from the child of a managed attempt
     * (T07-L1b). Records the raw flags and the monotonic turn counters.
     * Nothing here is a terminal state and nothing here is a success:
     * a turn that ended in a provider error also goes busy→idle.
     */
    noteSessionRuntime(sessionId: string, pid: number, report: {
        assistantTurns?: number;
        lastTurnEndAt?: number;
        thinking: boolean;
        hasOpenToolCall: boolean;
        pendingUserInput: boolean;
    }): void;
    /**
     * The daemon's tracking lost a child pid (T07-L1b). Recorded on the
     * receipt as an **observation** — the pid is probed again here and only
     * ESRCH counts; EPERM or anything else is not absence. `state` is left
     * alone: a leader that exited says nothing about its descendants, and
     * `stopped` stays the backend-proven meaning it has always had.
     *
     * The caller may drop its tracking whatever the answer: an exit that
     * could not be recorded now is kept here and retried (see
     * `flushPendingExits`).
     */
    noteChildExited(pid: number): ManagedChildExitNote;
    /**
     * Reports what this runtime is, and what it currently holds.
     *
     * A reading. It renews nothing and advances nothing — the parent polls
     * it, including while a runtime is expired, and a reading that renewed
     * would make asking the way to stay alive.
     */
    /**
     * Replaces the bearer this runtime authenticates with.
     *
     * Three things it refuses, and each is a way the identity could be
     * moved rather than renewed:
     *
     *  - a credential for **another Machine**. The marker says which one
     *    this is; a replacement naming a different one would make this
     *    runtime publish readiness where nobody is watching.
     *  - one that does not **outlive** what is stored. A replay of an
     *    earlier renewal would walk the credential backwards, and the
     *    window it shortens is the one the runtime is living in.
     *  - one for a **different server**. The bearer is only meaningful to
     *    the origin that issued it, and sending it elsewhere is sending a
     *    credential to a stranger.
     *
     * Key material is not part of this. A renewal extends a bearer; the
     * machine key is write-once and stays exactly as it was.
     */
    credential: (params: unknown) => Promise<{
        accepted: boolean;
        expiresAt: number;
    }>;
    /**
     * Takes the destinations one checkpoint may be written to.
     *
     * Tracked like every other write entry, so teardown waits for a
     * hand-over already in flight rather than finishing beside it.
     */
    checkpoint: (params: unknown) => Promise<{
        accepted: boolean;
        checkpointId: string;
        state: string;
    }>;
    /**
     * The push itself. Kept separate so the exported entry can be tracked
     * end to end, the way `spawn` and `stop` are.
     */
    status: (params: unknown) => Promise<ManagedRuntimeStatus>;
    /**
     * Grants this runtime a lease before it has any run.
     *
     * The same serialized fencing path the run-scoped lease takes — a
     * promotion still has to prove the previous generation is gone. Only
     * what the claim is bound to differs.
     */
    'runtime-lease': (params: unknown) => Promise<{
        ok: boolean;
        epoch: number;
        renewalSeq: number;
        grantedMs: number;
        fenced: boolean;
        localEvidence: ProcessGroupEvidence[];
        absoluteExpiry: number;
    }>;
    /** Tracked end to end so teardown waits for post-launch work too. */
    spawn(params: unknown): Promise<{
        accepted: boolean;
        receipt: {
            operationKey: string;
            runId: string;
            attemptId: string;
            state: "running" | "failed" | "claimed" | "spawning" | "spawned" | "stopping" | "stopped" | "tombstone";
            epoch: number;
            sessionId: string | null;
            stopRequested: boolean;
            certainty: "determinate" | "uncertain";
            updatedAt: number;
            failureReason: string | null;
            stopIntent: "parent-stop" | "lease-expired" | null;
            turnCount: number | null;
            lastTurnEndAt: number | null;
            reportThinking: boolean | null;
            reportOpenToolCall: boolean | null;
            reportPendingUserInput: boolean | null;
            childExitAt: number | null;
            childExitProof: "pid-absent" | null;
        };
        stopIntentRecorded: boolean;
        backendStop: BackendStopResult | null;
        terminationProven: boolean;
    } | {
        accepted: boolean;
        receipt: {
            operationKey: string;
            runId: string;
            attemptId: string;
            state: "running" | "failed" | "claimed" | "spawning" | "spawned" | "stopping" | "stopped" | "tombstone";
            epoch: number;
            sessionId: string | null;
            stopRequested: boolean;
            certainty: "determinate" | "uncertain";
            updatedAt: number;
            failureReason: string | null;
            stopIntent: "parent-stop" | "lease-expired" | null;
            turnCount: number | null;
            lastTurnEndAt: number | null;
            reportThinking: boolean | null;
            reportOpenToolCall: boolean | null;
            reportPendingUserInput: boolean | null;
            childExitAt: number | null;
            childExitProof: "pid-absent" | null;
        };
        stopIntentRecorded: boolean;
        backendStop: BackendStopResult | null;
        terminationProven: boolean;
        localEvidence: ProcessGroupEvidence;
    }>;
    /**
     * Refuses further RPC entries. Store writes stay open so that work
     * already inside can finish; teardown revokes those separately once
     * `drainLeaseWork` reports everything settled.
     */
    closeEntries(): void;
    stop(params: unknown): Promise<{
        stopIntentRecorded: boolean;
        backendStop: {
            requested: boolean;
            detail: string;
        };
        terminationProven: boolean;
        receipt: {
            operationKey: string;
            runId: string;
            attemptId: string;
            state: "running" | "failed" | "claimed" | "spawning" | "spawned" | "stopping" | "stopped" | "tombstone";
            epoch: number;
            sessionId: string | null;
            stopRequested: boolean;
            certainty: "determinate" | "uncertain";
            updatedAt: number;
            failureReason: string | null;
            stopIntent: "parent-stop" | "lease-expired" | null;
            turnCount: number | null;
            lastTurnEndAt: number | null;
            reportThinking: boolean | null;
            reportOpenToolCall: boolean | null;
            reportPendingUserInput: boolean | null;
            childExitAt: number | null;
            childExitProof: "pid-absent" | null;
        };
        localEvidence?: undefined;
    } | {
        stopIntentRecorded: boolean;
        backendStop: BackendStopResult;
        terminationProven: boolean;
        receipt: {
            operationKey: string;
            runId: string;
            attemptId: string;
            state: "running" | "failed" | "claimed" | "spawning" | "spawned" | "stopping" | "stopped" | "tombstone";
            epoch: number;
            sessionId: string | null;
            stopRequested: boolean;
            certainty: "determinate" | "uncertain";
            updatedAt: number;
            failureReason: string | null;
            stopIntent: "parent-stop" | "lease-expired" | null;
            turnCount: number | null;
            lastTurnEndAt: number | null;
            reportThinking: boolean | null;
            reportOpenToolCall: boolean | null;
            reportPendingUserInput: boolean | null;
            childExitAt: number | null;
            childExitProof: "pid-absent" | null;
        };
        localEvidence: ProcessGroupEvidence;
    }>;
    /** Durable receipt lookup — the only way to resolve a lost ACK. */
    receipt(params: unknown): {
        receipts: never[];
        unknown: {
            file: string;
            detail: string;
        }[];
    } | {
        receipts: {
            operationKey: string;
            runId: string;
            attemptId: string;
            state: "running" | "failed" | "claimed" | "spawning" | "spawned" | "stopping" | "stopped" | "tombstone";
            epoch: number;
            sessionId: string | null;
            stopRequested: boolean;
            certainty: "determinate" | "uncertain";
            updatedAt: number;
            failureReason: string | null;
            stopIntent: "parent-stop" | "lease-expired" | null;
            turnCount: number | null;
            lastTurnEndAt: number | null;
            reportThinking: boolean | null;
            reportOpenToolCall: boolean | null;
            reportPendingUserInput: boolean | null;
            childExitAt: number | null;
            childExitProof: "pid-absent" | null;
        }[];
        unknown: never[];
    };
    /**
     * Renews the write lease and, when the server raises the epoch, performs
     * the local part of fencing.
     *
     * A higher epoch is only persisted when nothing of the previous
     * generation is visible here. That is a necessary condition, not a
     * sufficient one: the server must still hold provider-level proof
     * (T09) before it treats the new generation as writable.
     */
    lease(params: unknown): Promise<{
        ok: boolean;
        epoch: number;
        renewalSeq: number;
        grantedMs: number;
        fenced: boolean;
        localEvidence: ProcessGroupEvidence[];
        absoluteExpiry: number;
    }>;
    /**
     * What to do when the write lease runs out while children are still
     * running. Refusing new work is not enough — an agent turn started
     * before the expiry keeps writing.
     *
     * This asks the privileged backend to stop them. With no backend the
     * honest answer is that nothing here can, so it reports
     * `actionRequired` instead of a clean stop.
     */
    runLeaseMaintenance(): Promise<{
        expired: boolean;
        launching: boolean;
        actionRequired: boolean;
        storeUnreadable: boolean;
        live: string[];
        unstoppable: string[];
        pendingStopsRetried: number;
    }>;
    /**
     * Resolves once every queued or running lease operation has finished.
     * Teardown uses this so a stop or fence in progress cannot outlive the
     * writer lock it is holding.
     */
    drainLeaseWork(): Promise<void>;
    /** Exposed for wiring tests: is the runtime currently allowed to work? */
    isLeaseValid: () => boolean;
    probeGroup: (pgid: number) => ProcessGroupEvidence;
};
type ManagedRpcHandlers = ReturnType<typeof createManagedRpcHandlers>;

type ByosConfirmHostReply = {
    kind: 'hosting';
} | {
    kind: 'not-hosting';
    reason: string;
} | {
    kind: 'unknown';
    reason: string;
};
type ByosDeliverReply = {
    kind: 'accepted';
    duplicate?: true;
} | {
    kind: 'refused';
    reason: string;
} | {
    kind: 'unknown';
    reason: string;
};
/**
 * The two handlers as the machine RPC surface sees them.
 *
 * Params arrive decrypted and **unvalidated** — the caller is whoever holds the
 * machine key, so every field is checked here before it is used.
 */
type ByosOfflineRpcHandlers = {
    confirmSessionHost: (params: unknown) => Promise<ByosConfirmHostReply>;
    deliver: (params: unknown) => Promise<ByosDeliverReply>;
};

/**
 * The two contracts are mutually exclusive on the wire. `deadlineAt` is an absolute instant
 * produced by *another* machine; `remainingMs` is a duration this host starts counting on
 * arrival, so it never compares its own clock against someone else's.
 */
type DifficultyRoutingRelayFields = {
    version: 1;
    requestId: string;
    signedGrant: string;
    policyRevision: number;
    sourceMachineId: string;
    hostMachineId: string;
    hostProcessKeyId: string;
    sealedText: {
        alg: 'x25519-xsalsa20-poly1305';
        nonce: string;
        ephemeralPublicKey: string;
        ciphertext: string;
    };
};
/** Legacy: an absolute instant produced by the *sending* machine. */
type DifficultyRoutingRelayRequestLegacy = DifficultyRoutingRelayFields & {
    timingVersion?: undefined;
    deadlineAt: number;
    remainingMs?: undefined;
};
/** Timing v2: a duration this host starts counting on arrival. */
type DifficultyRoutingRelayRequestV2 = DifficultyRoutingRelayFields & {
    timingVersion: 2;
    remainingMs: number;
    deadlineAt?: undefined;
};
type DifficultyRoutingRelayRequest = DifficultyRoutingRelayRequestLegacy | DifficultyRoutingRelayRequestV2;
type DifficultyRoutingRelayResponse = {
    version: 1;
    /** Echoed on every answer to a v2 request, so the caller can tell the contracts apart. */
    timingVersion?: 2;
    requestId: string;
    policyRevision: number;
    status: 'ok' | 'busy' | 'not-ready' | 'expired' | 'revoked' | 'unsupported' | 'error';
    difficulty?: 'trivial' | 'routine' | 'hard' | null;
    classifierRevision?: string;
    elapsedMs?: number;
};
type ClassifierHostDeps = {
    spawnWorker?: () => ChildProcess;
    /**
     * Wall clock. Used *only* to read a legacy `deadlineAt` at the entrance — that is the one
     * place a foreign absolute instant has to be interpreted, and it is also the legacy flaw
     * this contract exists to retire. Nothing downstream may use it.
     */
    wallNow?: () => number;
    /** Process monotonic clock: every deadline, timer, replay window and elapsed measurement. */
    monotonicNow?: () => number;
    /** Must validate live policy, exact signed grant, principal and session scope. */
    authorize?: (request: DifficultyRoutingRelayRequest, signal: AbortSignal) => Promise<boolean>;
    idleMs?: number;
    hangGraceMs?: number;
};
declare class DifficultyRoutingClassifierHost {
    private readonly hostProcessKey;
    private readonly deps;
    private readonly queue;
    private readonly replay;
    private active;
    private worker;
    private classifierRevision;
    private preparation;
    private retryAt;
    private stopping;
    private admittedBytes;
    private enabled;
    private epoch;
    private admitting;
    private idleTimer?;
    private hangTimer?;
    private loadTimer?;
    private readonly wallNow;
    private readonly mono;
    constructor(hostProcessKey: {
        id: string;
        publicKey: Uint8Array;
        secretKey: Uint8Array;
    }, deps?: ClassifierHostDeps);
    capability(): {
        hostProcessKeyId: string;
        hostProcessPublicKey: string;
        ready: boolean;
    };
    setEnabled(enabled: boolean): void;
    prepare(): void;
    classify(request: DifficultyRoutingRelayRequest): Promise<DifficultyRoutingRelayResponse>;
    terminate(): void;
    private settle;
    private stopWorker;
    /**
     * The callback gets the abort signal rather than recomputing a deadline of its own: the
     * HTTP call it makes has to die on the same budget, and it cannot see this host's clock.
     */
    private authorized;
    private pump;
    private ensureWorker;
    private onWorkerMessage;
    private armIdle;
    private openSealedText;
    private reply;
}

declare const ChildSchema: z$1.ZodObject<{
    sessionId: z$1.ZodString;
    peer: z$1.ZodString;
    parentSessionId: z$1.ZodString;
    createdAt: z$1.ZodNumber;
}, z$1.core.$strip>;
type DelegatedChild = z$1.infer<typeof ChildSchema>;
declare function createAgentDelegationStore(input: {
    path: string;
    now?: () => number;
    log?: (message: string) => void;
}): {
    installTarget(raw: unknown): Promise<void>;
    installSource(raw: unknown): Promise<void>;
    revoke(role: "target" | "source", peerMachineId: string): Promise<{
        removed: boolean;
    }>;
    list(): {
        asTarget: {
            sourceMachineId: string;
            keyId: string;
            createdBy: {
                accountId: string;
                displayName?: string | undefined;
            };
            createdAt: number;
        }[];
        asSource: {
            targetMachineId: string;
            keyId: string;
            name: string;
            platform: string;
            createdAt: number;
        }[];
    };
    sourceLinks(): {
        targetMachineId: string;
        keyId: string;
        key: string;
        name: string;
        platform: string;
    }[];
    laneLinks(): readonly DelegationLink[];
    targetLink(peerMachineId: string): {
        createdBy: {
            accountId: string;
            displayName?: string | undefined;
        };
    } | null;
    /**
     * Over the limit, the oldest children that are no longer running go first; a running child is
     * never forgotten (its stop and its slot depend on this record).
     */
    recordChild(child: {
        sessionId: string;
        peer: string;
        parentSessionId: string;
    }, isLive?: (sessionId: string) => boolean): Promise<void>;
    /** True the first time a peer's request id is seen within the memory window; false for a repeat. */
    claimRequest(peer: string, requestId: string): Promise<boolean>;
    childOf(sessionId: string, peerMachineId: string): boolean;
    children(): readonly DelegatedChild[];
};
type AgentDelegationStore = ReturnType<typeof createAgentDelegationStore>;

/** What a listing needs; the key is decoded only for the one session a read or prompt names. */
interface RelaySessionEntry {
    sessionId: string;
    directory: string;
    title: string | null;
    updatedAt: number;
}
interface RelaySessionBinding extends RelaySessionEntry {
    encryptionKey: Uint8Array;
    encryptionVariant: 'legacy' | 'dataKey';
}
type RelayCursor = {
    limit: number;
} & ({
    beforeSeq: number;
} | {
    afterSeq: number;
});
interface AgentDelegationRelayHost {
    store: Pick<AgentDelegationStore, 'targetLink' | 'childOf'>;
    /** Sessions this machine holds a key for. */
    sessions: () => readonly RelaySessionEntry[];
    /** One of them with its key; null when this machine holds no usable key for it. */
    binding: (sessionId: string) => RelaySessionBinding | null;
    isSessionLive: (sessionId: string) => boolean;
    /** The ids among `sessionIds` the server says belong to the person behind `requesterSessionId`; empty when it cannot say. */
    ownedBy: (requesterSessionId: string, sessionIds: string[]) => Promise<ReadonlySet<string>>;
    /** One server page, as `/v3/sessions/:id/messages` answers it. Throws when the server does. */
    fetchPage: (binding: RelaySessionBinding, cursor: RelayCursor) => Promise<Array<{
        seq: number;
        localId: string | null;
        createdAt: number | null;
        ciphertext: string;
    }>>;
    decrypt: (binding: RelaySessionBinding, ciphertext: string) => unknown;
    postUserMessage: (binding: RelaySessionBinding, message: {
        localId: string;
        content: Record<string, unknown>;
    }) => Promise<void>;
    now?: () => number;
}

interface AgentDelegationHost {
    store: AgentDelegationStore;
    /** Whether the session still has a live process here (counts toward `target_busy`). */
    isSessionLive: (sessionId: string) => boolean;
    /** The session's encryption variant as this machine persisted it; null when unknown here. */
    readSessionVariant: (sessionId: string) => 'dataKey' | 'legacy' | null;
    /** Stops a session this machine started; used when its record cannot be kept. */
    stopSession?: (sessionId: string) => unknown;
    /** How many delegated children may run here at once (D-5). */
    concurrencyLimit: number;
    directoryExists?: (path: string) => Promise<boolean>;
    /** Reading and prompting over the link (`agentDelegationRelay.ts`); absent = the relay methods are not registered. */
    relay?: Omit<AgentDelegationRelayHost, 'store'>;
}

/**
 * Per-(user, project) port allocation registry.
 *
 * Each daemon process owns a JSON file (typically ~/.happy(-dev)/port-
 * registry.json) that maps "userId:projectId" to { port, allocatedAt,
 * userId, projectId }. A given (user, project) tuple gets one sticky
 * port in the configured range (default 30000-40000). If a previously
 * assigned port is no longer bindable, the entry is replaced with a
 * freshly allocated port.
 *
 * Composite key (rather than projectId alone) so two users on the same
 * machine cannot end up sharing a port even if their projectId strings
 * happen to collide. See specs/preview-cross-user-isolation/ Phase 4.
 *
 * Concurrent allocate/release calls are serialized with an in-process
 * promise chain so two parallel requests cannot race into the same port.
 *
 * Migration: registries written before Phase 4 stored "projectId" keys
 * with no userId. The first matching allocate() upgrades the entry in
 * place to "userId:projectId" — cross-user-isolation-fix guarantees
 * project ownership cannot leak across users, so the first claimant of
 * a legacy entry is by definition its original owner.
 */
interface PortRegistryEntry {
    port: number;
    allocatedAt: number;
    /** Set on entries written by Phase 4+ daemons. Absent on legacy rows. */
    userId?: string;
    /** Set on entries written by Phase 4+ daemons. Absent on legacy rows. */
    projectId?: string;
}
type PortRegistryData = Record<string, PortRegistryEntry>;
interface AllocateResult {
    port: number;
    reused: boolean;
}
interface PortRegistry {
    allocate(userId: string, projectId: string): Promise<AllocateResult>;
    release(userId: string, projectId: string): Promise<boolean>;
    readAll(): Promise<PortRegistryData>;
}

/**
 * Scheduled automations — 스케줄 계산·게이트 판정·영속화 순수 로직.
 *
 * 데스크탑 v1(aplus-dev-studio-desktop `src/domain/scheduledAutomations.ts`)에서
 * 이식했다. 주석의 R#은 그 v1 spec의 요구사항 번호다. 데몬 환경에 맞춘 차이:
 * - `directory` 필드 추가(필수) — 스크립트 cwd이자 세션 spawn 디렉토리.
 * - localStorage 키·창 간 lease 개념 제거 — 데몬은 단일 실행자다.
 * 실행(스크립트·세션 spawn)은 automationTick.ts, 영속화는 automationStore.ts 담당.
 */
type AutomationSchedule = {
    kind: 'interval';
    minutes: number;
} | {
    kind: 'github';
    minutes: 15;
} | {
    kind: 'daily';
    hour: number;
    minute: number;
}
/** 실행 PC 현지 날짜(YYYY-MM-DD)·시각에 한 번. 서버 예약 payload 전용 — 레거시 RPC 파서는 받지 않는다. */
 | {
    kind: 'once';
    date: string;
    hour: number;
    minute: number;
}
/** 고른 요일(0=일요일, Date#getDay)의 실행 PC 현지 시각마다. 서버 예약 payload 전용. */
 | {
    kind: 'weekly';
    days: readonly number[];
    hour: number;
    minute: number;
}
/** 위 세 종류를 실행 PC 시계 대신 `timeZone`(IANA)의 달력으로. 서버 예약 payload 전용. */
 | {
    kind: 'daily-zoned';
    hour: number;
    minute: number;
    timeZone: string;
} | {
    kind: 'once-zoned';
    date: string;
    hour: number;
    minute: number;
    timeZone: string;
} | {
    kind: 'weekly-zoned';
    days: readonly number[];
    hour: number;
    minute: number;
    timeZone: string;
};
/**
 * `skipped-waiting`(aplus-dev-studio-desktop #2196): 직전 회차 대화가 사용자 답을 기다려 건너뛴 회차.
 * 데스크탑은 PR #2089부터 이 값을 안다. 구버전 데몬은 모르는 outcome 레코드를 버린다(parseRunHistory).
 */
type AutomationRunOutcome = 'woke' | 'skipped-gate' | 'skipped-overlap' | 'skipped-waiting' | 'silent' | 'error';
type AutomationAgent = 'claude' | 'codex' | 'gemini' | 'grok' | 'openclaw' | 'opencode';
interface AutomationRunRecord {
    at: number;
    outcome: AutomationRunOutcome;
    sessionId: string | null;
    /** skipped-waiting 전용 — 기다리는 대화. 이력 상한(20)에 woke 기록이 밀려나도 같은 대화로 게이트를 이어간다. */
    blockedBySessionId?: string;
}
interface ScheduledAutomation {
    id: string;
    projectId: string;
    name: string;
    schedule: AutomationSchedule;
    prompt: string;
    /** 스크립트 실행 cwd이자 세션 spawn 디렉토리. 없으면 무효 레코드. */
    directory: string;
    scriptCommand: string | null;
    suppressSilent: boolean;
    paused: boolean;
    createdAt: number;
    nextRunAt: number | null;
    runHistory: AutomationRunRecord[];
    /** 자동화가 깨울 세션의 agent. 이전 레코드의 부재는 claude로 해석한다. */
    agent?: AutomationAgent | null;
    /**
     * 등록한 계정 id. 한 머신 데몬에는 여러 계정이 붙을 수 있지만(cross-identity
     * machine socket) 자동화 세션은 항상 데몬 소유자 자격증명으로 spawn된다 —
     * 이 필드는 spawn의 createdByAccountId(→ HAPPY_CREATED_BY_ACCOUNT_ID)로 흘러
     * 세션 귀속을 표시하고, 클라이언트가 목록을 등록자별로 스코프하는 근거가 된다.
     * RPC에는 인증된 호출자 정보가 없어 이 값은 자기신고다 — 강제가 아니라 표시용.
     */
    createdByAccountId?: string | null;
}

/**
 * Scheduled automations 파일 저장소.
 *
 * portRegistry.ts와 같은 경로 주입 팩토리 패턴 — 테스트는 tmpdir 파일을 주입한다.
 * 데몬은 단일 프로세스 단일 실행자라 파일 락은 두지 않는다. 대신 모든 쓰기는
 * "예전에 읽어둔 배열"이 아니라 방금 다시 읽은 최신 파일 위에서 변경한다 —
 * 같은 이벤트 루프에서 직렬화되는 다른 핸들러(RPC·tick)의 쓰기를 덮어쓰지 않게.
 * 읽기는 관대한 파싱(없거나 손상 시 빈 목록), 쓰기는 tmp+rename 원자적 쓰기다.
 */

interface AutomationStore {
    list(): ScheduledAutomation[];
    /** id가 같은 기존 항목을 교체하거나 새로 추가한다. 상한 초과 추가는 throw. */
    upsert(automation: ScheduledAutomation): void;
    remove(id: string): boolean;
    replaceAll(automations: readonly ScheduledAutomation[]): void;
    /** 한 건만 갱신한다(tick의 이력 기록용). 없으면 null. */
    update(id: string, updater: (automation: ScheduledAutomation) => ScheduledAutomation): ScheduledAutomation | null;
}

/**
 * 'force' stops unconditionally (user-initiated), 'if-idle' runs the full local
 * idle guard (background cleanup), and 'if-not-busy' runs only the hard blocks
 * — used by aplus-dev-studio's trial budget stop (specs/trial-auto-onboarding-budget
 * D5), where a session must end as soon as its turn finishes even though the
 * user interacted seconds ago. Soft guards (recent interaction, minimum age,
 * local mode, stale runtime) exist to protect work the user may return to; a
 * budget-exhausted trial session has no such future — the shared credential
 * must leave the process.
 */
type StopSessionMode = 'force' | 'if-idle' | 'if-not-busy';
/**
 * Context carried alongside a stop request. `mode` decides whether the daemon
 * re-validates before killing: 'force' stops unconditionally (user-initiated),
 * 'if-idle' runs the local idle guard first (policy-initiated). When `mode` is
 * absent it is inferred from `source` — any idle/cleanup policy source is
 * treated as if-idle so a batch policy can never get force semantics by omission.
 */
type StopSessionContext = {
    source?: string;
    reason?: string;
    mode?: StopSessionMode;
};
type StopSessionResult = {
    stopped: true;
} | {
    stopped: false;
    reason: 'not-found';
} | {
    stopped: false;
    reason: 'active';
    guard: string;
    activity: IdleStopGuardActivity;
}
/**
 * A managed generation. A signal to the tracked pid would stop neither the
 * generation's tools nor the broker that grants them, and would prove
 * nothing either way, so the stop goes to the supervisor instead and this
 * path reports that it did not do it itself.
 */
 | {
    stopped: false;
    reason: 'managed-generation';
    detail: string;
} | {
    stopped: false;
    reason: 'standalone-drain';
    detail: string;
} | {
    stopped: false;
    reason: 'standalone-unowned';
    detail: string;
} | {
    stopped: false;
    reason: 'standalone-blocked';
    detail: string;
};
type IdleStopGuardActivity = {
    thinking: boolean;
    hasOpenToolCall: boolean;
    pendingUserInput: boolean;
    lastUserInteractionAt?: number;
    mode?: 'local' | 'remote';
    runtimeUpdatedAt?: number;
    sessionAgeMs?: number;
};

/**
 * Proof that a stopped session's processes are actually gone.
 *
 * `stopSession` sends one SIGTERM and drops the session from tracking, so its
 * `stopped: true` means "a signal was sent", not "the process exited" — a
 * caller that deletes the project right after can race a child still writing
 * to the workspace. This supplies the missing evidence, and nothing else:
 *
 * - The snapshot is taken **before** the stop, while the tracked root is still
 *   listed, and only those processes are observed afterwards. Nothing here
 *   sends a signal, scans cwds, matches command lines, or guesses a tree from
 *   a pid alone.
 * - Identity is pid **plus** `/proc/<pid>/stat` start time. A bare pid proves
 *   nothing after an exit: the kernel hands it out again.
 * - "I could not look" is always `unavailable`; no tracking is `not-tracked`.
 *   Neither is ever `exited` — the caller deletes data on `exited`, so an
 *   unproven exit must degrade to a warning. That is why every read
 *   distinguishes *absent* (the pid is gone) from *unreadable* (EACCES, EIO,
 *   a timeout, malformed content): conflating them would turn a permission
 *   error into a proof of exit.
 * - Every read is bounded and the whole walk is budgeted, so a wedged `/proc`
 *   stalls the answer rather than the stop RPC.
 *
 * **Scope, stated on the wire.** `session-process-tree-snapshot` is exactly
 * what is verified: the root and the descendants that existed at capture time.
 * A descendant spawned after the snapshot, or already reparented away from the
 * root, is outside it, so a consumer cannot read `exited` as "nothing of this
 * session is left on the machine".
 *
 * Linux only — the identity comes from `/proc`. Elsewhere the answer is
 * `unavailable`; the daemons this matters for run in Linux containers, and a
 * `ps`-based approximation would be a second untested path producing the same
 * confident-looking word.
 */

/** The only verification scope this module produces. */
declare const SESSION_EXIT_VERIFICATION_SCOPE: "session-process-tree-snapshot";
type SessionExitVerificationStatus = 'exited' | 'timeout' | 'unavailable' | 'not-tracked';
/**
 * Fixed vocabulary — these travel over the wire. Never a path, argv, env value
 * or raw error text.
 */
type SessionExitVerificationDetail = 'platform-unsupported' | 'process-table-unreadable' | 'root-process-absent' | 'root-identity-changed' | 'snapshot-too-large' | 'snapshot-budget-exceeded' | 'session-not-tracked' | 'stop-refused' | 'verification-unsupported';
type SessionExitVerification = {
    status: SessionExitVerificationStatus;
    scope: typeof SESSION_EXIT_VERIFICATION_SCOPE;
    detail?: SessionExitVerificationDetail;
    /** Processes in the snapshot (root included). Present once one was taken. */
    observedProcessCount?: number;
    /** Snapshot processes still alive when the budget ran out. */
    remainingProcessCount?: number;
};

/**
 * Bounded replay buffer for one terminal's output
 * (specs/desktop-terminal-reliability/ Phase 3, daemon side).
 *
 * Why the daemon owns this and not the relay: happy-server is multi-replica
 * with no sticky sessions, so a buffer kept there would live on whichever
 * replica the daemon happened to connect to, and a client reconnecting onto a
 * peer replica would find nothing. The daemon is the one place a session is
 * unambiguously singular — it is where the PTY runs.
 *
 * Frames are buffered as **plaintext**, before the secretbox hop. That is not a
 * weakening: this is the same process that owns the PTY and already has every
 * byte in memory. It is also what makes a snapshot possible at all — individual
 * frames are separately sealed, so no layer above this one can concatenate
 * them back into "what the screen looks like now".
 */
/** A frame that has been sent and can still be replayed. */
interface BufferedTerminalFrame {
    seq: number;
    chunk: string;
}
/**
 * What a `terminal-resume` should be answered with.
 *
 * `replay` — every frame after `afterSeq` is still buffered; send them in order.
 * `snapshot` — `afterSeq` fell out of the buffer, but the whole buffer is a
 *   valid picture of the screen; send it as one frame and let the client reset.
 * `gap` — nothing useful to send (the buffer is empty, or the client is ahead
 *   of us). Tell the client where its hole starts instead of pretending.
 * `none` — the client is already current; say nothing.
 */
type TerminalResumeAnswer = {
    kind: 'replay';
    frames: BufferedTerminalFrame[];
} & PageInfo | {
    kind: 'snapshot';
    seq: number;
    data: string;
} & PageInfo & LossInfo | {
    kind: 'gap';
    fromSeq: number;
} & LossInfo | {
    kind: 'none';
};
/**
 * Present only on a paged answer (`resume(afterSeq, maxChars)`,
 * specs/codexcli-daemon-stream-durability B-R3). `nextSeq` is the seq of the
 * last frame in this page — the `afterSeq` the next page is asked with — and
 * `more` says whether there is a next page at all. A one-shot answer carries
 * neither, so its shape is exactly what it was before paging existed.
 */
interface PageInfo {
    more?: boolean;
    nextSeq?: number;
}
/** Paged answers only: characters that fell out of the buffer after the client's position. */
interface LossInfo {
    droppedChars?: number;
}
interface TerminalOutputBuffer {
    /** Assigns the next seq, buffers the chunk, and returns that seq. */
    push(chunk: string): number;
    /**
     * Buffers a chunk under a seq someone else assigned — a terminal worker owns the seq of
     * the terminals it runs (specs/terminal-survive-runner-restart §2.3). A seq at or below the
     * last one is a repeat and is dropped. Seqs skipped before the first frame count as trimmed.
     * Returns the last seq.
     */
    pushAt(seq: number, chunk: string): number;
    /** The frames still buffered, oldest first — what an adopting daemon restores from. */
    frames(): BufferedTerminalFrame[];
    /**
     * Decides how to answer a resume for a client that has seen `afterSeq`.
     * With `maxChars` the answer is one page of at most that many characters
     * (capped at TERMINAL_RESUME_PAGE_CHARS, never splitting a frame); without
     * it, everything at once as before.
     */
    resume(afterSeq: number, maxChars?: number): TerminalResumeAnswer;
    /** Highest seq handed out so far. 0 before anything was sent. */
    lastSeq(): number;
    /** Buffered characters — observability, and what the cap is measured in. */
    bufferedChars(): number;
}

/**
 * The daemon side of the remote terminal contract v2 (aplus-dev-studio
 * specs/e2ee-machine-control-boundary terminal-binding-strict-design.md §4,
 * happy-wire terminalBinding.ts), shared by the relay path (apiMachine.ts) and
 * the direct path (controlServerTerminalWs.ts).
 *
 * `decideTerminalOpen` reads opened open params: a bound `terminal-open` with
 * a terminal key is a v2 terminal; an unbound one is the v1 open, kept on a
 * compat machine and refused under strict. Every open is held to the binding
 * window and its nonce is remembered — on compat too, and refused when full —
 * because a replayed open would otherwise open a shell for recorded input.
 *
 * `bindTerminal` picks a fresh daemon nonce, derives the per-direction frame
 * keys from it and the terminal key, and seals the proof the client checks.
 * A replayed open (after a restart forgot its nonce) therefore gets keys
 * nobody holds, and the input recorded for the first one opens nowhere. The
 * open itself still runs: a command it carries in `shell`/`args` runs again
 * (the memory-only nonce guard, rpcNonceGuard.ts).
 *
 * Inbound frames are written strictly in order, but a frame that arrives ahead
 * of the one before it waits for it: the relay swaps two frames of a client
 * whose socket it is rebinding. A hole still ends the terminal — once it has
 * stayed open for `TERMINAL_IN_REORDER_WINDOW_MS`, or at once when a frame is
 * further ahead than `TERMINAL_IN_REORDER_MAX_HELD` frames can bridge.
 */

type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
type TerminalOutBody = DistributiveOmit<TerminalOutFrame, 'v' | 't' | 'dir'>;
type BoundTerminalCloseReason = 'client-closed' | 'relay-closed' | 'input-gap';
interface BoundTerminal {
    readonly terminalId: string;
    /** Why the daemon ended it on this terminal's own account; carried on the sealed `closed`. */
    closeReason?: BoundTerminalCloseReason;
    /** Seals an outbound frame for `terminal-frame.data`. */
    sealOut(body: TerminalOutBody): string;
    /**
     * Opens `terminal-frame.data` from the client and admits it in order: the frames it lets through
     * (itself and any that waited for it), or `held` while the frame before it is missing.
     */
    openIn(data: string): {
        kind: 'frames';
        frames: TerminalInFrame[];
    } | {
        kind: 'held';
        awaiting: number;
    } | {
        kind: 'replayed';
    } | {
        kind: 'gap';
    } | {
        kind: 'unreadable';
    };
    /** True when `seq` is still missing behind held frames, which are then dropped: the hole stands. */
    abandonHole(seq: number): boolean;
    /**
     * Opens a direct-path `terminal-attach`: any seq after the last one counts. Each attempt of a
     * reconnecting client takes a seq, and one that died with its socket never arrives; on loopback
     * nobody can hold frames back selectively, so the hole is a lost attempt, not withheld input.
     * A repeat is still a replay, and anything but an attach is unreadable here.
     */
    openAttach(data: string): {
        kind: 'frame';
        frame: Extract<TerminalInFrame, {
            kind: 'attach';
        }>;
    } | {
        kind: 'replayed';
    } | {
        kind: 'unreadable';
    };
    /** Key material and input position, for a terminal worker to hold across a daemon restart (memory only). */
    exportState(): SerializedTerminalBinding;
}

/**
 * Per-daemon registry of active PTY-backed terminal sessions
 * (specs/remote-terminal/ Phase 2 + Phase 5). Holds the mapping between
 * server-issued sessionId and the local PtySession, plus the bookkeeping
 * needed for the audit log (openedAt, bytesIn/Out) and the idle-timeout
 * watchdog (Phase 5).
 *
 * Pure data-structure module — no socket.io / api coupling. apiMachine.ts
 * uses these helpers to plumb socket events into PtySession actions and
 * to record activity for the idle timer.
 */

interface TerminalExit {
    code: number;
    signal: number | null;
}
interface DaemonTerminalEntry {
    readonly id: string;
    readonly session: PtySession;
    readonly userId: string;
    readonly machineId: string | null;
    readonly openedAt: number;
    bytesIn: number;
    bytesOut: number;
    /** Last in/out activity wallclock ms — drives the idle timer reset. */
    lastActivityAt: number;
    /**
     * Last client → PTY input wallclock ms, null until the first keystroke.
     * Unlike `lastActivityAt` output does not move it: a `tail -f` streaming
     * away is not someone using the terminal (aplus codexcli-daemon-restart-drain R23).
     */
    lastInputAt: number | null;
    /** Why the daemon closed it, carried on `terminal-closed` (R23). */
    closeReason?: 'daemon-restart';
    /**
     * Bounded replay buffer for this terminal's output
     * (specs/desktop-terminal-reliability/ Phase 3). Lives here rather than in
     * the relay because happy-server is multi-replica: a buffer kept there
     * would sit on one replica and a client reconnecting onto a peer would
     * find nothing.
     */
    readonly output: TerminalOutputBuffer;
    /** Set once the PTY has exited; the entry is then only kept for resume. */
    exit: TerminalExit | null;
    /**
     * Which path carries the terminal. A direct (same-machine WebSocket,
     * ADR-061) terminal does not depend on the relay socket, so losing that
     * socket must not end it (specs/codexcli-daemon-stream-durability B2a).
     */
    readonly route: 'relay' | 'direct';
    /**
     * Set when the terminal was opened with its own key (contract v2,
     * terminalBindingSession.ts): its frames and controls then travel sealed
     * with that key, and the plaintext controls of the v1 contract are ignored.
     */
    binding?: BoundTerminal;
}
/**
 * Close every terminal because the daemon is being replaced: each entry is
 * tagged so its `terminal-closed` frame says why, then torn down and awaited.
 * Resolves with how many live terminals were closed. Terminals `survives` names
 * are left as they are — they outlive this daemon in a terminal worker
 * (aplus terminal-survive-runner-restart HR3).
 */
declare function closeAllDaemonTerminalSessionsForRestart(survives?: (entry: DaemonTerminalEntry) => boolean): Promise<number>;

interface MachineAutomationKey {
    version: 1;
    publicKey: Uint8Array;
    secretKey: Uint8Array;
    registeredKeyVersion: number;
}

/**
 * Why a machine does or does not advertise script automation protocol 5.
 * Enums only: the value is published in machine metadata, so it must never carry
 * paths, URLs, image names or error text.
 */
declare const SCRIPT_RUNTIME_CODES: readonly ["IMAGE_MISSING", "IMAGE_INVALID", "STUDIO_CONFIG_MISSING", "STUDIO_CONFIG_INVALID", "DOCKER_UNAVAILABLE", "ENGINE_UNSUPPORTED", "PROBE_FAILED", "SERVER_DISABLED", "SERVER_UNAVAILABLE", "MANAGED_RUNTIME", "DISABLED", "UNKNOWN"];
type ScriptRuntimeCode = (typeof SCRIPT_RUNTIME_CODES)[number];
type ScriptRuntimeImageSource = 'env' | 'release';
type ScriptRuntimeReadiness = {
    state: 'ready' | 'unavailable' | 'disabled';
    code?: ScriptRuntimeCode;
    checkedAt: number;
    imageSource?: ScriptRuntimeImageSource;
    /** First 12 hex characters of the image digest: enough to compare expected and actual, not a pullable reference. */
    imageFingerprint?: string;
};

/**
 * `lesson-host-v1` — the machine RPC the desktop calls for lesson state.
 *
 * The desktop sends `{ ...request, grantEnvelope }` flat. Nothing in that
 * object is authority:
 *
 *  - `grantEnvelope` is the **only** thing trusted. It is signed by the studio
 *    against the authenticated user, the project row, the machine-access check
 *    and the exact request digest.
 *  - `projectId` and `operation` are echoed back for an early mismatch check
 *    and then discarded — the verified claims are what the host acts on.
 *  - the remaining fields are the request, and they are digested *after* the
 *    envelope is split off so both sides agree on what "the request" is.
 *
 * Capabilities come from the grant. A UI grant never carries `lesson.review`,
 * so approving a candidate the automatic worker has not reviewed fails at the
 * CML status check rather than being smoothed over here.
 */

type LessonHostFailure = 'invalid_request' | 'unsupported_version' | 'unsupported' | 'disabled' | 'permission_denied' | 'timeout' | 'revision_conflict' | 'request_conflict' | 'payload_conflict' | 'usage_unknown' | 'budget_exceeded' | 'settings_unreadable'
/** The settings file is locked by a live writer (or one not provably gone); retry later. */
 | 'settings_busy'
/** A confirmed lesson of this name already exists; a person must decide. */
 | 'merge_required'
/** Approving this candidate replaces an existing lesson; the request must confirm which one. */
 | 'update_confirmation_required'
/** The lesson an update candidate replaces changed since it was proposed; reject and propose again. */
 | 'lesson_changed' | 'candidate_cap_reached' | 'evidence_conflict' | 'not_found' | 'runtime_error';
/** One page each of lessons and candidates, with the offsets to walk them. */
interface LessonSnapshotPagination {
    lessonOffset: number;
    candidateOffset: number;
    /** null means this was the last page — never "we stopped looking". */
    nextLessonOffset: number | null;
    nextCandidateOffset: number | null;
}
interface LessonSnapshot {
    version: 1;
    lessons: unknown[];
    candidates: unknown[];
    settings: LessonSettings;
    reviewOutcome: string;
    reviewExecution?: 'session';
    pagination: LessonSnapshotPagination;
}
type LessonHostResponse = {
    ok: true;
    snapshot: LessonSnapshot;
} | {
    ok: false;
    reason: LessonHostFailure;
};

interface LessonHostRuntime {
    handle(params: unknown): Promise<LessonHostResponse>;
    /** The live handle, for the turn host and the review worker. */
    host(): LessonHostHandle | null;
    /** The only way to obtain a binding CML will act on. */
    issuer(): LessonBindingIssuer | null;
    generation(): Promise<number>;
    close(): Promise<void>;
}

interface LessonHostSupervisor {
    handle(params: unknown): Promise<LessonHostResponse>;
    /**
     * Opens a project for host-initiated work (a turn, a review).
     *
     * Those callers hold no grant of their own, so one is requested from the
     * studio. The workspace still comes from the signature — the daemon is
     * asking, not asserting.
     */
    ensureOpen(projectId: string): Promise<LessonHostRuntime | null>;
    /**
     * For the turn host and the review worker.
     *
     * Only an **already open** project is returned. Those callers hold no
     * grant, so they cannot name a workspace, and inventing one from the
     * session's directory would reintroduce exactly the hole the signed claim
     * closes. A project nobody has opened through a grant yet is simply not
     * available to them — safe, and knowingly incomplete.
     */
    openedRuntimeFor(projectId: string): LessonHostRuntime | null;
    /**
     * The authenticated caller the studio named when this project was opened.
     *
     * Read back rather than derived: a host that invents a user id attributes
     * work — and gateway spend — to somebody who never authenticated.
     */
    openedUserId(projectId: string): string | null;
    /**
     * Confirms this project is still authorized, refreshing if the lease aged
     * out, and returns the caller the studio names *now*.
     *
     * The initial grant authorized one moment. Access to a project, a machine
     * or an account can be taken away afterwards, and nothing local can
     * observe that — so the lease carries the verified grant's own expiry and
     * is renewed by asking the studio again, never extended here.
     */
    authorize(projectId: string, budgetMs: number): Promise<string | null>;
    close(): Promise<void>;
}

interface EncryptedServerAutomation {
    automationId: string;
    revision: number;
    generation: number;
    payloadVersion: 1 | 4 | 6;
    payloadCiphertext: string;
    machineKeyVersion: number;
    machineKeyEnvelope: string;
    paused: boolean;
    migrationPending?: boolean;
    enabledAt: number;
    runRequestedAt?: number | null;
}
interface ServerAutomationCacheState {
    cursor: bigint;
    serverTime: number;
    syncedAt: number;
    automations: EncryptedServerAutomation[];
    pendingAcknowledgements: Array<{
        automationId: string;
        revision: number;
    }>;
    pendingCancellations?: EncryptedServerAutomation[];
    /**
     * 서버가 `automation-missed-record` 를 받는다고 마지막 sync 에서 알렸다(scheduled-missed-run-policy).
     * 구 서버는 그 이벤트에 ack 하지 않으므로, 이게 없으면 놓친 회차를 기록하려고 기다리지 않는다.
     */
    missedRunRecord?: boolean;
    /**
     * 서버가 claim 의 `catchUp`(늦은 1회 실행, 상한 8일)을 받는다고 마지막 sync 에서 알렸다(scheduled-missed-run-policy R11).
     * 구 서버는 그 필드를 무시하고 늦은 회차를 거절하므로, 이게 없으면 `돌아오면 1회 실행`을 기본 규칙으로 처리한다.
     */
    catchUpClaim?: boolean;
}
interface ServerAutomationCache {
    read(): ServerAutomationCacheState;
    resetCursor?(): void;
    applySync(value: unknown): {
        nextSeq: bigint;
        acknowledgements: Array<{
            automationId: string;
            revision: number;
        }>;
    };
    markAcknowledged(items: Array<{
        automationId: string;
        revision: number;
    }>): void;
    markCancelled?(items: Array<{
        automationId: string;
        revision: number;
    }>): void;
}

type ServerAutomationReportOutcome = 'WOKE' | 'SILENT' | 'SKIPPED_GATE' | 'ERROR' | 'NO_CHANGE';
interface PendingAutomationReport {
    runId: string;
    claimToken: string;
    reportId: string;
    status: 'COMPLETED' | 'FAILED';
    outcome: ServerAutomationReportOutcome;
    sessionId: string | null;
    detailCiphertext: string | null;
    failureCode?: string | null;
    degradedCode?: string | null;
    notificationOnly?: boolean;
    queueDepth?: number | null;
    queuePosition?: number | null;
    queueTotal?: number | null;
    queueEstimatedAt?: number | null;
    /** When this report was first queued. Absent on entries persisted before this field existed. */
    createdAt?: number;
}

type TransportResult = {
    ok: boolean;
    value?: any;
    error?: string;
};
interface ServerAutomationTransport {
    /** `catchUp`: specs/scheduled-missed-run-policy R11 — 놓친 회차를 늦게 1회 실행한다(서버 상한 8일). */
    claim(input: {
        automationId: string;
        generation: number;
        scheduledFor: number;
        catchUp?: true;
    }): Promise<TransportResult>;
    start(input: {
        runId: string;
        claimToken: string;
    }): Promise<TransportResult>;
    heartbeat(input: AutomationRunHeartbeatRequest): Promise<TransportResult>;
    report(input: PendingAutomationReport): Promise<TransportResult>;
    /** specs/scheduled-missed-run-policy R4·R5 — 놓친 회차 공백 하나를 서버 이력의 한 행으로 기록한다. */
    recordMissed?(input: {
        automationId: string;
        generation: number;
        firstMissedAt: number;
        missedCount: number;
        failureCode: 'MISSED_OFFLINE' | 'MISSED_COLLAPSED';
    }): Promise<TransportResult>;
}

type SessionFollowupTransportResult<T> = {
    ok: true;
    value: T;
} | {
    ok: false;
    error?: string;
};
interface SessionFollowupTransport {
    sync(input: {
        wireVersion: 1;
        afterSeq: string;
        limit: number;
    }): Promise<SessionFollowupTransportResult<unknown>>;
    claim(input: {
        wireVersion: 1;
        followupId: string;
        generation: number;
        step: number;
    }): Promise<SessionFollowupTransportResult<unknown>>;
    evaluate(input: {
        wireVersion: 1;
        followupId: string;
        generation: number;
        step: number;
        claimToken: string;
        decision: 'WAIT' | 'CONTINUE' | 'TERMINATE';
        observedSeq: number;
        terminalCode?: SessionFollowupEvaluationTerminalCode;
    }): Promise<SessionFollowupTransportResult<unknown>>;
    deliver(input: {
        wireVersion: 1;
        followupId: string;
        generation: number;
        step: number;
        claimToken: string;
        expectedSeq: number;
        localId: string;
        contentCiphertext: string;
    }): Promise<SessionFollowupTransportResult<unknown>>;
}

type SetupTokenAccountStatus = {
    managedAccountId: string;
    active: boolean;
    disabled: boolean;
    /** Stored is not verified: only an explicit inference check may change this. */
    authState: 'unverified';
    usageState: 'fresh' | 'unavailable';
    usageReason: string | null;
};

/** Group custody journal: hashes only, durable intent before changing credentials. */
type GroupProvider = 'claude' | 'codex';
type CredentialGroupRequest = {
    version: 1;
    scope: string;
    provider: GroupProvider;
    generation: number;
    fingerprint: string;
    payload: string | null;
    /** Setup-token wire: the provider bundle generation (equal to `generation`) and the Studio lease it applies. */
    assignmentGeneration?: number;
    leaseId?: string;
} & ({
    principalType?: 'user';
    userId: string;
    machineId?: never;
} | {
    principalType: 'machine';
    machineId: string;
    userId?: never;
});
type AppliedCredentialReceipt = {
    managedAccountId: string;
    credentialGeneration: number;
};

type VerificationIdentity = {
    email?: string;
    organizationUuid?: string;
    accountId?: string;
};
type AccountVerification = {
    account: number;
    ok: boolean;
    model?: string;
    errorKind?: string;
};

type CodexBackgroundTask = {
    callId: string;
    command: string;
    processId?: string;
    status: 'running' | 'unknown';
    /** When this runtime first saw it (aplus-dev-studio-desktop specs/agent-background-work-panel R1). */
    startedAt?: number;
};

/**
 * `background-task-stop`: the session RPC that stops one background task this runtime lists in its metadata
 * (aplus-dev-studio-desktop specs/agent-background-work-panel R2). Claude stops a `claudeBackgroundTasks` task
 * through the SDK, Codex a `codexBackgroundTasks` terminal through the app-server.
 *
 * `requested` only means the provider accepted the stop. Whether the task ended is read from the list, which
 * drops it once the provider reports it gone; the client waits for that.
 */

type BackgroundTaskStopStatus = 'requested' | 'not_found' | 'unavailable' | 'unsupported' | 'failed';

/**
 * Cherry-picked types from `codex app-server generate-ts` (Codex 0.107.0),
 * with the GPT-5.6 max/ultra effort extension supported by Saycode runtimes.
 * Only the essential types needed for our integration.
 */
type ThreadId = string;
type ThreadItem = {
    type: "userMessage";
    id: string;
    content: InputItem[];
} | {
    type: "agentMessage";
    id: string;
    text: string;
    phase?: string | null;
    memoryCitation?: unknown | null;
} | {
    type: "reasoning";
    id: string;
    summary?: string[];
    content?: string[];
} | {
    type: "commandExecution";
    id: string;
    command: string;
    cwd?: string;
    status?: string;
    aggregatedOutput?: string | null;
    exitCode?: number | null;
    durationMs?: number | null;
} | {
    type: "fileChange";
    id: string;
    changes: unknown[];
    status?: string;
} | {
    type: "mcpToolCall";
    id: string;
    server: string;
    tool: string;
    status?: string;
    arguments?: unknown;
    result?: unknown;
    error?: unknown;
    durationMs?: number | null;
} | ({
    type: string;
    id: string;
} & Record<string, unknown>);
type ThreadTurn = {
    id: string;
    items: ThreadItem[];
    itemsView?: unknown;
    status?: unknown;
    error?: unknown;
    startedAt?: number | null;
    completedAt?: number | null;
    durationMs?: number | null;
};
type Thread = {
    id: ThreadId;
    forkedFromId?: string | null;
    path?: string | null;
    cwd?: string;
    turns?: ThreadTurn[];
    [key: string]: unknown;
};
type ThreadGoalStatus = "active" | "paused" | "blocked" | "usageLimited" | "budgetLimited" | "complete";
type ThreadGoal = {
    threadId: ThreadId;
    objective: string;
    status: ThreadGoalStatus;
    tokenBudget: number | null;
    tokensUsed: number;
    timeUsedSeconds: number;
    createdAt: number;
    updatedAt: number;
};
type ThreadGoalSetParams = {
    threadId: ThreadId;
    objective?: string | null;
    status?: ThreadGoalStatus | null;
    tokenBudget?: number | null;
};
type ThreadGoalSetResponse = {
    goal: ThreadGoal;
};
type ThreadGoalClearResponse = {
    cleared: boolean;
};
type ReadConversationResponse = {
    thread: Thread;
};
type RollbackConversationResponse = {
    thread: Thread;
};
type InjectItemsResponse = Record<string, never>;
type CompactConversationResponse = Record<string, never>;
type McpServerStartupStatus = {
    threadId?: string | null;
    name: string;
    status: 'starting' | 'ready' | 'failed' | 'cancelled' | string;
    error?: string | null;
    failureReason?: 'reauthenticationRequired' | null;
};
type McpServerStatus = {
    runtimeStatus?: string | null;
    name: string;
    authStatus: 'unknown' | 'unsupported' | 'notLoggedIn' | 'bearerToken' | 'oAuth' | string;
    tools: Record<string, unknown>;
    serverInfo?: unknown | null;
    resources?: unknown[];
    resourceTemplates?: unknown[];
};
type ListMcpServerStatusResponse = {
    data: McpServerStatus[];
    nextCursor: string | null;
};
type ReviewDecision = "approved" | {
    approved_execpolicy_amendment: {
        proposed_execpolicy_amendment: string[];
    };
} | "approved_for_session" | "denied" | "abort";
type ApprovalPolicy = "untrusted" | "on-request" | "never";
type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
type ReasoningEffort = "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | "ultra";
type ImageDetail = "auto" | "low" | "high";
type InputItem = {
    type: "text";
    text: string;
    text_elements?: unknown[];
} | {
    type: "image";
    detail?: ImageDetail;
    url: string;
} | {
    type: "localImage";
    detail?: ImageDetail;
    path: string;
};
type EventMsg = {
    type: string;
} & Record<string, unknown>;

type CodexAuthSource = 'cli-login' | 'custom-home' | 'multi-auth' | 'managed' | 'unknown';
type CodexAuthCheck = 'authenticated' | 'unverified';

type UserInputHandler = (params: unknown, signal: AbortSignal) => Promise<{
    answers: Record<string, {
        answers: string[];
    }>;
}>;
type ApprovalHandler = (params: {
    type: 'exec' | 'patch' | 'mcp';
    callId: string;
    /**
     * The provider's own turn and thread for this approval, when its request carried them
     * (Saycode specs/desktop-messenger-channels — R8/R9).
     *
     * Read off the raw request with the same extractors the turn lifecycle uses, and passed
     * through **only when present**. A consumer that needs to name the waiting turn must use this;
     * falling back to whatever turn is currently open would attribute the wait to whichever
     * request happens to be running, which is a different request's business.
     */
    turnId?: string | null;
    threadId?: string | null;
    command?: string[];
    cwd?: string;
    fileChanges?: Record<string, unknown>;
    reason?: string | null;
    toolName?: string;
    input?: unknown;
    serverName?: string;
    message?: string;
}) => Promise<ReviewDecision>;
declare class CodexAppServerClient {
    /** Host-only decision retained across reconnects; never a user/provider override. */
    private readonly recallHostPrepared;
    private readonly startupEnvironment?;
    /** Fixed from the Happy run identity before the first native process starts. */
    private readonly isolatedAutomationContext;
    /** Set only by a launch-bound workspace owner; it must not alter manual memory/configuration. */
    private readonly workspaceExitObservation;
    private process;
    private readline;
    private outputGate;
    private outputReadAbort;
    private outputDrain;
    private outputSettled;
    private disconnectingEpoch;
    private preserveDisconnectingTurn;
    private shutdownInputFrozen;
    private disconnectRevision;
    private initializedEpoch;
    private reconnecting;
    private shutdownObservationFinished;
    private disconnectOperation;
    private outputFailed;
    private turnAdmissionAbort;
    private workspaceTurnOperations;
    private nextId;
    private pending;
    private rolloutUsage;
    private rolloutUsagePaths;
    private rolloutUsageThreads;
    private pendingRolloutTurns;
    private rolloutUsageReads;
    private rolloutUsageFailures;
    private rolloutUsageTimer;
    private observeRolloutUsage;
    private readRolloutUsage;
    private usageCoverage;
    private usageCoverageGapThreads;
    private processEpoch;
    private connected;
    private sandboxConfig?;
    private readonly sandboxPolicyMode;
    private readonly beforeTurn?;
    private readonly completeTurn?;
    private readonly markTurnDispatched?;
    private onTurnDispatch?;
    private readonly protectedWriterTree;
    private readonly automationProcesses;
    private automationExitEvidence;
    private automationInputClosed;
    private sandboxCleanup;
    private multiAuthProxy;
    private readonly managedProviderArgs;
    /** aplus specs/org-agent-plan §6.3-2 — the plan provider through the runner's local proxy, or null. */
    private readonly agentPlanProviderArgs;
    private agentPlanAppliedToLaunch;
    private multiAuthProxyCleanup;
    sandboxEnabled: boolean;
    /**
     * 샌드박스가 요청됐지만 초기화가 실패해 네이티브 정책으로 떨어진 상태.
     * connect() 시점에는 permissionMode 를 아직 모르므로(턴마다 결정된다)
     * 여기서는 사실만 기록하고, 네트워크를 실제로 잃는지는 호출자가 모드를
     * 아는 턴 시점에 isSandboxFallbackNetworkLoss 로 판정한다.
     */
    sandboxInitFailed: boolean;
    sandboxInitFailureReason: string | null;
    private _threadId;
    private pendingProjectBinding;
    private _turnId;
    private nativeThreadMetadata;
    private readonly nativeCompletionObservations;
    private threadDefaults;
    private pendingTurnCompletion;
    private pendingInterrupt;
    private outstandingServerRequests;
    private notificationProtocol;
    private completedTurnIds;
    private rawFileChangesByItemId;
    private openCommandExecutionTurns;
    private openCommandLabels;
    private backgroundTimer;
    private backgroundTasks;
    private readonly subagents;
    /** The main thread the tracker was pointed at, and on which app-server process (see `pointSubagentsAtMainThread`). */
    private subagentsMain;
    /** Connect-time version gate. Below it there is no list to follow, so no spawn row either (R13: as before). */
    private subagentTrackingAvailable;
    restoreBackgroundTasks(tasks: CodexBackgroundTask[]): void;
    /**
     * Ends one listed background terminal by its own process id (aplus-dev-studio-desktop
     * specs/agent-background-work-panel R2). `thread/backgroundTerminals/clean` is not used: it ends every
     * terminal of the thread. The list drops the terminal on the next refresh, brought forward here.
     */
    terminateBackgroundTask(callId: string): Promise<BackgroundTaskStopStatus>;
    private scheduleBackgroundRefresh;
    private deferredRawTurnCompletion;
    private rawTurnCompletionFallbackTimer;
    private pendingAgentMessageDeltas;
    private sentAgentMessageChars;
    private pendingAgentMessageDeltaChars;
    private agentMessageDeltaFlushTimer;
    private mcpServerStatuses;
    private pendingInactivityAbort;
    private eventHandler;
    private approvalHandler;
    private userInputHandler;
    private readonly userInputRequests;
    private cancelPendingApprovals;
    private approvalCancellation;
    private approvalShutdownFailed;
    private readonly serverRequestTasks;
    private preparedTurn;
    private static readonly PROCESS_EXIT_WAIT_MS;
    constructor(sandboxConfig?: SandboxConfig, beforeTurn?: () => Promise<CheckpointTurnPreparation | void>, completeTurn?: CheckpointSessionComposition['completeTurn'], 
    /** 생략하면 개인 머신(owner-choice)으로 본다 — sandbox/sandboxPolicy.ts */
    sandboxPolicyMode?: SandboxPolicyMode, 
    /**
     * The provider configuration a managed Cloud run must use.
     *
     * Present only for a managed run, and then it is the whole story: the
     * account-rotation proxy is not consulted, and the provider is not
     * chosen from whatever is in the user's config file.
     */
    managedProviderArgs?: string[] | null, markTurnDispatched?: () => void, 
    /** Host-only decision retained across reconnects; never a user/provider override. */
    recallHostPrepared?: boolean, startupEnvironment?: {
        CODEX_SQLITE_HOME: string;
    } | undefined, 
    /**
     * The organization agent plan's provider arguments (`agentPlanCodexArgs`). Like a managed run, they are
     * the whole provider story: account rotation is not consulted and no side command runs on the machine's
     * own login.
     */
    agentPlanProviderArgs?: string[] | null, 
    /** Fixed from the Happy run identity before the first native process starts. */
    isolatedAutomationContext?: boolean, 
    /** Set only by a launch-bound workspace owner; it must not alter manual memory/configuration. */
    workspaceExitObservation?: boolean);
    get threadId(): string | null;
    /**
     * The provider a thread start/resume/fork names. `null` lets Codex take the launch's configured provider;
     * a plan session names the plan provider explicitly so a resumed plan thread cannot pick another one.
     */
    private get threadModelProvider();
    /** True once a Codex process was started with the organization agent plan provider. */
    get agentPlanApplied(): boolean;
    get turnId(): string | null;
    get isConnected(): boolean;
    supportsGoalActions(): boolean;
    getMcpStartupStatuses(): McpServerStartupStatus[];
    setOutputStorageGate(gate: {
        wait: (signal: AbortSignal) => Promise<void>;
        onFailure: () => void;
    }): void;
    waitForOutputDrain(): Promise<void>;
    /** Permanent for this client/launch. The runtime must separately freeze its other producers. */
    freezeInputForShutdown(): boolean;
    /** Coordinator releases observation ownership; input stays permanently frozen. */
    finishShutdownObservation(): void;
    private hasPendingOutputProducers;
    cancelOutputDrain(): void;
    private assertInputOpen;
    private failOutputStorage;
    private admitTurn;
    /** Runtime claim commits at the request write, not the earlier checkpoint preparation hooks. */
    setTurnDispatchHandler(handler: () => void): void;
    setEventHandler(handler: (msg: EventMsg) => void): void;
    setUserInputHandler(handler: UserInputHandler): void;
    private cancelUserInputRequests;
    /** Replaces the handler/cancellation pair; omitting cancellation clears the old hook. */
    setApprovalHandler(handler: ApprovalHandler, cancelPending?: () => void | Promise<void>): void;
    private extractTurnId;
    /** Same shape as `extractTurnId`, for the thread. Absent stays absent — nothing is inferred. */
    private extractThreadId;
    private extractTurnStatus;
    private shouldHandleRawNotification;
    /** MCP servers whose last reported startup status is anything other than 'ready'. */
    private getNotReadyMcpServers;
    /**
     * If the current turn was force-interrupted by our inactivity watchdog,
     * returns the diagnostic snapshot to attach to the turn's terminal event and
     * clears it. Returns null for user-initiated aborts (which stay silent).
     */
    private consumeInactivityAbortFields;
    /**
     * completedTurnIds exists to dedupe the SAME completion reported twice in
     * quick succession (codex/event and v2 turn/completed racing for one
     * turn, or a stray fallback timer firing after the authoritative signal
     * already did — see emitOrDeferRawTurnCompletion/scheduleRawTurnCompletionFallback).
     * It must not survive genuine NEW work starting: a mid-turn agentMessage
     * can legitimately carry phase 'final_answer' (e.g. a clarifying
     * question), which fires our idle-fallback task_complete while Codex has
     * not actually finished. Codex then resumes the SAME provider turn — no
     * fresh turn/started precedes it, since it never asked for a new turn —
     * and with pendingTurnCompletion already null at that point, this
     * resumed activity is the only signal available that the earlier
     * completion was premature. Reopen the consumer lifecycle and forget the
     * stale marker so the eventual authoritative completion is delivered as a
     * balanced start/end pair instead of silently dropped. Otherwise the
     * session receives no durable terminal marker for the resumed work
     * (desktop-stuck-responding-state: a live client stayed "응답중" 24+
     * minutes past the real end of work because of exactly this).
     * Scoped to item/started (a new work item beginning) and its legacy
     * exec_command_begin equivalent — never to item/completed or its legacy
     * counterparts, so the same-tick dual-protocol completion race above
     * stays untouched.
     */
    private reopenConsumerLifecycleOnResumedWork;
    private emitRawTurnCompletion;
    private hasOpenCommandsForTurn;
    private emitOrDeferRawTurnCompletion;
    private clearRawTurnCompletionFallback;
    private scheduleRawTurnCompletionFallback;
    private flushDeferredRawTurnCompletion;
    private flushAgentMessageDeltas;
    private enqueueAgentMessageDelta;
    private clearAgentMessageDeltas;
    /** `rawResponse/completed` → `codex_usage` for the thread and turn that reported it. */
    private emitCodexUsage;
    /** The turn sendTurnAndWait is waiting on, by provider id; a deferred completion leaves it open. */
    private isInsideActiveTurn;
    /** The spawn row (design §1.3), titled once the child's label is read; never after its turn or app-server ended. */
    private emitSubagentSpawned;
    private handleRawNotification;
    connect(): Promise<void>;
    /**
     * Ends the app server's input and waits for it to leave on its own.
     *
     * `disconnectInternal` is a shutdown, not a flush: it does `stdin.end()`
     * and then `SIGTERM` in the same `try`, with `SIGKILL` two seconds later,
     * and never awaits the exit. A checkpoint that archives provider state
     * cannot use it — a signalled process did not flush, and an unawaited one
     * was not observed leaving at all.
     *
     * This sends **no signal**. It closes stdin and reports what the kernel
     * then said, within a budget. A timeout is reported as a timeout: the
     * caller decides whether to fall back to `disconnect()`, and that fallback
     * is a kill, so it is never quiescence.
     */
    endInputAndAwaitExit(budgetMs: number, signal?: AbortSignal): Promise<{
        exited: boolean;
        code: number | null;
        signal: string | null;
    }>;
    /** Cooperative native writer proof for a private run, distinct from model answer completion.
     * A failed background read, active/unknown child, signal or surviving group never counts as natural exit. */
    finishAutomationContext(budgetMs: number): Promise<{
        foregroundDrained: boolean;
        backgroundDrained: boolean;
        providerExitedCleanly: boolean;
    }>;
    private workspaceForegroundIdle;
    /** Read-only preflight; the root must recheck its own input/writer gate before freezing. */
    canDrainWorkspace(): Promise<boolean>;
    finishWorkspaceContext(budgetMs: number): Promise<{
        foregroundDrained: boolean;
        backgroundDrained: boolean;
        providerExitedCleanly: boolean;
    }>;
    private finishObservedNativeWriters;
    private disconnectInternal;
    private performDisconnectInternal;
    disconnect(): Promise<void>;
    /**
     * Opens the next protected turn before the provider process exists. Stops a running codex first
     * so its sandbox cleanup removes any bwrap mount points from the reserved workspace, then runs
     * the checkpoint gate. Returns null when the session is not protected.
     * specs/linux-checkpoint-enforcement-backend R4
     */
    /** Drops a cached preparation that will not be dispatched; the composition owns the cleanup. */
    abortPreparedTurn(): void;
    prepareProtectedTurn(): Promise<CheckpointTurnPreparation | null>;
    private cleanupMultiAuthProxy;
    /**
     * Tool policy (agent-tool-policy I1b): builds the thread entry that puts the shadow proxy in
     * front of the user's own cua-driver, from `config/read`'s `mcp_servers` (or
     * `CODEX_CONFIG_UNREADABLE`). Null keeps the thread config as it was.
     */
    setCuaShadow(build: ((nativeServers: unknown) => Record<string, unknown> | null) | null): void;
    private cuaShadow;
    /**
     * Desktop extension MCP servers in this session's map (aplus/launchMcpServers.ts). They stand aside
     * for a user `config.toml` server of the same name: Codex deep-merges the thread map into the native
     * one, so the user's entry would keep its `env` (credentials) and run the injected command.
     */
    setLaunchMcpServerNames(names: readonly string[]): void;
    private launchMcpServerNames;
    /** Read-only host discovery; credentials remain inside the session host. */
    readHostMcpServers(cwd: string): Promise<Record<string, unknown>>;
    private buildThreadConfig;
    private rememberThreadDefaults;
    startThread(opts: {
        model?: string;
        cwd?: string;
        approvalPolicy?: ApprovalPolicy;
        sandbox?: SandboxMode;
        writableRoots?: string[];
        mcpServers?: Record<string, unknown>;
        developerInstructions?: string | null;
    }): Promise<{
        threadId: string;
        model: string;
    }>;
    resumeThread(opts?: {
        threadId?: string;
        model?: string;
        cwd?: string;
        approvalPolicy?: ApprovalPolicy;
        sandbox?: SandboxMode;
        writableRoots?: string[];
        mcpServers?: Record<string, unknown>;
        developerInstructions?: string | null;
    }): Promise<{
        threadId: string;
        model: string;
    }>;
    /**
     * Another client on the same CODEX_HOME (e.g. the Codex app) can archive a thread, and Codex refuses to
     * use an archived thread until it is unarchived. Using the thread from here means it is wanted again.
     */
    private requestUnarchivingThread;
    forkThread(opts: {
        threadId: string;
        path?: string;
        model?: string;
        cwd?: string;
        approvalPolicy?: ApprovalPolicy;
        sandbox?: SandboxMode;
        writableRoots?: string[];
        mcpServers?: Record<string, unknown>;
        developerInstructions?: string | null;
    }): Promise<{
        threadId: string;
        model: string;
        thread: Thread;
    }>;
    forkThreadFromPath(opts: {
        path: string;
        cwd: string;
    }): Promise<{
        threadId: string;
        model: string;
        thread: Thread;
    }>;
    /**
     * Points the sub-agent tracker at the current main thread. Another thread, or the first start/resume on a new
     * app-server process, starts the list over. A same-process resume of the same thread (developer instructions,
     * MCP sync) does not: Codex hands it to the loaded session, whose children keep running.
     */
    private pointSubagentsAtMainThread;
    private rememberNativeThreadMetadata;
    private settleNativeCompletionObservation;
    private observeAuthoritativeNativeCompletion;
    readThread(opts: {
        threadId: string;
        includeTurns?: boolean;
    }): Promise<ReadConversationResponse>;
    /**
     * Full history, oldest first, one turn per response: a whole-thread read arrives as a single output
     * line and a long thread outgrows the reader's line limit. Codex without turn paging gets the whole read.
     */
    readThreadTurns(threadId: string): Promise<ThreadTurn[]>;
    listMcpServerStatus(opts: {
        threadId: string;
        serverNames?: string[];
        measureServer?: <T>(action: () => Promise<T>) => Promise<T>;
    }): Promise<ListMcpServerStatusResponse>;
    compactThread(opts: {
        threadId: string;
    }): Promise<CompactConversationResponse>;
    rollbackThread(opts: {
        threadId: string;
        numTurns: number;
    }): Promise<RollbackConversationResponse>;
    injectItems(opts: {
        threadId: string;
        items: unknown[];
    }): Promise<InjectItemsResponse>;
    setGoal(opts: {
        threadId: string;
        /** Omit to keep the stored objective (a status-only change: pause or resume). */
        objective?: string;
        status?: ThreadGoalSetParams['status'];
        tokenBudget?: number | null;
    }): Promise<ThreadGoalSetResponse>;
    clearGoal(opts: {
        threadId: string;
    }): Promise<ThreadGoalClearResponse>;
    /**
     * Whether a short side `codex` command may run beside this app-server.
     * Managed providers carry run-specific tool boundaries and mandatory
     * sandboxes guard shared machines, so neither gets a second process.
     */
    get sideCommandAllowed(): boolean;
    /**
     * Launch for a short side `codex` command with this app-server's payer and
     * sandbox: the multi-auth proxy account when one was chosen, and the same
     * sandbox wrapper and seatbelt marker when the app-server is wrapped.
     * Null until connected or when side commands are not allowed.
     */
    prepareSideCommand(args: string[]): Promise<{
        command: string;
        args: string[];
        env: Record<string, string>;
    } | null>;
    /**
     * Launch for the `/btw` side question's own app-server (codexSideQuestion.ts): this app-server's
     * payer, Codex state home and sandbox wrapper (Desktop specs/codexcli-side-question R4-d). The
     * session's sandbox runtime is borrowed, never initialized or reset — it is process-wide.
     * Null until connected or when side commands are not allowed.
     */
    prepareSideAppServer(): Promise<{
        command: string;
        args: string[];
        env: Record<string, string>;
    } | null>;
    /** The current thread's rollout file, when Codex reported one for it. */
    get threadRolloutPath(): string | null;
    /** The multi-auth proxy arguments and this app-server's sandbox wrapper, on a side launch. Never initializes or resets the sandbox. */
    private wrapSideLaunch;
    get authRecoverySource(): CodexAuthSource;
    get authRecoveryBusy(): boolean;
    /** Explicit, idle-only recovery. Unlike legacy reconnect, failure never discards the thread. */
    private withReconnect;
    reconnectForAuth(): Promise<CodexAuthCheck>;
    private reconnectForAuthInternal;
    reconnectAndResumeThread(opts?: {
        preservePendingTurnCompletion?: boolean;
    }): Promise<boolean>;
    private reconnectAndResumeThreadInternal;
    /** Default grace period after interrupt before forcing a restart (ms). */
    private static readonly ABORT_GRACE_MS;
    /** Allow the authoritative terminal notification to follow the final answer. */
    private static readonly RAW_TURN_COMPLETION_FALLBACK_GRACE_MS;
    private hasPendingTurnCompletion;
    private resolvePendingTurn;
    private schedulePendingTurnInactivityTimeout;
    private recordPendingTurnActivity;
    private matchesPendingTurn;
    private markPendingTurnStarted;
    private tryResolvePendingTurn;
    private waitForTurnCompletion;
    /**
     * Request turn interruption and optionally force-restart the app-server if
     * the turn does not settle within a short grace period.
     */
    abortTurnWithFallback(opts?: {
        gracePeriodMs?: number;
        forceRestartOnTimeout?: boolean;
    }): Promise<{
        hadActiveTurn: boolean;
        aborted: boolean;
        forcedRestart: boolean;
        resumedThread: boolean;
    }>;
    /**
     * Send a user turn and wait for it to complete.
     * Returns when task_complete or turn_aborted is received.
     */
    sendTurn(prompt: string, opts?: {
        model?: string;
        cwd?: string;
        approvalPolicy?: ApprovalPolicy;
        sandbox?: SandboxMode;
        writableRoots?: string[];
        effort?: ReasoningEffort;
        extraInputItems?: InputItem[];
        beforeTurn?: () => Promise<CheckpointTurnPreparation | void>;
        /** Must synchronously validate/claim input after all preparation, immediately before writing. */
        beforeDispatch?: () => void;
        /** Records a written request even if the ACK/start notification never arrives. */
        onDispatched?: () => void;
        /** Host observer invoked only after the provider accepts turn/start. */
        onSubmitted?: () => void;
    }): Promise<void>;
    /** Default maximum inactivity while waiting on turn completion (ms). */
    private static readonly TURN_TIMEOUT_MS;
    /**
     * Send a user turn and wait for it to complete (task_complete or turn_aborted).
     * Returns { aborted: true } if the turn was aborted (user cancel, permission reject, etc.).
     *
     * `turnTimeoutMs` bounds *inactivity*, not total turn duration: any turn
     * progress notification restarts the window, and it stays disarmed while an
     * approval request is awaiting the user. A turn that keeps making progress
     * therefore runs without a wall-clock limit; only a silent provider is
     * interrupted.
     */
    sendTurnAndWait(prompt: string, opts?: {
        model?: string;
        cwd?: string;
        approvalPolicy?: ApprovalPolicy;
        sandbox?: SandboxMode;
        writableRoots?: string[];
        effort?: ReasoningEffort;
        extraInputItems?: InputItem[];
        beforeTurn?: () => Promise<CheckpointTurnPreparation | void>;
        /** Must synchronously validate/claim input after all preparation, immediately before writing. */
        beforeDispatch?: () => void;
        /** Records a written request even if the ACK/start notification never arrives. */
        onDispatched?: () => void;
        /** Host observer invoked only after the provider accepts turn/start. */
        onSubmitted?: () => void;
        /** Host observer of this native completion, after successful checkpoint apply. */
        onCompleted?: (turnId: string, thread: {
            id: string;
            path: string;
        } | null) => void;
        /** Releases the pre-admitted host continuation, including unsupported/fallback completion. */
        onCompletionObservationSettled?: () => void;
        /** Max time without any turn activity before interrupting the provider. */
        turnTimeoutMs?: number;
    }): Promise<{
        aborted: boolean;
    }>;
    private resolveBeforeTurn;
    /** An explicit per-call beforeTurn overrides the pre-opened turn, matching resolveBeforeTurn. */
    private consumePreparedTurn;
    steerTurn(prompt: string): Promise<void>;
    interruptTurn(): Promise<void>;
    hasActiveThread(): boolean;
    clearThreadState(): void;
    /** Default timeout for RPC requests (ms). */
    private static readonly REQUEST_TIMEOUT_MS;
    private request;
    private notify;
    private respond;
    private handleLine;
    /**
     * Map our internal ReviewDecision to the wire format the server expects.
     * Server uses: accept, acceptForSession, decline, cancel
     * Our handler uses: approved, approved_for_session, denied, abort
     */
    /**
     * Map our internal ReviewDecision to the wire format codex expects.
     * v2 methods (item/*) use: accept/acceptForSession/decline/cancel
     * Legacy methods (execCommandApproval/applyPatchApproval) use: approved/approved_for_session/denied/abort
     */
    private mapDecisionToWire;
    private parseToolNameFromElicitationMessage;
    private mapDecisionToMcpElicitationResponse;
    private handleServerRequest;
    private handleApproval;
    private observeUsageCoverage;
    private handleNotification;
}

type ProbeClient = Pick<CodexAppServerClient, 'setEventHandler' | 'setApprovalHandler' | 'connect' | 'startThread' | 'sendTurnAndWait' | 'disconnect'>;
type CodexRecoveryProbeResult = {
    attempts: number;
} & ({
    ok: true;
    model: 'gpt-6.1-sol';
} | {
    ok: false;
    errorKind: string;
});
/** Uses the actual Happy app-server adapter, including its managed rotation proxy. */
declare function probeHappyCodex(cwd: string, factory?: (environment?: {
    CODEX_SQLITE_HOME: string;
}) => ProbeClient | Promise<ProbeClient>, environment?: {
    CODEX_SQLITE_HOME: string;
}): Promise<CodexRecoveryProbeResult>;

type SetupTokenAssignmentRecipient = {
    keyId: string;
    publicKey: string;
    secretKey: Uint8Array;
};

type OrgLlmEndpointFetch = (url: string, init: RequestInit) => Promise<Response>;

type AiCredentialProvider = 'claude' | 'codex' | 'zai';
type TrialAiCredentialLeaseMarker = {
    leaseId: string;
    contentHash: string;
    bundleVersion: number;
};
type AiCredentialCommandResult = {
    stdout: string;
    stderr: string;
    exitCode?: number;
};
type AiCredentialRotationStatus = {
    state: 'stopped' | 'starting' | 'running' | 'needs-reauth' | 'blocked' | 'quota-unknown' | 'not-routed' | 'not-applicable';
    lastErrorKind: string | null;
    warningKinds?: Array<'ACCOUNT_NEEDS_REAUTH' | 'NO_COMPARISON'>;
    lastSwitchAt?: string;
    activeAccount?: string;
    strategy?: 'sequential';
    threshold5h?: number;
    threshold7d?: number;
};
type CommandOptions = {
    cwd?: string;
    terminateProcessTree?: boolean;
    maxOutputBytes?: number;
    timeoutMs?: number;
    acceptNonZeroExit?: boolean;
    environment?: NodeJS.ProcessEnv;
    input?: string;
    signal?: AbortSignal;
};
type Supervisor = {
    enable(): Promise<void>;
    stop(): Promise<void>;
    status(): AiCredentialRotationStatus;
};
type AiCredentialRuntimeDependencies = {
    probeCodex?: typeof probeHappyCodex;
    homeDir: string;
    platform?: NodeJS.Platform;
    /** Happy machine identity used to bind server-side machine principal mutations. */
    machineId?: string;
    now(): number;
    env: Record<string, string | undefined>;
    execFile(command: string, args: string[], options?: CommandOptions): Promise<AiCredentialCommandResult>;
    readFile(path: string): Promise<string>;
    readdir(path: string): Promise<string[]>;
    writeFile(path: string, content: string, options?: {
        mode?: number;
    }): Promise<void>;
    mkdir(path: string, options?: {
        recursive?: boolean;
        mode?: number;
    }): Promise<unknown>;
    rename(from: string, to: string): Promise<void>;
    chmod(path: string, mode: number): Promise<void>;
    rm(path: string, options?: {
        recursive?: boolean;
        force?: boolean;
    }): Promise<void>;
    makeTempDir(): Promise<string>;
    /**
     * Holds the cross-process lock of one third-party credential file (Codex `auth.json`, the
     * codex-multi-auth pool) around a local read-compare-write. The same lock path is taken by
     * Desktop's remote scripts. Never held across a network call (aplus D4 Q-C3).
     */
    lockCredentialFile<T>(path: string, work: () => Promise<T>): Promise<T>;
    /** Required only for one-use setup-token binding nonce persistence; missing support fails closed. */
    syncFile?(path: string): Promise<void>;
    syncDirectory?(path: string): Promise<void>;
    /** Unexpected but non-fatal conditions, e.g. a provenance record that could not be written. */
    warn?(message: string): void;
    /** The organization LLM endpoint status probe (aplus specs/org-llm-endpoints C5); defaults to the global fetch. */
    fetch?: OrgLlmEndpointFetch;
    supervisor: Supervisor;
    codexProxyStatus?: () => {
        activeRoutes: number;
    };
    /** Present only when the daemon has a trusted Studio origin configured. */
    setupTokenBinding?: Pick<SetupTokenBindingVerifier, 'verify' | 'available'>;
    /**
     * Saycode specs/setup-token-switch-usage-check — Studio's pick among the accounts this shared PC holds; a move checks a
     * candidate first. The account, null when none is usable, undefined when Studio could not answer.
     */
    sharedChoose?(input: {
        companyId: string;
        candidates: Array<{
            managedAccountId: string;
            credentialGeneration: number;
        }>;
        exclude: string[];
        measure: boolean;
    }): Promise<string | null | undefined>;
    machineSetupTokenStart?(binding: MachineSetupTokenBindingRecord): Promise<void>;
    machineSetupTokenAuthority?(binding: MachineSetupTokenBindingRecord): Promise<void>;
    /** Managed account IDs the daemon's running sessions are bound to; a group sync leaves their slots for a later sync. */
    setupTokenAccountsInUse?(): string[];
};
declare function createAiCredentialRuntime(deps: AiCredentialRuntimeDependencies): {
    orgLlmModelBindingSync: (params: unknown) => Promise<{
        ok: true;
        bindingId: string;
        snapshotId: string;
        selectedModel: string;
    }>;
    orgLlmEndpointSync: (params: unknown) => Promise<{
        ok: true;
        generation: number;
    }>;
    sharedMachineSetupTokenScope: () => Promise<string | null>;
    sharedMachineUsage: (managedAccountId: string, observation: SetupTokenUsageObservation) => Promise<void>;
    sharedMachineRebind: (managedAccountId: string, observation?: SetupTokenUsageObservation) => Promise<Record<string, string> | null>;
    sharedMachineAccountEnvironment: (managedAccountId: string) => Promise<Record<string, string> | null>;
    sharedMachineStartProof: (managedAccountId: string) => Promise<{
        companyId: string;
        credentialGeneration: number;
    } | null>;
    sharedMachineStartBudgetMove: (managedAccountId: string, preferred: string[]) => Promise<Record<string, string> | null>;
    measureWithPermit: (input: {
        companyId: string;
        machineId: string;
        managedAccountId: string;
        credentialGeneration: number;
        permit: Record<string, unknown>;
    }) => Promise<Record<string, unknown> | null>;
    launchSession: <T>(environment: Record<string, string>, start: () => T | Promise<T>) => Promise<T>;
    personalSchedulerTick: (context: {
        online: boolean;
        inUse: boolean;
    }) => Promise<void>;
    stopPersonalScheduler: () => void;
    tokenProbe: (input: unknown, signal?: AbortSignal) => Promise<{
        version: number;
        operation: any;
        accountRef: any;
        credentialGeneration: any;
        scope: string;
        enabled: any;
        ackCost: any;
        status: string;
        reason: any;
        eligibility: string;
        account: {
            observation?: {
                source: string;
                observedAt: any;
                windows: any;
                coverage: string;
                reason: any;
                retryAt: any;
            } | undefined;
            managedAccountId?: any;
            scope: string;
            enabled: any;
            ackCost: any;
            status: string;
            reason: any;
            eligibility: string;
            budget: {
                minIntervalMs: number;
                dailyLimit: any;
                remaining: any;
                retryAt: number | null;
                machineRemaining: any;
            };
            accountRef: any;
            credentialGeneration: any;
            credentialType: any;
            probeEnabled: any;
            authState: any;
            usageStatus: any;
            decisionEligible: boolean;
            reasonCodes: any;
        };
        budget: {
            machineUsed24h: any;
            machineLimit24h: any;
            accountLimit24h: any;
            minIntervalMs: number;
            dailyLimit: any;
            remaining: any;
            retryAt: number | null;
            machineRemaining: any;
        };
    } | {
        version: number;
        status: string;
        reason: string;
        error: string;
    }>;
    collectorProbe: (input: unknown, machineId: string) => Promise<{
        version: number;
        status: string;
        error: string;
    } | {
        version: number;
        status: string;
        companyId: string;
        machineId: string;
        managedAccountId: string;
        credentialGeneration: number;
        policyRevision: number;
        permitId: any;
        observation: {
            source: string;
            observedAt: number;
            windows: any;
            coverage: string;
            reason: string;
            retryAt: number | null;
        };
    }>;
    capture: (input: {
        provider: AiCredentialProvider;
        codexRecovery?: boolean;
        refreshOwner?: boolean;
    }) => Promise<{
        provider: "claude" | "codex";
        payload: string;
    }>;
    refreshCodexOwner: (input: {
        provider: "codex";
        thresholdMs?: number;
    }) => Promise<{
        provider: "codex";
        refreshedAccountIds: string[];
        failedAccounts: {
            accountId: string;
            errorKind: string;
        }[];
        payload: string;
    }>;
    refreshClaudeOwner: (input: {
        provider: "claude";
        thresholdMs?: number;
    }) => Promise<{
        provider: "claude";
        payload: string;
    }>;
    repairCodex: (input: {
        provider: "codex";
        payload: string;
    }) => Promise<{
        provider: "codex";
        configured: boolean;
        applyGeneration: number;
        runtime: {
            transport: "happy-app-server";
            attempts: number;
            stateRecovered: boolean;
            authChanged: boolean;
            rotationChanged: boolean;
        };
        verification: {
            checkedAt: number;
            accounts: ({
                model: "gpt-6.1-sol";
                account: number;
                ok: boolean;
            } | {
                errorKind: string;
                account: number;
                ok: boolean;
            })[];
        };
    }>;
    apply: (input: {
        provider: AiCredentialProvider;
        payload: string;
        trialLease?: TrialAiCredentialLeaseMarker;
        applyMode?: "merge" | "replace" | "repair";
        activeAccountIndex?: number;
        /** Sent only by the org deployment: which company bundle this is. */
        provenance?: unknown;
    }) => Promise<{
        applyMode?: "merge" | "replace" | "repair" | undefined;
        activeAccountIndex?: number | undefined;
        applyGeneration: number;
        verification: {
            checkedAt: number;
            accounts: AccountVerification[];
        };
        rotation: AiCredentialRotationStatus;
        accountCount: number;
        activeAccountStatus: "unknown" | "disabled" | "not-selected" | "usage-readable" | "api-key" | "relogin-required";
        usableAccountCount: number;
        reloginRequiredAccountCount: number;
        provider: "claude";
        configured: boolean;
    } | {
        applyMode?: "merge" | "replace" | "repair" | undefined;
        activeAccountIndex?: number | undefined;
        applyGeneration: number;
        repairedAccountCount: number;
        credentialRepairFailedAccountCount: number;
        rotation: AiCredentialRotationStatus;
        accountCount: number;
        activeAccountStatus: "unknown" | "disabled" | "not-selected" | "usage-readable" | "api-key" | "relogin-required";
        usableAccountCount: number;
        reloginRequiredAccountCount: number;
        provider: "claude";
        configured: boolean;
    } | {
        applyMode?: "merge" | "replace" | "repair" | undefined;
        activeAccountIndex?: number | undefined;
        applyGeneration: number;
        provider: "claude";
        configured: boolean;
        credentialKind: "api_key";
        rotation: AiCredentialRotationStatus;
    } | {
        applyMode?: "merge" | "replace" | "repair" | undefined;
        activeAccountIndex?: number | undefined;
        applyGeneration: number;
        provider: "claude";
        configured: boolean;
        rotation: AiCredentialRotationStatus;
        credentialKind?: undefined;
    } | {
        applyMode?: "merge" | "replace" | "repair" | undefined;
        activeAccountIndex?: number | undefined;
        applyGeneration: number;
        provider: "zai";
        configured: boolean;
        accountCount: number;
    } | {
        applyMode?: "merge" | "replace" | "repair" | undefined;
        activeAccountIndex?: number | undefined;
        applyGeneration: number;
        provider: "codex";
        configured: boolean;
        accountCount: number;
        rotation?: undefined;
    } | {
        applyMode?: "merge" | "replace" | "repair" | undefined;
        activeAccountIndex?: number | undefined;
        applyGeneration: number;
        provider: "codex";
        configured: boolean;
        accountCount: number;
        rotation: {
            state: "running" | "blocked" | "quota-unknown";
            lastErrorKind: null;
            strategy: "sequential";
            threshold5h: number;
            threshold7d: number;
        };
    } | {
        applyMode?: "merge" | "replace" | "repair" | undefined;
        activeAccountIndex?: number | undefined;
        applyGeneration: number;
        provider: "codex";
        configured: boolean;
        status: "authenticated";
    }>;
    groupSync: (input: CredentialGroupRequest) => Promise<{
        provider: GroupProvider;
        generation: number;
        fingerprint: string;
        payloadDigest: string | null;
        reconciled: boolean;
        assignmentGeneration: number;
        leaseId: string | null;
        appliedCredentials: AppliedCredentialReceipt[];
        principalType: "machine";
        machineId: string | undefined;
        version: 1;
        scope: string;
    } | {
        provider: GroupProvider;
        generation: number;
        fingerprint: string;
        payloadDigest: string | null;
        reconciled: boolean;
        assignmentGeneration: number;
        leaseId: string | null;
        appliedCredentials: AppliedCredentialReceipt[];
        userId: string;
        version: 1;
        scope: string;
    }>;
    setupTokenGroupSync: (input: unknown, machineId: string, recipient: SetupTokenAssignmentRecipient) => Promise<{
        provider: GroupProvider;
        generation: number;
        fingerprint: string;
        payloadDigest: string | null;
        reconciled: boolean;
        assignmentGeneration: number;
        leaseId: string | null;
        appliedCredentials: AppliedCredentialReceipt[];
        principalType: "machine";
        machineId: string | undefined;
        version: 1;
        scope: string;
    } | {
        provider: GroupProvider;
        generation: number;
        fingerprint: string;
        payloadDigest: string | null;
        reconciled: boolean;
        assignmentGeneration: number;
        leaseId: string | null;
        appliedCredentials: AppliedCredentialReceipt[];
        userId: string;
        version: 1;
        scope: string;
    }>;
    releaseSetupTokenAccounts: (managedAccountIds: string[]) => Promise<boolean>;
    groupReceipt: (scope: string, selected: "claude" | "codex", principal?: {
        principalType: "machine";
        machineId: string;
    }) => Promise<{
        provider: GroupProvider;
        generation: number;
        fingerprint: string;
        payloadDigest: string | null;
        reconciled: boolean;
        assignmentGeneration: number;
        leaseId: string | null;
        appliedCredentials: AppliedCredentialReceipt[];
        principalType: "machine";
        machineId: string | undefined;
        version: 1;
        scope: string;
    } | {
        provider: GroupProvider;
        generation: number;
        fingerprint: string;
        payloadDigest: string | null;
        reconciled: boolean;
        assignmentGeneration: number;
        leaseId: string | null;
        appliedCredentials: AppliedCredentialReceipt[];
        userId: string;
        version: 1;
        scope: string;
    } | null>;
    purge: (input: {
        provider: AiCredentialProvider;
        leaseId: string;
    }) => Promise<{
        provider: AiCredentialProvider;
        purged: boolean;
        alreadyPurged: boolean;
    }>;
    status: (input: {
        provider: AiCredentialProvider;
    }) => Promise<{
        provider: "zai";
        configured: boolean;
        accountCount: number;
    } | {
        rotation: {
            state: "running" | "blocked" | "quota-unknown" | "not-routed";
            lastErrorKind: null;
            strategy: "sequential";
            threshold5h: number;
            threshold7d: number;
        };
        activeAccount?: string | undefined;
        provider: "codex";
        configured: boolean;
        accountCount: number;
    } | {
        rotation: AiCredentialRotationStatus;
        tokenRuntime?: {
            version: number;
            state: string;
            accounts: any;
        } | undefined;
        credentialKind?: "api_key" | "oauth" | undefined;
        setupToken?: {
            version: 1;
            accounts: SetupTokenAccountStatus[];
        } | undefined;
        accountCount: number;
        activeAccountStatus: "unknown" | "disabled" | "not-selected" | "usage-readable" | "api-key" | "relogin-required";
        usableAccountCount: number;
        reloginRequiredAccountCount: number;
        configured: boolean;
        activeAccount: string | null;
        provider: "claude";
    }>;
    verify: (input: {
        provider: AiCredentialProvider;
        accounts?: VerificationIdentity[];
        scope?: "active" | "accounts";
    }) => Promise<{
        checkedAt: number;
        accounts: AccountVerification[];
    } | {
        scope: "active";
        activeAccountNumber: number | null;
        activeAccount: string;
        checkedAt: number;
        accounts: AccountVerification[];
    }>;
    rotation: (input: {
        action: "start" | "stop";
    }) => Promise<{
        provider: "claude";
        credentialKind: "api_key";
        rotation: AiCredentialRotationStatus;
    } | {
        provider: "claude";
        rotation: AiCredentialRotationStatus;
        credentialKind?: undefined;
    }>;
    sessionEnvironment: (agent: string | undefined, selection?: AiAuthSelection, recorded?: SetupTokenBinding) => Promise<Record<string, string>>;
    capabilities: (machineId?: string) => Promise<{
        newSessionProfileBinding: boolean;
        setupTokenSessionBindingVersion: number;
        setupTokenCredentialProofVersion: number;
        setupTokenVersion?: number | undefined;
        setupTokenStatusVersion?: number | undefined;
        groupAssignmentVersion: number;
        sharedMachineAssignmentVersion: number;
        setupTokenResumeRequirementVersion: number;
        activeSelectionVersion: number;
        verificationVersion: number;
        verificationScopes: string[];
        applyModes: string[];
        collectorProbeVersion?: number | undefined;
        collectorMachinePrincipalVersion?: number | undefined;
        tokenProbeVersion?: number | undefined;
        version: number;
        codexRecoveryVersion: number;
        codexRefreshOwnerVersion: number;
        claudeRefreshOwnerVersion: number;
        orgLlmEndpointVersion: number;
        orgLlmEndpointModelBindingVersion: number;
        personalLlmEndpointVersion: number;
        credentialDeliveryVersion: number;
    } | {
        newSessionProfileBinding: boolean;
        setupTokenVersion?: number | undefined;
        setupTokenStatusVersion?: number | undefined;
        groupAssignmentVersion: number;
        sharedMachineAssignmentVersion: number;
        setupTokenResumeRequirementVersion: number;
        activeSelectionVersion: number;
        verificationVersion: number;
        verificationScopes: string[];
        applyModes: string[];
        collectorProbeVersion?: number | undefined;
        collectorMachinePrincipalVersion?: number | undefined;
        tokenProbeVersion?: number | undefined;
        version: number;
        codexRecoveryVersion: number;
        codexRefreshOwnerVersion: number;
        claudeRefreshOwnerVersion: number;
        orgLlmEndpointVersion: number;
        orgLlmEndpointModelBindingVersion: number;
        personalLlmEndpointVersion: number;
        credentialDeliveryVersion: number;
    }>;
};
type AiCredentialRuntime = ReturnType<typeof createAiCredentialRuntime>;

interface AutonomousQualityGateRpcHandlers {
    start(params: unknown): Promise<unknown>;
    status(params: unknown): Promise<unknown>;
    control(params: unknown): Promise<unknown>;
}

type CheckpointRpcHandlers = {
    status(params: unknown): Promise<unknown>;
    list(params: unknown): Promise<unknown>;
    preview(params: unknown): Promise<unknown>;
    retireWorktree?(params: unknown): Promise<unknown>;
    diff?(params: unknown): Promise<unknown>;
    execute(params: unknown): Promise<unknown>;
    retry(params: unknown): Promise<unknown>;
    cancel(params: unknown): Promise<unknown>;
    decision(params: unknown): Promise<unknown>;
    restart(params: unknown): Promise<unknown>;
    refresh?(params: unknown): Promise<unknown>;
};

/** What the daemon can answer about its own link to the server. */
interface MachineConnectionHealth {
    /** A live socket exists right now. */
    connected: boolean;
    /** A retry cadence is in flight. Meaningless while `connected`. */
    reconnecting: boolean;
    /** Milliseconds since the socket was last up, or null while connected. */
    disconnectedForMs: number | null;
}
type MachineRpcHandlers = {
    sessionRetention?: SessionRetention;
    /** aplus-dev-studio specs/cross-machine-agent-delegation. Absent = no links, no lane, no advertisement. */
    agentDelegation?: AgentDelegationHost;
    ownedSpawn?: OwnedSpawnRpc;
    orgSubagent?: ReturnType<typeof createOrgSubagentRuntime>;
    daemonSessionState?: (request: unknown) => Promise<DaemonSessionStateResponse>;
    spawnSession: (options: SpawnSessionOptions) => Promise<SpawnSessionResult>;
    resumeSession?: (sessionId: string, options?: {
        model?: string;
        permissionMode?: string;
        environmentVariables?: Record<string, string>;
        mcpCallerGrantEnvelope?: string;
        mcpConfigProjectId?: string;
        personalChatId?: string;
        expectedConnectors?: string[];
        /** Present = authoritative (empty withdraws every root); absent = keep the session's roots. */
        additionalDirectories?: string[];
        aiAuthRequirement?: ResumeAuthRequirement;
        personalEndpoint?: PersonalEndpointSelection;
        /** Checked at this boundary (launchMcpServers.ts); absent = no injected MCP servers. */
        launchMcpServers?: LaunchMcpRequest;
    }) => Promise<ResumeSessionResult>;
    recoverSession?: (sessionId: string, options: RecoverSessionOptions) => Promise<RecoverSessionResult>;
    stopSession: (sessionId: string, context?: StopSessionContext) => StopSessionResult;
    /**
     * Stop plus proof that the session's processes are gone. Used only for a
     * `verifyExit: true` request; absent on a daemon build without it, which
     * answers such a request with the legacy stop and `unavailable` evidence.
     */
    stopSessionWithExitVerification?: (sessionId: string, context?: StopSessionContext) => Promise<{
        result: StopSessionResult;
        exitVerification: SessionExitVerification;
    }>;
    requestShutdown: () => void;
    /**
     * aplus codexcli-daemon-restart-drain R25 "지금 교대": pulls a pending bundle handoff forward.
     * Narrower than `stop-daemon` — it can only hasten a handoff whose bundle is already installed,
     * never start a restart or stop.
     */
    forceRestartHandoff?: () => Promise<{
        ok: true;
        deadlineAt: number;
    } | {
        ok: false;
        code: 'no-pending-handoff' | 'replacement-unavailable';
    }>;
    portRegistry: PortRegistry;
    /** When present, registers the scheduled-automation RPCs and advertises automationSupport. */
    automationStore?: AutomationStore;
    /**
     * Reports a freshly spawned session to A+ so it lands in the project's conversation list
     * (specs/daemon-spawn-project-link). Absent on a plain Happy daemon.
     *
     * The spawn path awaits this bounded bookkeeping attempt before returning so Desktop cannot
     * observe lineage before the project can load the child. Failure still leaves spawn successful.
     */
    linkSpawnedSession?: (input: {
        sessionId: string;
        directory: string;
    }) => void | Promise<void>;
    /**
     * Whether a browser task of the session waits for the user (Agent Browser). A run-once host (Studio
     * Chat(beta)) keeps the session instead of deleting it, so the attention after an approval or a login
     * can resume it. Absent on a machine without the browser runtime.
     */
    browserSessionPrepare?: (sessionId: string) => Promise<{
        supported: boolean;
        reconnect?: boolean;
    }>;
    browserSessionWaiting?: (sessionId: string) => Promise<boolean>;
    aiCredentialRuntime: AiCredentialRuntime;
    setupTokenCapacityBarrier?: (input: unknown) => Promise<unknown>;
    autonomousQualityGate?: AutonomousQualityGateRpcHandlers;
    checkpoint?: CheckpointRpcHandlers;
    /**
     * BYOS offline delivery, when the daemon wired it.
     *
     * Absent on a daemon that has no parent origin configured: without one the
     * receiver cannot ask whether a delivery is authorized, and registering a
     * handler that can only ever hold would make the parent wait for a person
     * on every request.
     */
    byosOfflineReceive?: ByosOfflineRpcHandlers;
    difficultyRouting?: DifficultyRoutingClassifierHost;
    /**
     * Desktop's sealed settings call to the daemon channel host (Saycode
     * specs/happy-cli-channel-host). Present only on a daemon that supervises a host; it answers
     * with the host's sealed reply or a closed code and never throws, so no error text reaches
     * the generic RPC error log.
     */
    channelHostCall?: (params: unknown) => Promise<unknown>;
};
declare class ApiMachineClient {
    private token;
    private machine;
    private readonly deviceKeys?;
    private readonly deviceEnrollment?;
    private readonly admitSubprocess?;
    private readonly reserveLegacyDispatch?;
    private socket;
    /** Set when the managed credential ended; suppresses every reconnect. */
    private credentialStopped;
    private keepAliveInterval;
    private runtimeActivityProvider;
    /** aplus codexcli-daemon-restart-drain R6·R22 — current drain / pending handoff, null while running normally. */
    private restartLifecycleProvider;
    /** aplus terminal-survive-runner-restart HR4·HR10 — null while terminal workers are off. */
    private terminalSurvivalProvider;
    private lastKnownCLIAvailability;
    private lastKnownResumeSupport;
    private lastKnownCliVersion;
    /**
     * The keep-alive capability update awaiting the server, if any; see `publishKeepAlive`. Its own
     * object, so a late settle of an update that was given up on cannot clear a newer one.
     */
    private capabilityUpdateInFlight;
    private automationRpcAvailable;
    private lastKnownAutomationRpcAvailable;
    private autonomousQualityGateRpcAvailable;
    private lastKnownAutonomousQualityGateRpcAvailable;
    private automationKey;
    private authenticatedEnvelopeSender;
    private authenticatedEnvelopesRequired;
    /** Set once the daemon can resolve projects to workspaces. */
    private lessonHosts;
    private automationProtocolVersion;
    private automationContextHostReady;
    private automationContextIsolationVersion;
    private automationContextReadinessEpoch;
    private readonly automationKeyRegistration;
    private scriptRuntimeReadiness;
    private lastKnownScriptRuntimeKey;
    /** specs/scheduled-missed-run-policy R14 — the last automation sync said the server honours `catchUp` claims. */
    private automationCatchUpClaim;
    private persistAutomationKeyVersion;
    private automationServerKeyVersion;
    private automationLegacyFallbackEnabled;
    private lastKnownAutomationServerKeyVersion;
    private serverAutomationCache;
    private serverAutomationSyncInFlight;
    private rpcHandlerManager;
    /** General daemons reuse the protected device key; managed runtimes keep their existing ephemeral recipient. */
    private readonly setupTokenAssignmentRecipient;
    /**
     * The machine's only resource sampler. It measures nothing until something
     * subscribes and stops again when the last subscription goes away, so an
     * unwatched daemon costs exactly one idle object (specs/machine-resource-metrics).
     */
    private readonly machineResourceService;
    /** Remembers bound terminal opens across reconnects, so one recorded open opens one shell. */
    private readonly terminalOpenNonceGuard;
    private readonly openingTerminals;
    private previewWsProxy;
    /**
     * specs/runtime-isolation-hardening (H3, P2) — opens whose binding is
     * still being verified.
     *
     * Verification runs before the upstream is touched and can take a while
     * (a saturated probe queue, a slow docker call). happy-server's open
     * deadline can pass during that window, and the close it sends then finds
     * nothing: previewWsProxy has no record of a tunnel that has not started
     * connecting. Without this the upstream is opened afterwards anyway — a
     * ghost with no owner, no expiry timer and no recheck behind it.
     *
     * Only ids with an open actually in flight are held, and each is removed
     * when its open finishes: a map of every tunnel id ever seen would be
     * unbounded and fed by the network.
     */
    private previewWsPendingOpens;
    private previewEvidenceIo;
    private previewProbe;
    private previewPortRegistry;
    private previewPathCanonicalizer;
    private viewer;
    private viewerStartInFlight;
    /** Set only on a verified managed runtime; null on every BYOS machine. */
    private managedHandlers;
    private windowsStandaloneTrial;
    private daemonSessionStateRpcAvailable;
    /** What the channel host child last said it can serve; undefined while it is not ready. */
    private channelHostAdvertisement;
    private isolatedViewerStarts;
    private isolatedViewerMutation;
    private isolatedViewerRegistry;
    private browserSessionBroker;
    private brokerRelayTouchedAt;
    /**
     * specs/runtime-isolation-hardening (H3, P3) — one gate for the whole
     * daemon, so the per-machine cap on viewer proof work is real. Reuses the
     * project probe's measured limits (8 concurrent, 256 queued); the budget
     * is per call and defaults to DEFAULT_VIEWER_PROOF_DEADLINE_MS.
     */
    private viewerProofGate;
    private browserCdpPipes;
    private resumeSessionHandler;
    private recoverSessionHandler;
    private linkSpawnedSessionHandler;
    private allowedRoot;
    /** aplus-dev-studio specs/approved-folder-roots — folders outside allowedRoot the machine owner approved. */
    private approvedRoots;
    /**
     * The pending next dial. Non-null means "a retry cadence is running", which
     * is all `getConnectionHealth()` and the connection supervisor read it for.
     */
    private reconnectInterval;
    /** Consecutive dials since the last successful connect. Drives the backoff. */
    private reconnectAttempts;
    /**
     * When the outstanding `socket.connect()` was issued, or null when no dial
     * is out. specs/machine-socket-duplicate-registration/ — this is the
     * single-flight guard: the old cadence dialled every 3s regardless, so a
     * slow handshake collected several overlapping dials and several of them
     * completed, leaving the server holding more than one live machine socket.
     */
    private reconnectDialStartedAt;
    /**
     * `shutdown()` 이 시작됐는가.
     *
     * `socket.close()` 는 `disconnect` 를 발생시키고, 그 핸들러가 재연결 cadence 를
     * 다시 켠다. 정리하려고 끈 타이머가 끄는 그 동작 때문에 되살아나는 것이라,
     * 종료 절차가 이벤트 루프를 놓지 못하고 run.ts 의 1초 fallback 에 걸려
     * `forcing exit with code 1` 로 끝난다. 강제 종료는 정리를 건너뛰므로 서버는
     * 소켓이 죽은 줄 ping 예산이 다 될 때까지 모른다 — 재시작 한 번이 필요 이상으로
     * 긴 오프라인이 되는 경로다.
     *
     * apiSession 은 같은 결함을 `closed` 플래그로 이미 막아 뒀다(2026-09-05:
     * 닫은 세션이 1초 뒤 되살아나 프로세스가 2시간 11분 남았던 건). 여기에는
     * 그 대응물이 없었다.
     */
    private shuttingDown;
    private connectionSupervisorInterval;
    private companyKeyReseedAvailable;
    private agentDelegationAvailable;
    /** When the socket was last known to be down. Null only while connected. */
    private disconnectedSince;
    /** Process identity is not replicated state: a server conflict can contain the previous daemon. */
    private readonly processState;
    constructor(token: string, machine: Machine, deviceKeys?: DeviceKeys | undefined, deviceEnrollment?: ReturnType<typeof createDeviceEnrollment> | undefined, processState?: DaemonState | null, withFilesystemMutation?: CommonHandlerOptions['withFilesystemMutation'], admitSubprocess?: CommonHandlerOptions['admitSubprocess'], reserveLegacyDispatch?: ((roots: readonly string[]) => Promise<LegacyDispatchReservation>) | undefined);
    /**
     * Registers a listener for an event the server sends with an ack. An event that
     * arrives without one is dropped before any side effect (hasAck), and a listener
     * that fails is logged instead of rejecting: socket.io does not await listeners,
     * and the daemon shuts down on an unhandled rejection, so one failed request would
     * otherwise take every session on the machine down with it.
     */
    private onAcked;
    /** Internal opt-in trial policy; install before connecting the machine transport. */
    setWindowsStandaloneTrial(): void;
    /**
     * Enables the managed dispatch surface. Must be called before
     * `setRPCHandlers`, which applies the restrictions as its last step.
     */
    setManagedRuntime(handlers: ManagedRpcHandlers): void;
    /**
     * The channel host's advertisement, or undefined to withdraw it. Published by the keep-alive,
     * which compares with the server's copy: the child becomes ready after registration and can
     * die at any time, so a startup-only publish would go stale.
     */
    setChannelHostAdvertisement(advertisement: MachineMetadata['channelHost']): void;
    /**
     * aplus specs/e2ee-machine-control-boundary F8: `datakey:reseed`, customer lane only. The daemon
     * sets it on a strict machine that can pin an organization key; the capability follows it.
     */
    setCompanyKeyReseedHandler(handler: (params: unknown) => Promise<unknown>): void;
    setRPCHandlers({ sessionRetention, daemonSessionState, spawnSession, resumeSession, recoverSession, stopSession, stopSessionWithExitVerification, requestShutdown, forceRestartHandoff, portRegistry, automationStore, aiCredentialRuntime, setupTokenCapacityBarrier, autonomousQualityGate, checkpoint, byosOfflineReceive, linkSpawnedSession, difficultyRouting, browserSessionWaiting, browserSessionPrepare, channelHostCall, ownedSpawn, orgSubagent, agentDelegation, }: MachineRpcHandlers): void;
    /**
     * specs/runtime-isolation-hardening (H3). Null until `setRPCHandlers` has
     * run: without the port registry the daemon cannot spot a port that is
     * registered to another project, and a partial check is not the check.
     */
    private previewLeaseDeps;
    /**
     * specs/runtime-isolation-hardening (H3, P3) — the viewer counterpart of
     * `previewLeaseDeps`.
     *
     * The mode is decided once, here, by whether a root broker is configured,
     * and there is **no fallback between the two**. In broker mode the native
     * registry describes nothing that is running, so reading it after a failed
     * broker lookup would not be a second opinion — it would be a first
     * opinion about the wrong machine state.
     */
    private viewerLeaseDeps;
    /**
     * The unbounded proof itself. Mode is picked per call because the broker
     * may be configured after construction; there is no fallback between the
     * two — in broker mode the native registry describes nothing running.
     */
    private resolveViewerEvidence;
    /**
     * Same gate as the project relay, over the viewer variant. There is no
     * `unbound` outcome: these events exist only for bound requests, so an
     * absent binding is a caller error rather than an older server.
     */
    private enforceViewerBinding;
    /** Handler body of the `preview-viewer-runtime-lease` socket event. */
    private answerPreviewViewerRuntimeLease;
    private relayPreviewViewerBoundHttp;
    /**
     * Viewer upgrades. Shares the whole cancellation / supersede / close
     * machinery with the project tunnel — a second copy would drift, and the
     * expiry and revocation behaviour is exactly what must not differ.
     */
    private openPreviewViewerWsTunnelBound;
    /**
     * specs/runtime-isolation-hardening (H3) — prove that the runtime still
     * answering on this port is the one the token was minted for, before any
     * bytes are relayed. `bindingEnforced` is echoed on success: it is the
     * only way happy-server can tell an enforcing daemon apart from one that
     * silently ignored the binding fields.
     */
    /**
     * Same binding gate as the HTTP relay: a tunnel is a relayed request too,
     * and leaving it unchecked would make the upgrade path the way around the
     * binding.
     */
    /**
     * Bound upgrades arrive here instead. Since this event exists only for
     * them, serving it unbound would give the whole separation away.
     */
    private openPreviewWsTunnelBound;
    private openPreviewWsTunnel;
    private closePreviewWsTunnel;
    /** Daemon socket dropped: nothing in flight can still be wanted. */
    private cancelPreviewWsTunnels;
    private relayPreviewBoundHttp;
    private relayPreviewHttp;
    private enforcePreviewBinding;
    /**
     * Handler body of the `preview-runtime-lease` socket event (mint time).
     * Answers inside happy-server's 3 s ack window: a probe that cannot finish
     * by then is reported as EVIDENCE_BUSY rather than left to ack late.
     */
    private answerPreviewRuntimeLease;
    /**
     * Binds the lesson hosts for this daemon.
     *
     * Late-bound because resolving a project to a workspace needs the
     * authoritative bindings the daemon accumulates as sessions start, and the
     * studio key needs credentials this client does not own. Replacing an
     * existing supervisor closes it, so a re-bind cannot leave a second store
     * open on the same project.
     */
    setLessonHosts(hosts: LessonHostSupervisor | null): Promise<void>;
    /**
     * Published under automationSupport.scriptRuntime. Before the socket is up this only records the
     * values; afterwards a change re-registers the same automation key with the new protocol (the
     * server updates the target without bumping the key) and republishes the metadata.
     */
    updateScriptRuntime(readiness: ScriptRuntimeReadiness, protocolVersion: number): void;
    private scriptRuntimeField;
    /**
     * specs/scheduled-missed-run-policy R14 — Desktop offers the per-schedule missed-run choice only on this.
     * Advertised only when this daemon runs server-backed automations against a server that accepts late
     * `catchUp` claims; an old server ignores the field, so "run once when back" would quietly do nothing.
     */
    private automationMissedRunPolicyField;
    private refreshAutomationCatchUpClaim;
    setAutomationKey(key: MachineAutomationKey, persistVersion: (version: number) => void, protocolVersion?: number): void;
    /** Trusted daemon composition, before connect. A protocol number cannot enable the private host. */
    setAutomationContextIsolationReady(ready: boolean): void;
    /**
     * aplus-dev-studio specs/e2ee-machine-control-boundary R12/R15 — the sender this daemon
     * trusts for automations, follow-ups and scripts, or null when it has none (legacy
     * credentials). With one, the machine metadata tells clients to seal with it, to which
     * automation key, and whether this daemon refuses anonymous payloads (`required`, under
     * strict). The metadata is encrypted with the machine key, so a server without that key
     * can neither read nor forge the advertisement. It is only as genuine as the machine
     * key envelope a client unwraps, which nothing yet authenticates.
     */
    setAuthenticatedEnvelopeSender(publicKey: Uint8Array | null, options?: {
        required: boolean;
    }): void;
    private authenticatedEnvelopesField;
    setServerAutomationCache(cache: ServerAutomationCache): void;
    shouldRunLegacyAutomationScheduler(): boolean;
    serverAutomationTransport(): ServerAutomationTransport;
    /**
     * 자동화 tick 은 이 ack 를 await 한다. 상한 없이 기다리면 서버가 ack 를 한 번만 빠뜨려도
     * tick 이 영원히 끝나지 않고, 이 머신의 GitHub 트리거·예약 전체가 데몬 재시작 전까지
     * 조용히 멈춘다 (2026-10-22, 2026-10-24 — 소켓과 다른 ack 는 모두 정상이었다).
     * 타임아웃은 전송 실패로 돌려 다음 tick 이 claim·보고를 다시 시도하게 한다.
     */
    private automationAck;
    deliverAutomationConversation(input: AutomationConversationDeliverRequest): Promise<{
        ok: boolean;
        value?: unknown;
        error?: string;
    }>;
    sessionFollowupTransport(): SessionFollowupTransport;
    /**
     * Idempotent: returns the running stack if one is already up. Shared by
     * the `browser-viewer:start` RPC and `browser-setup:launch`'s `viewer`
     * option, so "launch Chrome under the viewer" never spins up a second,
     * disconnected Xvfb (specs/browser-remote-login/).
     *
     * Runs under the same mutation as the per-user starts. Its own in-flight
     * entry only collapses concurrent callers of *this* path; both paths draw
     * displays and ports from one pool, so without the shared lock they can
     * pick the same slot and each report the other's server as their own.
     */
    private startViewerStack;
    private startViewerStackOnce;
    private startIsolatedViewerStack;
    private startBrokerViewer;
    private touchBrokerViewerPort;
    private withIsolatedViewerMutation;
    private startIsolatedViewerStackOnce;
    /**
     * Brings up the display and VNC server for one viewer slot.
     *
     * Two backends, chosen by what the machine has. TigerVNC's Xvnc accepts
     * the client's `SetDesktopSize`, which is the only way the remote screen
     * can become exactly the size of the user's window — noVNC otherwise
     * draws a fixed 1920x1080 desktop clipped into whatever window it gets
     * (reported 2026-09-19). Machines with only the older Xvfb + x11vnc pair
     * keep working, scaled rather than clipped.
     *
     * The window manager is not decoration: a desktop that resizes under a
     * browser window nothing re-maximizes is worse than one that does not
     * resize at all, so `selectViewerBackend` only asks for remote resizing
     * when openbox is there to refit the window.
     */
    /**
     * The display for this slot, or the next slot that will have one.
     *
     * A display can be refused for reasons no port reveals — another X server
     * already on it, its pids recorded nowhere. Failing the whole start there
     * would turn one unusable slot into no remote screen at all, so the slot
     * is marked taken and the next is tried. `slot` is reassigned, so the
     * caller records the lease against the one that actually opened.
     */
    private startViewerDisplayOnSlot;
    private startViewerDisplay;
    private startViewerDisplayOnce;
    private buildViewerWebRoot;
    /**
     * Whether the noVNC port actually answers, and a log line when it does
     * not.
     *
     * The caller turns a false here into `ready: false`, which the studio
     * surfaces as "원격 화면이 응답하지 않습니다" rather than opening a relay
     * URL onto a port that resets every connection. Logged at warn because
     * the whole of the 2026-09-21 outage left no daemon-side trace at all:
     * the failure was only visible three layers away, as ECONNRESET in the
     * server's relay log.
     */
    private awaitViewerServing;
    /**
     * Ends a viewer stack and waits for its web port to come free.
     *
     * SIGTERM returns long before the port is released, and slot selection
     * reads "still bound" as "occupied" — so without the wait a reap frees a
     * slot and then declines to use it. The escalation is what keeps the slot
     * recoverable at all: once the lease naming these pids is gone, nothing
     * else knows what is holding the port, and with three slots on a machine
     * that is a third of its capacity until it reboots.
     */
    private reapViewerStack;
    private signalViewerGroups;
    /**
     * Both halves of letting go. The processes, because an Xvfb has no port
     * and would otherwise look gone; and the ports, because a signal returns
     * long before the kernel takes the listener back and the slot loop right
     * after this reads "still bound" as "occupied".
     */
    private waitForViewerStackGone;
    /**
     * Every pid that looks like it is running this slot's stack.
     *
     * Two sources, because neither alone is enough. The lease's own pids are
     * the cheap answer, but a leader can exit while the worker it forked keeps
     * the listener — websockify does exactly that — and then `/proc/<leader>`
     * is gone. So `/proc` is swept as well, which finds a group through any
     * surviving member and also finds a stack whose pids were never recorded.
     *
     * Deliberately generous: this answers "is this slot taken", where a false
     * positive costs a slot and a false negative costs a user their screen.
     * It is not enough to kill on — see {@link ownedViewerGroups}.
     */
    private viewerSlotPids;
    /**
     * The process groups this daemon may end for a slot.
     *
     * A command line says which slot a process is on, not who started it:
     * `Xvfb :99` is a command anyone here can run, and the match is loose
     * enough that `tail -f /tmp/Xvfb :99` satisfies it. Good enough to
     * reserve a slot, nowhere near good enough to signal a process group —
     * which reaches that process's siblings too. So every candidate has to
     * carry this daemon's marker in its environment before its group becomes
     * a target. A viewer from an older CLI has no marker and is left alone:
     * its slot reads occupied, which loses a screen rather than someone
     * else's work.
     */
    private ownedViewerGroups;
    /**
     * Puts a browser on the viewer display, or reuses the one already there.
     *
     * Without this the viewer is a black screen: Xvfb renders nothing on its
     * own, and the "원격 브라우저 화면 열기" flow never called the launch
     * path. Reuse is probed rather than cached so a browser that outlived the
     * daemon is adopted instead of a second Chrome being stacked onto the
     * same display, one per click.
     */
    private ensureViewerBrowser;
    /**
     * The shared browser-pairing contract behind both the explicit setup RPC
     * and the noVNC viewer. Keeping the existing runPairing sequence here
     * preserves extension injection, token storage, and debugger-tier checks.
     */
    private pairBrowser;
    /** Pairing failure must not hide the login screen used to repair it. */
    private pairViewerBrowser;
    private rememberBrowserCdpPipe;
    private requestServerAutomationSync;
    /** The Windows standalone runtime fences sessions only; script gates and GitHub triggers run outside its Job. */
    private automationHostCommandsField;
    private registerAutomationKey;
    private performAutomationKeyRegistration;
    private syncResumeSessionRpcRegistration;
    private syncRecoverSessionRpcRegistration;
    /**
     * Update machine metadata
     * Currently unused, changes from the mobile client are more likely
     * for example to set a custom name.
     */
    updateMachineMetadata(handler: (metadata: MachineMetadata | null) => MachineMetadata): Promise<void>;
    private acceptDaemonState;
    /**
     * Update daemon state (runtime info) - similar to session updateAgentState
     * Simplified without lock - relies on backoff for retry
     */
    updateDaemonState(handler: (state: DaemonState | null) => DaemonState): Promise<void>;
    /**
     * Takes up a renewed credential — by **re-authenticating**, not by
     * relabelling.
     *
     * Two things made the obvious version wrong.
     *
     * The handshake is what presents the credential, and it reads `socket.auth`
     * at connect time, so changing only the field the constructor was given
     * left every reconnect presenting the expired token: the connection alive
     * today keeps working, and the first network flap ends the runtime in a way
     * that reads as a network fault and never resolves.
     *
     * And the live connection is **not** fine as it is. The server re-reads the
     * grant on every event against the token the handshake carried, and a
     * renewal supersedes the previous grant — after a short grace in which the
     * renewal itself is delivered over this very socket (the server's
     * `MANAGED_DAEMON_RENEWAL_GRACE_MS`). A connection still presenting the
     * old bearer is refused once that grace ends, and dropped by the server's
     * own revalidation shortly after. An earlier version of this comment
     * claimed a live socket did not need the new token; that was wrong, and
     * this is the correction.
     *
     * So the connection is dropped and the reconnect path brings it back
     * authenticated with the new bearer, re-registering its RPC methods as any
     * reconnect does. A few seconds of connection is the cost; the alternative
     * is a runtime that looks connected while every request it makes is
     * refused.
     */
    replaceToken(token: string): void;
    /**
     * Stops presenting a credential that is no longer valid, and stops working.
     *
     * Called when the credential expired and no renewal replaced it. The socket
     * is closed and reconnection is not attempted: a runtime that kept retrying
     * with a dead credential would look like a connectivity failure to
     * everybody, while the real answer — this runtime is no longer authorised —
     * is one the parent already knows.
     */
    stopForExpiredCredential(): void;
    /**
     * A relay terminal's exit. A v2 terminal says it sealed first — the only close its client
     * shows as an exit — and then in plaintext, which the relay keeps to answer a late resume.
     */
    private emitTerminalClosed;
    /** A v2 relay terminal's sealed frame: shared rules, relay delivery. */
    private receiveBoundTerminalFrame;
    connect(): void;
    private startKeepAlive;
    setRuntimeActivityProvider(provider: () => {
        activeSessionCount: number;
        activeAutomationCount: number;
        inTurnCount?: number;
    }): void;
    setRestartLifecycleProvider(provider: () => DaemonRestartLifecycle | null): void;
    setTerminalSurvivalProvider(provider: () => TerminalSurvivalState | null): void;
    /** Push the drain state now instead of waiting for the next keep-alive (R6). */
    publishRestartLifecycle(): void;
    /**
     * R23: close every daemon terminal before a restart, while the socket is still
     * up so each `terminal-closed` carries `reason: 'daemon-restart'`.
     */
    closeDaemonTerminalsForRestart(survives?: Parameters<typeof closeAllDaemonTerminalSessionsForRestart>[0]): Promise<number>;
    /**
     * What this daemon can honestly say about its link to the server.
     *
     * Read by the daemon heartbeat so the local state file records a socket
     * that is down instead of a bare `running` that is true of the process
     * and false of everything anyone actually wants from it.
     */
    getConnectionHealth(): MachineConnectionHealth;
    private startConnectionSupervisor;
    private stopConnectionSupervisor;
    private startSmartReconnect;
    /** Ends the cadence and forgets any dial it was waiting on. */
    private stopSmartReconnect;
    /**
     * True while a `socket.connect()` is still waiting for `connect` or
     * `connect_error`. Expires on its own so a handshake that resolves with
     * neither cannot wedge the cadence shut.
     */
    private isReconnectDialInFlight;
    private scheduleReconnectDial;
    private stopKeepAlive;
    shutdown(): void;
}

interface PushToken {
    id: string;
    token: string;
    createdAt: number;
    updatedAt: number;
}
type SessionNotificationKind = 'done' | 'permission' | 'question';
declare class PushNotificationClient {
    private readonly token;
    private readonly baseUrl;
    private readonly expo;
    constructor(token: string, baseUrl?: string);
    /**
     * Fetch all push tokens for the authenticated user.
     * Retries up to 3 times with exponential backoff on transient errors.
     */
    fetchPushTokens(): Promise<PushToken[]>;
    /**
     * Send push notification via Expo Push API with retry
     * @param messages - Array of push messages to send
     */
    sendPushNotifications(messages: ExpoPushMessage[]): Promise<void>;
    /**
     * Send a push notification to all registered devices for the user
     * @param title - Notification title
     * @param body - Notification body
     * @param data - Additional data to send with the notification
     */
    sendToAllDevices(title: string, body?: string, data?: Record<string, any>): void;
    /**
     * Routes session-event pushes through the server so it can apply
     * presence-based suppression (active desktop/web, mobile foreground).
     * Falls back to direct Expo send only when sessionId is missing — that
     * shouldn't happen for session notifications but guards against regressions.
     */
    sendSessionNotification(params: {
        kind: SessionNotificationKind;
        metadata: Metadata | null | undefined;
        data?: Record<string, any>;
    }): void;
}

/** Creation response only; never session metadata, provider state or event wire. */
declare const ownershipCreatedSchema: z$1.ZodObject<{
    sessionId: z$1.ZodString;
    ownershipBindingId: z$1.ZodString;
    registrationState: z$1.ZodEnum<{
        pending: "pending";
        confirmed: "confirmed";
    }>;
    createDigest: z$1.ZodString;
}, z$1.core.$strict>;
type OwnershipCreatedReceipt = z$1.infer<typeof ownershipCreatedSchema>;
declare class ApiClient {
    static create(credential: Credentials): Promise<ApiClient>;
    /**
     * A client for a session this process did not create.
     *
     * It holds a bearer scoped to one session and nothing else. There is no
     * account credential here — not a stand-in, not a cast — so the
     * account-shaped members are simply unreachable: `accountCredential()`
     * refuses, and the paths that need account encryption material or a push
     * registration go through it.
     */
    static managed(attachment: ManagedAttachment): ApiClient;
    private readonly principal;
    private readonly pushClient;
    private constructor();
    /**
     * A client for a Machine the trusted parent already registered.
     *
     * It never creates: `getOrCreateMachine` refuses for this principal, and the
     * attach path below reads. Registration would either fail (the bearer is not
     * the account's) or, worse, overwrite key material the server treats as
     * write-once — after which nothing could read the machine again.
     */
    static managedMachine(input: {
        machineId: string;
        token: string;
        machineKey: Uint8Array;
        /** The Happy this credential was issued for, as the parent recorded it. */
        serverOrigin: string;
        usageRecoveryRoot?: string;
    }): ApiClient;
    /**
     * Create a new session or load existing one with the given tag
     */
    /**
     * The account this client acts for, or a refusal.
     *
     * Reached only by code that genuinely needs account material. A managed
     * session has none, and saying so here is the whole point of the split.
     */
    private accountCredential;
    /** The bearer this client presents, whichever principal it is. */
    private bearer;
    /**
     * Reads the Machine this runtime **is**, and refuses anything else.
     *
     * Three things it deliberately does not do:
     *
     *  - **It does not create.** The Machine exists; the parent registered it
     *    with key material the server treats as write-once.
     *  - **It does not derive or wrap keys.** The key arrives from the parent
     *    through the protected credential. Deriving one here would produce a key
     *    the server never stored, and the machine would be unreadable forever.
     *  - **It does not fall back offline.** The ordinary path can synthesise a
     *    local Machine when the server is unreachable, which is right for a
     *    laptop and wrong here: a runtime that proceeded on a synthesised machine
     *    would answer the parent about a registration that does not exist.
     *
     * The id is compared, not adopted: a response describing another Machine is
     * the one case where continuing would attach this runtime to somebody else's.
     */
    attachRegisteredMachine(): Promise<Machine>;
    /** Prepare once without sending a request. The daemon persists this private snapshot before commit. */
    prepareSessionCreation(opts: {
        tag: string;
        metadata: Metadata;
        state: AgentState | null;
        dataKey?: {
            key: Uint8Array;
            wrapped: Uint8Array;
        };
    }): {
        body: Readonly<{
            tag: string;
            metadata: string;
            agentState: string | null;
            dataEncryptionKey: string | null;
        }>;
        encryptionKey: Uint8Array<ArrayBufferLike>;
        encryptionVariant: "legacy" | "dataKey";
    };
    getOrCreateSession(opts: {
        tag: string;
        metadata: Metadata;
        state: AgentState | null;
        /**
         * A session key the caller chose, with its envelope wrapped to the account public key.
         *
         * For a parent that creates the session and hands the key to someone else (the daemon's
         * channel host): it must know the key the session is sealed with, so this call uploads
         * exactly these bytes instead of minting its own. Legacy accounts have no per-session key.
         */
        dataKey?: {
            key: Uint8Array;
            wrapped: Uint8Array;
        };
        /** Daemon-owned two-step authorization: retain these exact encrypted bytes while the user gate signs them. */
        prepared?: ReturnType<ApiClient['prepareSessionCreation']>;
        /** Trusted daemon preparation only: prove the exact already-encrypted create payload. */
        executionProof?: (body: Readonly<SessionExecutionCreateBody>, encryption: {
            encryptionKey: Uint8Array;
            encryptionVariant: 'legacy' | 'dataKey';
        }) => Promise<HappySessionExecutionProof>;
        /** Trusted daemon only. Seals these exact bytes; a private journal owns prepare/commit. */
        ownershipProof?: (body: Readonly<SessionExecutionCreateBody>, encryption: {
            encryptionKey: Uint8Array;
            encryptionVariant: 'legacy' | 'dataKey';
        }) => Promise<unknown>;
        /** Persist the server's candidate before confirm/start. This is not effective owner authority. */
        onOwnershipCreated?: (receipt: OwnershipCreatedReceipt) => Promise<void>;
    }): Promise<Session | null>;
    /**
     * Resolve the machine encryption key and the wrap material used to register
     * it. Shared so the offline fallback keys its machine exactly the way a
     * successful registration would.
     */
    private resolveMachineEncryption;
    /**
     * Build the local-only machine used when the server cannot be reached.
     *
     * Versions start at 0; the sync client reconciles them against the server on
     * reconnect via its version-mismatch retry, so starting low is self-healing.
     * Exposed so callers that must not fail — the daemon's startup path — can
     * fall back even when getOrCreateMachine throws.
     */
    buildOfflineMachine(opts: {
        machineId: string;
        metadata: MachineMetadata;
        daemonState?: DaemonState;
    }): Machine;
    /**
     * Register or update machine with the server
     * Returns the current machine state from the server with decrypted metadata and daemonState
     */
    getOrCreateMachine(opts: {
        machineId: string;
        metadata: MachineMetadata;
        daemonState?: DaemonState;
        /** aplus §6-1 B1 — 서버 서비스 공개키(base64). 있으면 machineKey 를
         *  서버 몫으로도 wrap 해 serverDataEncryptionKey 로 등록한다. */
        serverPublicKey?: string | null;
        /**
         * aplus-dev-studio specs/e2ee-machine-control-boundary — in strict mode the
         * server receives only the server-lane key, never the machine key.
         */
        machineControl?: 'compat' | 'strict';
    }): Promise<Machine>;
    /** The encryption identity is stable across bearer refresh; no bearer is written to the spool. */
    private usageRecoveryKey;
    /** Uses only account-authorized lookup results. Machine bearers cannot impersonate session owners. */
    startUsageRecovery(isCurrent?: () => Promise<boolean>, localSession?: (id: string) => UsageRecoverySession | null, managedToken?: () => Promise<string | null>, currentAccount?: () => Promise<Credentials | null>): () => Promise<void>;
    /** Called only by the daemon after validating a parent-signed managed launch envelope. */
    provisionManagedUsageRecovery(input: {
        sessionId: string;
        key: Uint8Array;
        serverOrigin: string;
    }): void;
    private usageSpool;
    sessionSyncClient(session: Session, options?: ApiSessionClientOptions): ApiSessionClient;
    machineSyncClient(machine: Machine, deviceKeys?: DeviceKeys, deviceEnrollment?: ReturnType<typeof createDeviceEnrollment>, processState?: DaemonState, withFilesystemMutation?: CommonHandlerOptions['withFilesystemMutation'], admitSubprocess?: CommonHandlerOptions['admitSubprocess'], reserveLegacyDispatch?: (roots: readonly string[]) => Promise<LegacyDispatchReservation>): ApiMachineClient;
    /**
     * Post a session event to the durable event log on the server.
     * Used by daemon recovery to emit session-end for dead sessions.
     */
    postSessionEvent(sessionId: string, eventType: string, content: string): Promise<void>;
    push(): PushNotificationClient;
    /**
     * Register a vendor API token with the server
     * The token is sent as a JSON string - server handles encryption
     */
    registerVendorToken(vendor: 'openai' | 'anthropic' | 'gemini', apiKey: any): Promise<void>;
    /**
     * Get vendor API token from the server
     * Returns the token if it exists, null otherwise
     */
    getVendorToken(vendor: 'openai' | 'anthropic' | 'gemini'): Promise<any | null>;
    /**
     * Mark a session as inactive on the server (active=false). Does NOT
     * change `lifecycleState`, so the session remains visible in the app
     * and resumable — same effect as the in-app "Archive" button hitting
     * the /archive endpoint, but without the extra metadata.
     *
     * Used during graceful shutdown (Ctrl-C / SIGTERM) as a synchronous
     * fallback for the socket-based session-end signal: even if the
     * socket emit doesn't drain before the process exits, the HTTP
     * response confirms the deactivate landed.
     */
    deactivateSession(sessionId: string): Promise<boolean>;
}

/**
 * Size-bounded writer for one process-owned log path. Rotation keeps the base
 * path stable because daemon.state.json and `happy logs` both point to it.
 */
interface LogRotationPolicy {
    maxFileBytes: number;
    maxArchives: number;
}

/**
 * Design decisions:
 * - Logging should be done only through file for debugging, otherwise we might disturb the claude session when in interactive mode
 * - Use info for logs that are useful to the user - this is our UI
 * - File output location: ~/.handy/logs/<date time in local timezone>.log
 */

declare class Logger {
    readonly logFilePath: string;
    private dangerouslyUnencryptedServerLoggingUrl;
    private readonly largePayloadOmissions;
    private readonly fileWriter;
    constructor(logFilePath?: string, rotationPolicy?: LogRotationPolicy);
    localTimezoneTimestamp(): string;
    debug(message: string, ...args: unknown[]): void;
    debugLargeJson(message: string, object: unknown, maxStringLength?: number, maxArrayLength?: number): void;
    info(message: string, ...args: unknown[]): void;
    infoDeveloper(message: string, ...args: unknown[]): void;
    warn(message: string, ...args: unknown[]): void;
    getLogPath(): string;
    private logToConsole;
    private sendToRemoteServer;
    private logToFile;
}
declare let logger: Logger;

/**
 * Global configuration for happy CLI
 *
 * Centralizes all configuration including environment variables and paths
 * Environment files should be loaded using Node's --env-file flag
 */
declare class Configuration {
    serverUrl: string;
    webappUrl: string;
    readonly isDaemonProcess: boolean;
    readonly happyHomeDir: string;
    readonly logsDir: string;
    readonly settingsFile: string;
    readonly privateKeyFile: string;
    readonly daemonStateFile: string;
    readonly daemonLockFile: string;
    readonly portRegistryFile: string;
    readonly browserBridgeTokenFile: string;
    /** Pre-machine-wide location of the same token; adopted once, then unused. */
    readonly legacyBrowserBridgeTokenFile: string | null;
    readonly sessionsFile: string;
    readonly automationsFile: string;
    readonly automationKeyFile: string;
    readonly serverAutomationsCacheFile: string;
    readonly serverAutomationsRuntimeFile: string;
    readonly currentCliVersion: string;
    readonly daemonHappyHomeDir: string;
    readonly isExperimentalEnabled: boolean;
    readonly disableCaffeinate: boolean;
    /**
     * aplus-dev-studio specs/e2ee-machine-control-boundary — whether the server
     * may hold this machine's key. Read once per process, so every check in it
     * agrees; switching takes a daemon restart.
     */
    readonly machineControl: 'compat' | 'strict';
    constructor();
    /**
     * Per-command relay override, e.g. `happy auth login --server <url>` (standalone
     * zrok URL). serverUrl 과 webappUrl 을 함께 맞춰 /v1/auth/request 와 승인 URL 이 같은
     * 릴레이를 가리키게 한다. 빈 문자열은 무시. 후행 슬래시 제거.
     */
    applyRelayOverride(url: string): void;
}
declare const configuration: Configuration;

export { ApiClient, ApiSessionClient, RawJSONLinesSchema, configuration, logger };
export type { RawJSONLines };
