import { z } from 'zod'; import { EventEmitter } from 'node:events'; import { open } from 'node:fs/promises'; import { Socket } from 'socket.io-client'; /** Actual locked context state, reported only over the child's bootstrap capability. */ declare const CodexBootstrapContextSchema: z.ZodObject<{ version: z.ZodLiteral<1>; contextId: z.ZodString; instanceId: z.ZodString; workspace: z.ZodEffects; threadId: z.ZodNullable; completedTurn: z.ZodBoolean; }, "strict", z.ZodTypeAny, { version: 1; contextId: string; instanceId: string; workspace: string; threadId: string | null; completedTurn: boolean; }, { version: 1; contextId: string; instanceId: string; workspace: string; threadId: string | null; completedTurn: boolean; }>; type CodexBootstrapContext = z.infer; declare const CodexContextAttestationSchema: z.ZodObject<{ version: z.ZodLiteral<1>; source: z.ZodLiteral<"trusted_runtime_bootstrap">; machineId: z.ZodString; sessionId: z.ZodString; runtimeSessionInstanceId: z.ZodString; requestedWorkspace: z.ZodEffects; context: z.ZodObject<{ version: z.ZodLiteral<1>; contextId: z.ZodString; instanceId: z.ZodString; workspace: z.ZodEffects; threadId: z.ZodNullable; completedTurn: z.ZodBoolean; } & { supported: z.ZodLiteral; }, "strict", z.ZodTypeAny, { version: 1; contextId: string; instanceId: string; workspace: string; threadId: string | null; completedTurn: boolean; supported: true; }, { version: 1; contextId: string; instanceId: string; workspace: string; threadId: string | null; completedTurn: boolean; supported: true; }>; }, "strict", z.ZodTypeAny, { sessionId: string; version: 1; source: "trusted_runtime_bootstrap"; machineId: string; runtimeSessionInstanceId: string; requestedWorkspace: string; context: { version: 1; contextId: string; instanceId: string; workspace: string; threadId: string | null; completedTurn: boolean; supported: true; }; }, { sessionId: string; version: 1; source: "trusted_runtime_bootstrap"; machineId: string; runtimeSessionInstanceId: string; requestedWorkspace: string; context: { version: 1; contextId: string; instanceId: string; workspace: string; threadId: string | null; completedTurn: boolean; supported: true; }; }>; type CodexContextAttestation = z.infer; /** * Simplified schema that only validates fields actually used in the codebase * while preserving all other fields through passthrough() */ declare const UsageSchema: z.ZodObject<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>; declare const RawJSONLinesSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{ type: z.ZodLiteral<"user">; isSidechain: z.ZodOptional; isMeta: z.ZodOptional; uuid: z.ZodString; message: z.ZodObject<{ content: z.ZodUnion<[z.ZodString, z.ZodAny]>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ content: z.ZodUnion<[z.ZodString, z.ZodAny]>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ content: z.ZodUnion<[z.ZodString, z.ZodAny]>; }, z.ZodTypeAny, "passthrough">>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ type: z.ZodLiteral<"user">; isSidechain: z.ZodOptional; isMeta: z.ZodOptional; uuid: z.ZodString; message: z.ZodObject<{ content: z.ZodUnion<[z.ZodString, z.ZodAny]>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ content: z.ZodUnion<[z.ZodString, z.ZodAny]>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ content: z.ZodUnion<[z.ZodString, z.ZodAny]>; }, z.ZodTypeAny, "passthrough">>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ type: z.ZodLiteral<"user">; isSidechain: z.ZodOptional; isMeta: z.ZodOptional; uuid: z.ZodString; message: z.ZodObject<{ content: z.ZodUnion<[z.ZodString, z.ZodAny]>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ content: z.ZodUnion<[z.ZodString, z.ZodAny]>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ content: z.ZodUnion<[z.ZodString, z.ZodAny]>; }, z.ZodTypeAny, "passthrough">>; }, z.ZodTypeAny, "passthrough">>, z.ZodObject<{ uuid: z.ZodString; type: z.ZodLiteral<"assistant">; message: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; model: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ usage: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; model: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ usage: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; model: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ uuid: z.ZodString; type: z.ZodLiteral<"assistant">; message: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; model: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ usage: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; model: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ usage: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; model: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ uuid: z.ZodString; type: z.ZodLiteral<"assistant">; message: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; model: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ usage: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; model: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ usage: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ input_tokens: z.ZodNumber; cache_creation_input_tokens: z.ZodOptional; cache_read_input_tokens: z.ZodOptional; output_tokens: z.ZodNumber; service_tier: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; model: z.ZodOptional; }, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">>, z.ZodObject<{ type: z.ZodLiteral<"summary">; summary: z.ZodString; leafUuid: z.ZodString; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ type: z.ZodLiteral<"summary">; summary: z.ZodString; leafUuid: z.ZodString; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ type: z.ZodLiteral<"summary">; summary: z.ZodString; leafUuid: z.ZodString; }, z.ZodTypeAny, "passthrough">>, z.ZodObject<{ type: z.ZodLiteral<"system">; uuid: z.ZodString; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ type: z.ZodLiteral<"system">; uuid: z.ZodString; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ type: z.ZodLiteral<"system">; uuid: z.ZodString; }, z.ZodTypeAny, "passthrough">>]>; type RawJSONLines = z.infer; /** * Legacy permission mode type - includes both Claude and Codex preset modes. * Must match MessageMetaSchema.permissionMode enum values * * Claude modes: default, acceptEdits, auto, bypassPermissions, dontAsk, 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 ClaudePermissionMode = 'default' | 'acceptEdits' | 'auto' | 'bypassPermissions' | 'dontAsk'; type PermissionMode = ClaudePermissionMode | 'plan' | 'read-only' | 'safe-yolo' | 'yolo'; /** Stable wire names used when attesting session encryption to Agent Plane. */ type AgentPlaneSessionEncryptionMode = 'data_key' | 'legacy'; /** * Encryption proof for a session created by the currently loaded credential. * The two fields are intentionally distinct so a future credential format can * change its session-encryption policy without silently weakening the contract. */ type AgentPlaneSessionEncryptionAttestation = { credentialMode: AgentPlaneSessionEncryptionMode; sessionMode: AgentPlaneSessionEncryptionMode; }; /** * Usage data type from Claude */ type Usage = z.infer; /** * 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.ZodObject<{ host: z.ZodString; platform: z.ZodString; happyCliVersion: z.ZodString; /** * This daemon accepts bound RPC requests of this version (rpc/rpcBinding.ts). * A caller relies on it only while `rpcBindingCliVersion` equals * `happyCliVersion`: a CLI from before the binding rewrites the version at * its start and leaves these two keys as it found them. */ rpcBinding: z.ZodOptional>; rpcBindingCliVersion: z.ZodOptional; homeDir: z.ZodString; happyHomeDir: z.ZodString; happyLibDir: z.ZodString; claudeCodeVersion: z.ZodOptional; claudeCodeLatestVersion: z.ZodOptional; claudeCodeUpdateCommand: z.ZodOptional; /** * What the daemon actually does (daemon/executionContract.ts). A reader * relies on it only while `cliVersion` equals `happyCliVersion`. */ executionContract: z.ZodOptional>; mode: z.ZodEnum<["isolated", "without_contract_by_local_choice", "refusing"]>; isolatorVersion: z.ZodNullable; cliVersion: z.ZodString; reason: z.ZodNullable>; }, "strict", z.ZodTypeAny, { version: 1 | null; mode: "isolated" | "without_contract_by_local_choice" | "refusing"; isolatorVersion: string | null; cliVersion: string; reason: "no_isolator_configured" | "isolator_unavailable" | null; }, { version: 1 | null; mode: "isolated" | "without_contract_by_local_choice" | "refusing"; isolatorVersion: string | null; cliVersion: string; reason: "no_isolator_configured" | "isolator_unavailable" | null; }>>; /** Native service identity was checked by this daemon. Network entries are * configuration until an exact runtime's root observation agrees with them. */ managedRuntime: z.ZodOptional; cliVersion: z.ZodString; instance: z.ZodString; serviceUser: z.ZodString; configurationSha256: z.ZodString; programsSha256: z.ZodString; networkPolicyId: z.ZodString; networkPolicySha256: z.ZodString; webAccess: z.ZodObject<{ mode: z.ZodEnum<["none", "allowlist", "public"]>; hosts: z.ZodArray; }, "strict", z.ZodTypeAny, { mode: "none" | "allowlist" | "public"; hosts: string[]; }, { mode: "none" | "allowlist" | "public"; hosts: string[]; }>; status: z.ZodLiteral<"configuration_verified">; }, "strict", z.ZodTypeAny, { status: "configuration_verified"; version: 1; cliVersion: string; instance: string; serviceUser: string; configurationSha256: string; programsSha256: string; networkPolicyId: string; networkPolicySha256: string; webAccess: { mode: "none" | "allowlist" | "public"; hosts: string[]; }; }, { status: "configuration_verified"; version: 1; cliVersion: string; instance: string; serviceUser: string; configurationSha256: string; programsSha256: string; networkPolicyId: string; networkPolicySha256: string; webAccess: { mode: "none" | "allowlist" | "public"; hosts: string[]; }; }>>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ host: z.ZodString; platform: z.ZodString; happyCliVersion: z.ZodString; /** * This daemon accepts bound RPC requests of this version (rpc/rpcBinding.ts). * A caller relies on it only while `rpcBindingCliVersion` equals * `happyCliVersion`: a CLI from before the binding rewrites the version at * its start and leaves these two keys as it found them. */ rpcBinding: z.ZodOptional>; rpcBindingCliVersion: z.ZodOptional; homeDir: z.ZodString; happyHomeDir: z.ZodString; happyLibDir: z.ZodString; claudeCodeVersion: z.ZodOptional; claudeCodeLatestVersion: z.ZodOptional; claudeCodeUpdateCommand: z.ZodOptional; /** * What the daemon actually does (daemon/executionContract.ts). A reader * relies on it only while `cliVersion` equals `happyCliVersion`. */ executionContract: z.ZodOptional>; mode: z.ZodEnum<["isolated", "without_contract_by_local_choice", "refusing"]>; isolatorVersion: z.ZodNullable; cliVersion: z.ZodString; reason: z.ZodNullable>; }, "strict", z.ZodTypeAny, { version: 1 | null; mode: "isolated" | "without_contract_by_local_choice" | "refusing"; isolatorVersion: string | null; cliVersion: string; reason: "no_isolator_configured" | "isolator_unavailable" | null; }, { version: 1 | null; mode: "isolated" | "without_contract_by_local_choice" | "refusing"; isolatorVersion: string | null; cliVersion: string; reason: "no_isolator_configured" | "isolator_unavailable" | null; }>>; /** Native service identity was checked by this daemon. Network entries are * configuration until an exact runtime's root observation agrees with them. */ managedRuntime: z.ZodOptional; cliVersion: z.ZodString; instance: z.ZodString; serviceUser: z.ZodString; configurationSha256: z.ZodString; programsSha256: z.ZodString; networkPolicyId: z.ZodString; networkPolicySha256: z.ZodString; webAccess: z.ZodObject<{ mode: z.ZodEnum<["none", "allowlist", "public"]>; hosts: z.ZodArray; }, "strict", z.ZodTypeAny, { mode: "none" | "allowlist" | "public"; hosts: string[]; }, { mode: "none" | "allowlist" | "public"; hosts: string[]; }>; status: z.ZodLiteral<"configuration_verified">; }, "strict", z.ZodTypeAny, { status: "configuration_verified"; version: 1; cliVersion: string; instance: string; serviceUser: string; configurationSha256: string; programsSha256: string; networkPolicyId: string; networkPolicySha256: string; webAccess: { mode: "none" | "allowlist" | "public"; hosts: string[]; }; }, { status: "configuration_verified"; version: 1; cliVersion: string; instance: string; serviceUser: string; configurationSha256: string; programsSha256: string; networkPolicyId: string; networkPolicySha256: string; webAccess: { mode: "none" | "allowlist" | "public"; hosts: string[]; }; }>>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ host: z.ZodString; platform: z.ZodString; happyCliVersion: z.ZodString; /** * This daemon accepts bound RPC requests of this version (rpc/rpcBinding.ts). * A caller relies on it only while `rpcBindingCliVersion` equals * `happyCliVersion`: a CLI from before the binding rewrites the version at * its start and leaves these two keys as it found them. */ rpcBinding: z.ZodOptional>; rpcBindingCliVersion: z.ZodOptional; homeDir: z.ZodString; happyHomeDir: z.ZodString; happyLibDir: z.ZodString; claudeCodeVersion: z.ZodOptional; claudeCodeLatestVersion: z.ZodOptional; claudeCodeUpdateCommand: z.ZodOptional; /** * What the daemon actually does (daemon/executionContract.ts). A reader * relies on it only while `cliVersion` equals `happyCliVersion`. */ executionContract: z.ZodOptional>; mode: z.ZodEnum<["isolated", "without_contract_by_local_choice", "refusing"]>; isolatorVersion: z.ZodNullable; cliVersion: z.ZodString; reason: z.ZodNullable>; }, "strict", z.ZodTypeAny, { version: 1 | null; mode: "isolated" | "without_contract_by_local_choice" | "refusing"; isolatorVersion: string | null; cliVersion: string; reason: "no_isolator_configured" | "isolator_unavailable" | null; }, { version: 1 | null; mode: "isolated" | "without_contract_by_local_choice" | "refusing"; isolatorVersion: string | null; cliVersion: string; reason: "no_isolator_configured" | "isolator_unavailable" | null; }>>; /** Native service identity was checked by this daemon. Network entries are * configuration until an exact runtime's root observation agrees with them. */ managedRuntime: z.ZodOptional; cliVersion: z.ZodString; instance: z.ZodString; serviceUser: z.ZodString; configurationSha256: z.ZodString; programsSha256: z.ZodString; networkPolicyId: z.ZodString; networkPolicySha256: z.ZodString; webAccess: z.ZodObject<{ mode: z.ZodEnum<["none", "allowlist", "public"]>; hosts: z.ZodArray; }, "strict", z.ZodTypeAny, { mode: "none" | "allowlist" | "public"; hosts: string[]; }, { mode: "none" | "allowlist" | "public"; hosts: string[]; }>; status: z.ZodLiteral<"configuration_verified">; }, "strict", z.ZodTypeAny, { status: "configuration_verified"; version: 1; cliVersion: string; instance: string; serviceUser: string; configurationSha256: string; programsSha256: string; networkPolicyId: string; networkPolicySha256: string; webAccess: { mode: "none" | "allowlist" | "public"; hosts: string[]; }; }, { status: "configuration_verified"; version: 1; cliVersion: string; instance: string; serviceUser: string; configurationSha256: string; programsSha256: string; networkPolicyId: string; networkPolicySha256: string; webAccess: { mode: "none" | "allowlist" | "public"; hosts: string[]; }; }>>; }, z.ZodTypeAny, "passthrough">>; type MachineMetadata = z.infer; /** * Daemon state - dynamic runtime information (frequently updated) */ declare const DaemonStateSchema: z.ZodObject<{ status: z.ZodUnion<[z.ZodEnum<["running", "shutting-down"]>, z.ZodString]>; pid: z.ZodOptional; httpPort: z.ZodOptional; startedAt: z.ZodOptional; shutdownRequestedAt: z.ZodOptional; shutdownSource: z.ZodOptional, z.ZodString]>>; }, "strip", z.ZodTypeAny, { status: string; pid?: number | undefined; httpPort?: number | undefined; startedAt?: number | undefined; shutdownRequestedAt?: number | undefined; shutdownSource?: string | undefined; }, { status: string; pid?: number | undefined; httpPort?: number | undefined; startedAt?: number | undefined; shutdownRequestedAt?: number | undefined; shutdownSource?: string | undefined; }>; type DaemonState = z.infer; type Machine = { id: string; encryptionKey: Uint8Array; encryptionVariant: 'legacy' | 'dataKey'; metadata: MachineMetadata; metadataVersion: number; daemonState: DaemonState | null; daemonStateVersion: number; }; declare const SessionMessageReplayPageSchema: z.ZodObject<{ messages: z.ZodArray; }, "strip", z.ZodTypeAny, { c: string; t: "encrypted"; }, { c: string; t: "encrypted"; }>; createdAt: z.ZodNumber; id: z.ZodString; localId: z.ZodOptional>; seq: z.ZodNumber; updatedAt: z.ZodNumber; }, "strip", z.ZodTypeAny, { content: { c: string; t: "encrypted"; }; id: string; createdAt: number; updatedAt: number; seq: number; localId?: string | null | undefined; }, { content: { c: string; t: "encrypted"; }; id: string; createdAt: number; updatedAt: number; seq: number; localId?: string | null | undefined; }>, "many">; hasMore: z.ZodBoolean; nextAfterSeq: z.ZodNumber; }, "strip", z.ZodTypeAny, { messages: { content: { c: string; t: "encrypted"; }; id: string; createdAt: number; updatedAt: number; seq: number; localId?: string | null | undefined; }[]; hasMore: boolean; nextAfterSeq: number; }, { messages: { content: { c: string; t: "encrypted"; }; id: string; createdAt: number; updatedAt: number; seq: number; localId?: string | null | undefined; }[]; hasMore: boolean; nextAfterSeq: number; }>; type SessionMessageReplayPage = z.infer; declare const UserMessageSchema: z.ZodObject<{ role: z.ZodLiteral<"user">; content: z.ZodUnion<[z.ZodObject<{ type: z.ZodLiteral<"text">; text: z.ZodString; }, "strip", z.ZodTypeAny, { type: "text"; text: string; }, { type: "text"; text: string; }>, z.ZodObject<{ type: z.ZodLiteral<"multipart">; parts: z.ZodArray; text: z.ZodString; }, "strip", z.ZodTypeAny, { type: "text"; text: string; }, { type: "text"; text: string; }>, z.ZodObject<{ type: z.ZodLiteral<"image">; source: z.ZodUnion<[z.ZodObject<{ type: z.ZodLiteral<"base64">; media_type: z.ZodEnum<["image/jpeg", "image/png", "image/gif", "image/webp"]>; data: z.ZodString; }, "strip", z.ZodTypeAny, { type: "base64"; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; data: string; }, { type: "base64"; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; data: string; }>, z.ZodObject<{ type: z.ZodLiteral<"url">; media_type: z.ZodEnum<["image/jpeg", "image/png", "image/gif", "image/webp"]>; url: z.ZodString; sha256: z.ZodOptional; size_bytes: z.ZodOptional; filename: z.ZodOptional; headers: z.ZodOptional>; }, "strip", z.ZodTypeAny, { type: "url"; url: string; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; sha256?: string | undefined; size_bytes?: number | undefined; filename?: string | undefined; headers?: Record | undefined; }, { type: "url"; url: string; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; sha256?: string | undefined; size_bytes?: number | undefined; filename?: string | undefined; headers?: Record | undefined; }>]>; }, "strip", z.ZodTypeAny, { type: "image"; source: { type: "url"; url: string; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; sha256?: string | undefined; size_bytes?: number | undefined; filename?: string | undefined; headers?: Record | undefined; } | { type: "base64"; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; data: string; }; }, { type: "image"; source: { type: "url"; url: string; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; sha256?: string | undefined; size_bytes?: number | undefined; filename?: string | undefined; headers?: Record | undefined; } | { type: "base64"; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; data: string; }; }>]>, "many">; }, "strip", z.ZodTypeAny, { type: "multipart"; parts: ({ type: "text"; text: string; } | { type: "image"; source: { type: "url"; url: string; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; sha256?: string | undefined; size_bytes?: number | undefined; filename?: string | undefined; headers?: Record | undefined; } | { type: "base64"; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; data: string; }; })[]; }, { type: "multipart"; parts: ({ type: "text"; text: string; } | { type: "image"; source: { type: "url"; url: string; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; sha256?: string | undefined; size_bytes?: number | undefined; filename?: string | undefined; headers?: Record | undefined; } | { type: "base64"; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; data: string; }; })[]; }>]>; localKey: z.ZodOptional; meta: z.ZodOptional; permissionPreset: z.ZodOptional>>; permissionMode: z.ZodOptional>; mode: z.ZodOptional>>; accessMode: z.ZodOptional>>; claudePermissionMode: z.ZodOptional>>; codexCollaborationMode: z.ZodOptional>>; codexPermissionProfile: z.ZodOptional>; approvalPolicy: z.ZodOptional>>; sandboxMode: z.ZodOptional>>; codexSandboxNetworkAccess: z.ZodOptional>; model: z.ZodOptional>; fallbackModel: z.ZodOptional>; customSystemPrompt: z.ZodOptional>; appendSystemPrompt: z.ZodOptional>; allowedTools: z.ZodOptional>>; disallowedTools: z.ZodOptional>>; reasoningEffort: z.ZodOptional>; terminalProtocol: z.ZodOptional>; agentPlaneTurnAuthority: z.ZodOptional; conduitInstanceId: z.ZodString; authorityGeneration: z.ZodNumber; activationId: z.ZodString; }, "strict", z.ZodTypeAny, { protocolVersion: 1; authorityGeneration: number; activationId: string; conduitInstanceId: string; }, { protocolVersion: 1; authorityGeneration: number; activationId: string; conduitInstanceId: string; }>>; runtimeGoalCommand: z.ZodOptional; objective: z.ZodOptional; }, "strip", z.ZodTypeAny, { action: "start" | "view" | "pause" | "resume" | "clear"; objective?: string | undefined; }, { action: "start" | "view" | "pause" | "resume" | "clear"; objective?: string | undefined; }>>; }, "strip", z.ZodTypeAny, { model?: string | null | undefined; mode?: "default" | "plan" | null | undefined; sentFrom?: string | undefined; permissionPreset?: "ask" | "auto_edits" | "full_access" | "read_only" | null | undefined; permissionMode?: "default" | "acceptEdits" | "bypassPermissions" | "plan" | "read-only" | "safe-yolo" | "yolo" | "auto" | "dontAsk" | undefined; accessMode?: "read-only" | "workspace-write" | "danger-full-access" | null | undefined; claudePermissionMode?: "default" | "acceptEdits" | "bypassPermissions" | "auto" | "dontAsk" | null | undefined; codexCollaborationMode?: "default" | "plan" | null | undefined; codexPermissionProfile?: string | null | undefined; approvalPolicy?: "never" | "untrusted" | "on-failure" | "on-request" | null | undefined; sandboxMode?: "read-only" | "workspace-write" | "danger-full-access" | null | undefined; codexSandboxNetworkAccess?: boolean | null | undefined; fallbackModel?: string | null | undefined; customSystemPrompt?: string | null | undefined; appendSystemPrompt?: string | null | undefined; allowedTools?: string[] | null | undefined; disallowedTools?: string[] | null | undefined; reasoningEffort?: string | null | undefined; terminalProtocol?: 1 | undefined; agentPlaneTurnAuthority?: { protocolVersion: 1; authorityGeneration: number; activationId: string; conduitInstanceId: string; } | undefined; runtimeGoalCommand?: { action: "start" | "view" | "pause" | "resume" | "clear"; objective?: string | undefined; } | undefined; }, { model?: string | null | undefined; mode?: "default" | "plan" | null | undefined; sentFrom?: string | undefined; permissionPreset?: "ask" | "auto_edits" | "full_access" | "read_only" | null | undefined; permissionMode?: "default" | "acceptEdits" | "bypassPermissions" | "plan" | "read-only" | "safe-yolo" | "yolo" | "auto" | "dontAsk" | undefined; accessMode?: "read-only" | "workspace-write" | "danger-full-access" | null | undefined; claudePermissionMode?: "default" | "acceptEdits" | "bypassPermissions" | "auto" | "dontAsk" | null | undefined; codexCollaborationMode?: "default" | "plan" | null | undefined; codexPermissionProfile?: string | null | undefined; approvalPolicy?: "never" | "untrusted" | "on-failure" | "on-request" | null | undefined; sandboxMode?: "read-only" | "workspace-write" | "danger-full-access" | null | undefined; codexSandboxNetworkAccess?: boolean | null | undefined; fallbackModel?: string | null | undefined; customSystemPrompt?: string | null | undefined; appendSystemPrompt?: string | null | undefined; allowedTools?: string[] | null | undefined; disallowedTools?: string[] | null | undefined; reasoningEffort?: string | null | undefined; terminalProtocol?: 1 | undefined; agentPlaneTurnAuthority?: { protocolVersion: 1; authorityGeneration: number; activationId: string; conduitInstanceId: string; } | undefined; runtimeGoalCommand?: { action: "start" | "view" | "pause" | "resume" | "clear"; objective?: string | undefined; } | undefined; }>>; }, "strip", z.ZodTypeAny, { content: { type: "text"; text: string; } | { type: "multipart"; parts: ({ type: "text"; text: string; } | { type: "image"; source: { type: "url"; url: string; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; sha256?: string | undefined; size_bytes?: number | undefined; filename?: string | undefined; headers?: Record | undefined; } | { type: "base64"; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; data: string; }; })[]; }; role: "user"; localKey?: string | undefined; meta?: { model?: string | null | undefined; mode?: "default" | "plan" | null | undefined; sentFrom?: string | undefined; permissionPreset?: "ask" | "auto_edits" | "full_access" | "read_only" | null | undefined; permissionMode?: "default" | "acceptEdits" | "bypassPermissions" | "plan" | "read-only" | "safe-yolo" | "yolo" | "auto" | "dontAsk" | undefined; accessMode?: "read-only" | "workspace-write" | "danger-full-access" | null | undefined; claudePermissionMode?: "default" | "acceptEdits" | "bypassPermissions" | "auto" | "dontAsk" | null | undefined; codexCollaborationMode?: "default" | "plan" | null | undefined; codexPermissionProfile?: string | null | undefined; approvalPolicy?: "never" | "untrusted" | "on-failure" | "on-request" | null | undefined; sandboxMode?: "read-only" | "workspace-write" | "danger-full-access" | null | undefined; codexSandboxNetworkAccess?: boolean | null | undefined; fallbackModel?: string | null | undefined; customSystemPrompt?: string | null | undefined; appendSystemPrompt?: string | null | undefined; allowedTools?: string[] | null | undefined; disallowedTools?: string[] | null | undefined; reasoningEffort?: string | null | undefined; terminalProtocol?: 1 | undefined; agentPlaneTurnAuthority?: { protocolVersion: 1; authorityGeneration: number; activationId: string; conduitInstanceId: string; } | undefined; runtimeGoalCommand?: { action: "start" | "view" | "pause" | "resume" | "clear"; objective?: string | undefined; } | undefined; } | undefined; }, { content: { type: "text"; text: string; } | { type: "multipart"; parts: ({ type: "text"; text: string; } | { type: "image"; source: { type: "url"; url: string; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; sha256?: string | undefined; size_bytes?: number | undefined; filename?: string | undefined; headers?: Record | undefined; } | { type: "base64"; media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; data: string; }; })[]; }; role: "user"; localKey?: string | undefined; meta?: { model?: string | null | undefined; mode?: "default" | "plan" | null | undefined; sentFrom?: string | undefined; permissionPreset?: "ask" | "auto_edits" | "full_access" | "read_only" | null | undefined; permissionMode?: "default" | "acceptEdits" | "bypassPermissions" | "plan" | "read-only" | "safe-yolo" | "yolo" | "auto" | "dontAsk" | undefined; accessMode?: "read-only" | "workspace-write" | "danger-full-access" | null | undefined; claudePermissionMode?: "default" | "acceptEdits" | "bypassPermissions" | "auto" | "dontAsk" | null | undefined; codexCollaborationMode?: "default" | "plan" | null | undefined; codexPermissionProfile?: string | null | undefined; approvalPolicy?: "never" | "untrusted" | "on-failure" | "on-request" | null | undefined; sandboxMode?: "read-only" | "workspace-write" | "danger-full-access" | null | undefined; codexSandboxNetworkAccess?: boolean | null | undefined; fallbackModel?: string | null | undefined; customSystemPrompt?: string | null | undefined; appendSystemPrompt?: string | null | undefined; allowedTools?: string[] | null | undefined; disallowedTools?: string[] | null | undefined; reasoningEffort?: string | null | undefined; terminalProtocol?: 1 | undefined; agentPlaneTurnAuthority?: { protocolVersion: 1; authorityGeneration: number; activationId: string; conduitInstanceId: string; } | undefined; runtimeGoalCommand?: { action: "start" | "view" | "pause" | "resume" | "clear"; objective?: string | undefined; } | undefined; } | undefined; }>; type UserMessage = z.infer; type Metadata = { path: string; host: string; version?: string; name?: string; os?: string; summary?: { text: string; updatedAt: number; }; machineId?: string; claudeSessionId?: string; tools?: string[]; slashCommands?: 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; /** Session-process attestation for authoritative Agent Plane terminals. */ terminalProtocol?: 1; /** This session accepts bound RPC requests of this version (rpc/rpcBinding.ts). */ rpcBinding?: 1; /** Exact session-process encryption attestation reported to its daemon. */ sessionEncryption?: AgentPlaneSessionEncryptionAttestation; }; type AgentRequestKind = 'permission' | 'questionnaire' | 'plan_decision'; type AgentQuestionnaireOption = { label: string; description?: string | null; }; type AgentQuestionnaireQuestion = { id: string; header?: string | null; question: string; options?: AgentQuestionnaireOption[] | null; isOther?: boolean; isSecret?: boolean; multiSelect?: boolean; }; type AgentQuestionnaire = { provider: 'claude' | 'codex'; questions: AgentQuestionnaireQuestion[]; autoResolutionMs?: number | null; }; type AgentQuestionnaireAnswer = { answers: string[]; }; type AgentQuestionnaireAnswerMap = Record; type AgentPlanDecisionAction = 'approve' | 'stay_in_plan'; type AgentPlanDecisionPlan = { id: string; provider?: 'claude' | 'codex' | string; text?: string; explanation?: string | null; steps?: Array<{ step: string; status?: string | null; }>; status?: 'updated' | 'complete'; }; type AgentPlanDecision = { provider: 'claude' | 'codex' | string; planId: string; plan?: AgentPlanDecisionPlan; actions: AgentPlanDecisionAction[]; }; type AgentStateRequest = { kind?: AgentRequestKind; tool: string; arguments: any; createdAt: number; questionnaire?: AgentQuestionnaire; planDecision?: AgentPlanDecision; }; type AgentStateCompletedRequest = AgentStateRequest & { completedAt: number; status: 'canceled' | 'denied' | 'approved' | 'answered' | 'expired' | 'stayed_in_plan'; reason?: string; mode?: PermissionMode; decision?: 'approved' | 'approved_for_session' | 'denied' | 'abort'; allowTools?: string[]; answers?: AgentQuestionnaireAnswerMap; planDecisionResult?: AgentPlanDecisionAction; feedback?: string; }; type AgentState = { controlledByUser?: boolean | null | undefined; requests?: { [id: string]: AgentStateRequest; }; completedRequests?: { [id: string]: AgentStateCompletedRequest; }; }; interface RpcAcknowledgedTombstoneProof { callId: string; method: string; paramsHash: string; retiredAt: number; } type RpcResultRetention = 'time_bounded' | 'caller_acknowledged'; type RpcResultLedgerOutcome = { status: 'completed'; response: string; replayed: boolean; } | { status: 'already_acknowledged'; proof: RpcAcknowledgedTombstoneProof; } | { status: 'conflict'; reason: string; reasonCode?: RpcResultLedgerReasonCode; } | { status: 'unavailable'; reason: string; reasonCode?: RpcResultLedgerReasonCode; }; type RpcResultLedgerReplayOutcome = RpcResultLedgerOutcome | { status: 'not_found'; }; /** A snapshot only. Missing/pending/unknown records never prove absence of effects. */ type RpcResultLedgerObservation = { status: 'completed'; response: string; } | { status: 'not_found' | 'pending'; } | { status: 'already_acknowledged'; proof: RpcAcknowledgedTombstoneProof; } | { status: 'conflict'; reasonCode: 'rpc_ledger_call_id_conflict'; } | { status: 'unavailable'; reasonCode: 'rpc_ledger_io_unavailable' | 'rpc_ledger_storage_full' | 'rpc_ledger_unknown_outcome'; }; type RpcResultLedgerAcknowledgeOutcome = { status: 'acknowledged' | 'already_acknowledged'; } | { status: 'not_found' | 'conflict' | 'unavailable'; reason: string; reasonCode?: RpcResultLedgerReasonCode; }; interface RpcResultLedgerOptions { directory?: string; maxEntries?: number; /** Permanent unknown-outcome fences. Acknowledged fences use compact shards. */ maxTombstoneEntries?: number; maxTotalBytes?: number; maxResultBytes?: number; /** Grace before an authoritative caller-acknowledged tombstone is GC'd. */ acknowledgedTombstoneRetentionMs?: number; /** Retry horizon for callers that have not implemented result ACKs. */ minCompletedRetentionMs?: number; lockTimeoutMs?: number; pendingWaitMs?: number; pollIntervalMs?: number; now?: () => number; /** How a write is made durable: its file, then its directory entry, synced to the disk. Production keeps the * default. A unit test that proves the ledger's protocol (replay, refusal, acknowledgement), not the disk, may * pass no-op syncs: they decide no outcome, they only wait for the disk. */ diskSync?: LedgerDiskSync; } interface LedgerDiskSync { file(handle: Awaited>): Promise; directory(path: string): Promise; } type RpcResultLedgerReasonCode = 'rpc_ledger_active_capacity_exhausted' | 'rpc_ledger_unknown_outcome_capacity_exhausted' | 'rpc_ledger_byte_capacity_exhausted' | 'rpc_ledger_acknowledgement_byte_capacity_exhausted' | 'rpc_ledger_unknown_outcome' | 'rpc_ledger_call_in_flight' /** The call ID was already used with another method or other params: this request can never pass. */ | 'rpc_ledger_call_id_conflict' | 'rpc_ledger_io_unavailable' | 'rpc_ledger_storage_full'; interface RpcResultLedgerTelemetry { protocolVersion: 1; layoutVersion: 2; available: boolean; pressure: 'normal' | 'high' | 'exhausted' | 'unavailable'; reasonCode: RpcResultLedgerReasonCode | null; activeEntries: number | null; maxActiveEntries: number; unknownOutcomeFences: number | null; maxUnknownOutcomeFences: number; acknowledgedFences: number | null; acknowledgedShardFiles: number | null; totalBytes: number | null; maxTotalBytes: number; acknowledgedFenceRetentionMs: number; oldestAcknowledgedFenceAt: number | null; nextAcknowledgedFenceGcAt: number | null; acknowledgementProgressProtected: true; } declare class RpcResultLedger { private readonly directory; private readonly lockDirectory; private readonly acknowledgedDirectory; private readonly maxEntries; private readonly maxUnknownOutcomeFences; private readonly maxTotalBytes; private readonly maxResultBytes; private readonly minCompletedRetentionMs; private readonly acknowledgedTombstoneRetentionMs; private readonly lockTimeoutMs; private readonly diskSync; private readonly pendingWaitMs; private readonly pollIntervalMs; private readonly now; private activeIndex; private storagePreparation; constructor(options?: RpcResultLedgerOptions); existingStatus(callId: string): Promise<'not_found' | 'pending' | 'completed' | 'tombstone'>; /** * Observe an exact retained call without executing, waiting, reserving, * acknowledging or retiring anything. In particular, a dead pending owner * stays pending: replayExisting's recovery writes are not allowed here. */ observeRetainedResult(input: { callId: string; method: string; paramsHash: string; }): Promise; execute(input: { callId: string; method: string; paramsHash: string; retention?: RpcResultRetention; }, executor: () => Promise, options?: { isDefinitiveNoSideEffectResponse?: (response: string) => boolean; }): Promise; /** * Replay/fence an already-known call without reserving a new slot. This is * used when a rolling upgrade removed the handler after its result was * persisted; arbitrary unknown methods must remain non-mutating. */ replayExisting(input: { callId: string; method: string; paramsHash: string; }): Promise; /** * Release a replayable result only after the authoritative caller has * durably committed it. The short-lived tombstone fences delayed network * duplicates; unacknowledged results and unknown outcomes are never aged * into re-executable calls. */ acknowledge(input: { callId: string; method: string; }): Promise; private executeInternal; private waitForCompletion; private recordPath; private acknowledgedShardKey; private acknowledgedShardPath; private readRecordForCallId; private readAcknowledgedTombstoneIfPresent; private serializeAcknowledgedShard; private persistAcknowledgedTombstone; private refreshAcknowledgedSummary; private totalIndexedBytes; private projectAcknowledgedWrite; private tombstoneOutcome; private tombstoneFor; private recordRetention; private pendingOwnerAppearsAlive; private retirePending; private readRecordIfPresent; private readRecord; private indexedRecord; private indexRecord; private invalidateActiveIndex; private writeIndexedRecordExclusive; private replaceIndexedRecord; private unindexRecord; private loadRecordsFromDisk; private loadAcknowledgedShardsFromDisk; private loadRecords; private gcAcknowledgedTombstones; private pruneToFit; private capacityReasonCode; getTelemetry(): Promise; private ensureStorageLayout; private prepareStorageLayout; private withLock; private readLatestLockState; private readLatestLockStateFrom; private publishLockState; private publishLockStateTo; private pruneLockStates; } type UnboundRpcRequestPolicy = 'accept' | 'refuse'; /** * 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 = (data: TRequest) => TResponse | Promise; /** * The only retry contracts a caller may rely on after a transport failure. * * `read_only` may be replayed with the same logical request. * `server_proved_not_started` may be replayed only after Happy explicitly * proves that the target handler was not entered. * `caller_acknowledged_retained_result` may reuse one stable callId after an * unknown outcome because the daemon retains the result until the caller * durably commits and acknowledges it. */ type RpcRetryClass = 'read_only' | 'server_proved_not_started' | 'caller_acknowledged_retained_result'; interface RpcMethodRetryCapability { retryClass: RpcRetryClass; } interface RpcPreLedgerGuardContext { callId?: string; durableRecordStatus: 'not_found' | 'pending' | 'completed' | 'tombstone'; } interface RpcHandlerRegistrationOptions { /** * `durable` is the compatibility default and retains replayable results * for a bounded retry horizon. `durable-acknowledged` retains results * until the authoritative caller explicitly commits and acknowledges * them. `read-only` bypasses the side-effect ledger. */ execution?: 'durable' | 'durable-acknowledged' | 'read-only' | 'ephemeral'; /** * Runs after decrypting params but before consulting the durable result * ledger. Use this only for process-incarnation fences whose truth cannot * be replayed from disk after a restart. */ preLedgerGuard?: (data: unknown, context: RpcPreLedgerGuardContext) => { proceed: true; } | { proceed: false; response: unknown; } | Promise<{ proceed: true; } | { proceed: false; response: unknown; }>; /** Require durable at-most-once identity instead of the legacy path. */ requiresCallId?: boolean | ((data: unknown) => boolean); /** * Adds a trusted, non-caller-controlled incarnation to the durable * fingerprint. A function may scope only selected request variants. */ durabilityScope?: string | ((data: unknown) => string | undefined); /** * A narrowly reviewed domain proof that the returned rejection performed * no side effect. Such results may release their pending reservation * immediately; a retry converges through the domain operation instead of * consuming a caller-acknowledged result slot. Never use this for thrown * errors or ambiguous outcomes. */ isDefinitiveNoSideEffectResult?: (result: unknown) => boolean; } /** * RPC request data from server */ interface RpcRequest { callId?: string; method: string; params: string; } /** * Configuration for RPC handler manager */ interface RpcHandlerConfig { scopePrefix: string; encryptionKey: Uint8Array; encryptionVariant: 'legacy' | 'dataKey'; /** * What happens to a request without a binding (see rpcBinding.ts). There * is no default: every receiver states it, with UNBOUND_RPC_REQUESTS. */ unboundRequests: UnboundRpcRequestPolicy; logger?: (message: string, data?: any) => void; resultLedger?: RpcResultLedger; /** This machine's clock in milliseconds; a test sets it. */ now?: () => number; } declare const retainedResultObservationRequest: z.ZodObject<{ callId: z.ZodString; method: z.ZodEnum<["prepare-agent-plane-session", "export-agent-plane-native-context", "import-agent-plane-native-context", "spawn-agent-plane-session", "stop-agent-plane-session", "prepare-agent-plane-turn-authority", "activate-agent-plane-turn-authority", "close-agent-plane-turn-authority"]>; paramsHash: z.ZodString; }, "strict", z.ZodTypeAny, { callId: string; method: "spawn-agent-plane-session" | "stop-agent-plane-session" | "prepare-agent-plane-session" | "prepare-agent-plane-turn-authority" | "activate-agent-plane-turn-authority" | "close-agent-plane-turn-authority" | "export-agent-plane-native-context" | "import-agent-plane-native-context"; paramsHash: string; }, { callId: string; method: "spawn-agent-plane-session" | "stop-agent-plane-session" | "prepare-agent-plane-session" | "prepare-agent-plane-turn-authority" | "activate-agent-plane-turn-authority" | "close-agent-plane-turn-authority" | "export-agent-plane-native-context" | "import-agent-plane-native-context"; paramsHash: string; }>; interface RetainedResultObservation { type: 'agent-plane-retained-rpc-result'; version: 1; target: z.infer & { machineId: string; }; outcome: RpcResultLedgerObservation; } declare class RpcHandlerManager { private handlers; private ephemeralHandlers; private readOnlyHandlers; private callerAcknowledgedHandlers; private preLedgerGuards; private callIdRequirements; private durabilityScopes; private definitiveNoSideEffectResults; private retryCapabilities; private readonly scopePrefix; private readonly encryptionKey; private readonly encryptionVariant; private readonly unboundRequests; private readonly now; private readonly logger; private readonly resultLedger; private readonly unboundMethodsLogged; private socket; constructor(config: RpcHandlerConfig); /** * Register an RPC handler for a specific method * @param method - The method name (without prefix) * @param handler - The handler function */ registerHandler(method: string, handler: RpcHandler, options?: RpcHandlerRegistrationOptions): void; /** * Handle an incoming RPC request * @param request - The RPC request data * @param callback - The response callback */ handleRequest(request: RpcRequest): Promise; /** * Runs a request whose params are opened and whose call ID is settled. * Returns the sealed answer in the old form; a bound request gets it * bound by the caller of this function. */ private handleOpenedRequest; acknowledgeDurableResult(input: { callId: string; method: string; }): Promise; getResultLedgerTelemetry(): Promise; observeAgentPlaneRetainedResult(input: unknown): Promise; private executeHandler; /** * Puts the answer of a bound request into its binding. The ledger keeps * answers in the old form, also those of before the binding existed, so * the binding is added here, for each delivery. */ private bindSealedResponse; private encryptError; private encryptResult; private encryptAlreadyAcknowledged; 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; /** * Return an immutable, prefix-free declaration for every registered * method. Capability consumers can therefore fail closed for an absent * mutating method instead of guessing from transport outcomes. */ getRetryCapabilities(): Record; /** * Clear all handlers */ clearHandlers(): void; /** * Get the prefixed method name * @param method - The method name */ private getPrefixedMethod; } interface SessionMessageOutboxOptions { rootDirectory?: string; now?: () => number; createLocalId?: () => string; /** Test seam; returns false only when directory fsync is unsupported. */ syncDirectory?: (directory: string) => boolean; } declare const SOCKET_CREDENTIAL_PROTOCOL_VERSION: 1; type SocketCredentialMode = 'auto' | 'required' | 'legacy'; type SocketCredentialRequest = { role: 'controller'; } | { role: 'machine'; machineId: string; } | { role: 'runtime'; sessionId: string; sessionInstanceId?: string; replayOnly: boolean; }; interface IssuedSocketCredential { token: string; protocolVersion: typeof SOCKET_CREDENTIAL_PROTOCOL_VERSION; role: SocketCredentialRequest['role']; expiresAt: number; } interface SocketCredentialProvider { getToken(): Promise; invalidate(token?: string): void; readonly renewable: boolean; } type RuntimeSocketCredentialRequest = Extract; type IssueSocketCredential = (issuerToken: string, request: SocketCredentialRequest & { ttlSeconds: number; }) => Promise; interface SocketCredentialExchangeOptions { serverUrl?: string; mode?: SocketCredentialMode; ttlSeconds?: number; refreshSkewMs?: number; legacyReprobeMs?: number; now?: () => number; issue?: IssueSocketCredential; } /** * Account/controller credential exchange shared by every socket owned by one * CLI process. The account credential is used only to bootstrap a controller * credential. While that controller credential remains valid, it renews itself * and issues exact machine/runtime credentials without exposing the account * credential in Socket.IO handshakes. */ declare class SocketCredentialExchange { private readonly mode; private readonly ttlSeconds; private readonly refreshSkewMs; private readonly legacyReprobeMs; private readonly now; private readonly issue; private controllerCredential; private controllerIssuePromise; private legacyFallbackUntil; private readonly accountToken; /** * `accountToken` is the token itself, or a function that gives the token * at the moment of asking. A process that lives longer than one account * token passes the function: the server ends a token after 30 days and * the daemon stores a new one meanwhile (see accountToken.ts). */ constructor(accountToken: string | (() => Promise), options?: SocketCredentialExchangeOptions); machine(machineId: string): SocketCredentialProvider; runtime(input: { sessionId: string; sessionInstanceId?: string; replayOnly?: boolean; }): SocketCredentialProvider; /** * Issue a subordinate credential without ever falling back to the account * token. Brokered runtimes use this path so an older server fails closed * instead of accidentally handing a broad legacy bearer to the child. */ issueRequired(request: SocketCredentialRequest): Promise; controllerToken(): Promise; private bound; credentialFresh(credential: IssuedSocketCredential | null): credential is IssuedSocketCredential; private credentialUsable; private issueController; issueBound(request: SocketCredentialRequest): Promise; legacyToken(): Promise; } /** * 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; } | { type: 'reasoning'; message: string; } | { type: 'thinking'; text: string; } | { type: 'plan'; id: string; text?: string; explanation?: string | null; steps?: Array<{ step: string; status?: string | null; }>; status?: 'updated' | 'complete'; } | { type: 'plan_delta'; id: string; delta: 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; terminal_protocol?: 1; } | { type: 'task_complete'; id: string; terminal_protocol?: 1; subtype?: string; reason?: string; is_error?: false; result?: string; } | { type: 'task_failed'; id: string; message: string; code?: string; param?: string; status?: number; terminal_protocol?: 1; subtype?: string; reason?: string; is_error?: true; result?: string; retryable?: boolean; prompt_executed?: boolean; /** With reason `authentication_required`: the login command to show (closed set, agreed with Agent Plane). */ login_command?: 'boujot claude-login' | 'claude auth login'; } | { type: 'turn_aborted'; id: string; terminal_protocol?: 1; subtype?: string; reason?: string; is_error?: true; result?: string; } | { type: 'permission-request'; permissionId: string; toolName: string; description: string; options?: unknown; } | { type: 'token_count'; [key: string]: unknown; }; interface ApiSessionClientOptions { outbox?: SessionMessageOutboxOptions; messageAckTimeoutMs?: number; outboxRetryBaseMs?: number; outboxRetryMaxMs?: number; outboxDrainBatchSize?: number; reconnectRecoveryJitterMs?: number; random?: () => number; inbox?: { fetchPage?: (afterSeq: number) => Promise; reconcileIntervalMs?: number; periodicJitterMs?: number; maxPagesPerReconcile?: number; retryBaseMs?: number; retryMaxMs?: number; }; } interface SessionCredentialAccess { socketCredential: SocketCredentialProvider; httpCredential: SocketCredentialProvider; sessionInstanceId: string; } declare class ApiSessionClient extends EventEmitter { private readonly controllerToken; private readonly socketCredential; readonly sessionId: string; private metadata; private metadataVersion; private agentState; private agentStateVersion; private socket; private pendingMessages; private pendingMessageDrainPromise; private pendingControlMessages; private pendingMessageCallback; readonly rpcHandlerManager: RpcHandlerManager; private agentStateLock; private metadataLock; private daemonActivityReportLock; private encryptionKey; private encryptionVariant; private readonly outbox; private readonly messageAckTimeoutMs; private readonly outboxRetryBaseMs; private readonly outboxRetryMaxMs; private readonly outboxDrainBatchSize; private readonly reconnectRecoveryJitterMs; private readonly random; private readonly sessionInstanceId; private outboxDrainPromise; private outboxRetryTimer; private outboxRetryAttempt; private outboxBlockedByPermanentError; private closed; private currentThinking; private currentLastActivityAt; private lastDaemonActivityReportAt; private lastReportedThinking; private lastReportedPendingOutbox; private readonly inbox; private readonly inboxReconcileIntervalMs; private readonly inboxRetryBaseMs; private readonly inboxRetryMaxMs; private readonly inboxPeriodicJitterMs; private inboxReconcilePromise; private inboxRetryTimer; private inboxPeriodicTimer; private inboxRetryAttempt; private readonly ownMessageCiphertextByLocalId; private connectedOnce; private credentialReconnectTimer; private credentialReconnectAttempt; private socketConnectionGeneration; private activeRpcRequests; private outboxAckRecoveryLocalId; private outboxAckRecoveryGeneration; private outboxReconnectTimer; private outboxReconnectAttempt; constructor(tokenOrExchange: string | SocketCredentialExchange | SessionCredentialAccess, session: Session, options?: ApiSessionClientOptions); get pendingOutboxCount(): number; get quarantinedOutboxCount(): number; get inboundAfterSeq(): number; on(eventName: string | symbol, listener: (...args: any[]) => void): this; onUserMessage(callback: (data: UserMessage) => void | Promise): void; private drainPendingUserMessages; /** * Send message to session * @param body - Message body (can be MessageContent or raw content for agent messages) */ sendClaudeSessionMessage(body: RawJSONLines): void; sendCodexMessage(body: any): 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', body: ACPMessageData): void; sendSessionEvent(event: { type: 'switch'; mode: 'local' | 'remote'; } | { type: 'message'; message: string; } | { type: 'permission-mode-changed'; mode: PermissionMode; } | { type: 'ready'; }, id?: string): void; /** * Send a ping message to keep the connection alive */ keepAlive(thinking: boolean, mode: 'local' | 'remote'): void; /** * Send session death message */ sendSessionDeath(): void; /** * Send usage data to the server */ sendUsageData(usage: Usage, model?: string): void; /** * Update session metadata * @param handler - Handler function that returns the updated metadata */ updateMetadata(handler: (metadata: Metadata) => Metadata): void; /** * Update session agent state * @param handler - Handler function that returns the updated agent state */ updateAgentState(handler: (metadata: AgentState) => AgentState): void; /** * Wait for socket buffer to flush */ flush(): Promise; close(): Promise; private scheduleCredentialReconnect; private clearCredentialReconnect; private clearOutboxReconnect; private scheduleOutboxReconnect; private reconnectTimedOutOutbox; private startInboxPeriodicReconciliation; private stopInboxReconciliationTimers; private scheduleInboxReconciliation; private deliverStoredSessionMessage; private drainPendingControlMessages; private enqueueEncryptedMessage; private scheduleOutboxDrain; private drainOutbox; private deliverOutboxRecord; private deliverSessionEnd; private reportDaemonActivity; } type PrepareAgentPlaneSessionFile = { path: string; content: string; }; type PrepareAgentPlaneSessionRequest = { projectOperationsRequired?: true; conversationId?: string; directory?: string; files: PrepareAgentPlaneSessionFile[]; }; type PrepareAgentPlaneSessionResponse = { type: 'success'; directory: string; filesWritten: number; } | { type: 'prepare_rejected'; error: string; /** False for tool settings the machine does not accept while its shell and files are off. */ retryable: boolean; } | { type: 'spawn_rejected'; code: 'execution_contract_not_met' | 'isolation_service_unavailable'; retryable: boolean; failure: { code: 'execution_contract_not_met' | 'isolation_service_unavailable'; retryable: boolean; }; error: string; }; /** * Minimal persistence functions for happy CLI * * Handles settings and private key storage in ~/.happy/ or local .happy/ */ type Credentials = { token: string; encryption: { type: 'legacy'; secret: Uint8Array; } | { type: 'dataKey'; publicKey: Uint8Array; machineKey: Uint8Array; }; }; /** * Off-login history of an isolated conversation (owner's decision 139 C, 22 October 2026, agreed with Agent * Plane's maintainer down to the field names): "When a chat that ran a local model, a gateway, a proxy or * Gemini switches to the owner's own login (Claude or ChatGPT), Agent Plane asks on a card; on Continue the * chat continues." * * The isolated launcher marks a conversation when one of its runtimes runs off this machine's logins (what * that run leaves in the conversation must not reach the login unasked), refuses a start on the owner's login * in a marked conversation with a typed failure that carries the mark, and allows the start that brings an * acknowledgement of exactly that mark (Agent Plane's Continue). Isolated machines only: on a Mac everything * runs as the owner, so the rule would protect nothing there. */ /** The kinds of off-login runs, in the order the daemon reports them (sorted). */ declare const OFF_LOGIN_KINDS: readonly ["gateway", "gemini", "local_model", "proxy"]; type OffLoginKind = typeof OFF_LOGIN_KINDS[number]; /** A conversation's off-login runs: their kinds, and when the first of them was marked (ISO 8601, UTC). */ interface OffLoginHistory { kinds: OffLoginKind[]; since: string; } /** Agent Plane's Continue on the card: names the conversation and the exact history it was shown. */ interface OffLoginAcknowledgement { conversationId: string; kinds: OffLoginKind[]; since: string; } /** The typed spawn failure a start on the owner's login meets in a marked conversation. */ interface OffLoginHistoryFailure { code: 'off_login_history'; retryable: false; offLoginHistory: OffLoginHistory; } /** * The machine-wide shell, files and SSH (finding C5): off unless the machine's * user turned them on locally (owner's step 129, 19 October 2026). Each call * reads the machine settings again, so a switch applies at once. While the * shell and files are off, a session's shell and file handlers answer only the * app's Git views, file reads and file search in its folder (step 131 c, * modules/common/sessionAppViews.ts); the agent's own tools are not gated, nor * are the model lists, which run the installed CLIs with fixed arguments. * * The refusal is a result, not an RPC error, in the shape agreed with Agent * Plane on 19 October 2026; `error` is for people and is not stored there. */ /** `sessionShellAndFiles`, `callerMcpServers`: the same switch, with the words of a session's handlers and of a start. */ type MachineAccessKind = 'shellAndFiles' | 'sessionShellAndFiles' | 'callerMcpServers' | 'ssh'; interface MachineAccessRefusal { type: 'machine_access_refused'; code: 'machine_shell_and_files_off' | 'machine_ssh_off'; retryable: false; error: string; } interface MachineAccess { /** Null when the machine's user allowed this kind of access. */ refusal(kind: MachineAccessKind): MachineAccessRefusal | null; } declare const AgentPlaneTurnAuthorityV1Schema: z.ZodObject<{ protocolVersion: z.ZodLiteral<1>; expectedConduitInstanceId: z.ZodString; authorityGeneration: z.ZodNumber; activationId: z.ZodString; accountId: z.ZodString; actorId: z.ZodString; conversationId: z.ZodString; sessionSnapshotId: z.ZodString; runtimeTurnId: z.ZodString; runtimeAttemptNo: z.ZodNumber; runtimeAttemptId: z.ZodString; /** Unix timestamp in seconds, matching the MCP JWT-style `exp` claim. */ expiresAt: z.ZodNumber; mcpUrl: z.ZodEffects; mcpBearerToken: z.ZodEffects; codexMcpApprovalRequiredToolNames: z.ZodDefault, string[], string[]>>; allowedToolNames: z.ZodEffects, string[], string[]>; /** Selected by Agent Plane for this exact turn; absent only for older controllers. */ modelId: z.ZodOptional; git: z.ZodNullable; targets: z.ZodArray; connectorFingerprint: z.ZodString; }, "strict", z.ZodTypeAny, { deliveryWorkspaceId: string; providerBaseUrl: string; connectorFingerprint: string; }, { deliveryWorkspaceId: string; providerBaseUrl: string; connectorFingerprint: string; }>, "many">; }, "strict", z.ZodTypeAny, { appBaseUrl: string; targets: { deliveryWorkspaceId: string; providerBaseUrl: string; connectorFingerprint: string; }[]; }, { appBaseUrl: string; targets: { deliveryWorkspaceId: string; providerBaseUrl: string; connectorFingerprint: string; }[]; }>>; }, "strict", z.ZodTypeAny, { protocolVersion: 1; expectedConduitInstanceId: string; authorityGeneration: number; activationId: string; accountId: string; actorId: string; conversationId: string; sessionSnapshotId: string; runtimeTurnId: string; runtimeAttemptNo: number; runtimeAttemptId: string; expiresAt: number; mcpUrl: string; mcpBearerToken: string; codexMcpApprovalRequiredToolNames: string[]; allowedToolNames: string[]; git: { appBaseUrl: string; targets: { deliveryWorkspaceId: string; providerBaseUrl: string; connectorFingerprint: string; }[]; } | null; modelId?: string | undefined; }, { protocolVersion: 1; expectedConduitInstanceId: string; authorityGeneration: number; activationId: string; accountId: string; actorId: string; conversationId: string; sessionSnapshotId: string; runtimeTurnId: string; runtimeAttemptNo: number; runtimeAttemptId: string; expiresAt: number; mcpUrl: string; mcpBearerToken: string; allowedToolNames: string[]; git: { appBaseUrl: string; targets: { deliveryWorkspaceId: string; providerBaseUrl: string; connectorFingerprint: string; }[]; } | null; codexMcpApprovalRequiredToolNames?: string[] | undefined; modelId?: string | undefined; }>; declare const AgentPlaneRuntimeTurnAuthorityAdmissionV1Schema: z.ZodObject<{ protocolVersion: z.ZodLiteral<1>; conduitInstanceId: z.ZodString; sessionId: z.ZodString; authorityGeneration: z.ZodNumber; activationId: z.ZodString; promptLocalId: z.ZodString; }, "strict", z.ZodTypeAny, { protocolVersion: 1; authorityGeneration: number; activationId: string; sessionId: string; promptLocalId: string; conduitInstanceId: string; }, { protocolVersion: 1; authorityGeneration: number; activationId: string; sessionId: string; promptLocalId: string; conduitInstanceId: string; }>; type AgentPlaneTurnAuthorityV1 = z.infer; type AgentPlaneTurnAuthorityPhase = 'prepare' | 'activate' | 'close'; type AgentPlaneTurnAuthorityRejectionCode = 'invalid_request' | 'unsupported_provider' | 'session_not_found' | 'session_ambiguous' | 'session_not_idle' | 'session_outbox_pending' | 'runtime_binding_unavailable' | 'runtime_binding_mismatch' | 'authority_conflict' | 'generation_mismatch' | 'activation_mismatch' | 'invalid_transition' | 'authority_expired' | 'drain_timeout' | 'conduit_unavailable'; interface AgentPlaneTurnAuthorityRejectedV1 { type: 'authority_rejected'; protocolVersion: 1; conduitInstanceId: string; phase: AgentPlaneTurnAuthorityPhase; sessionId: string; code: AgentPlaneTurnAuthorityRejectionCode; retryable: boolean; } interface AgentPlaneTurnAuthorityPreparedV1 { type: 'authority_prepared'; protocolVersion: 1; conduitInstanceId: string; sessionId: string; authorityGeneration: number; activationId: string; state: 'prepared'; } interface AgentPlaneTurnAuthorityArmedV1 { type: 'authority_armed'; protocolVersion: 1; conduitInstanceId: string; sessionId: string; authorityGeneration: number; activationId: string; promptLocalId: string; state: 'armed'; } interface AgentPlaneTurnAuthorityClosedV1 { type: 'authority_closed'; protocolVersion: 1; conduitInstanceId: string; sessionId: string; authorityGeneration: number; activationId: string; state: 'closed'; } type PrepareAgentPlaneTurnAuthorityResultV1 = AgentPlaneTurnAuthorityPreparedV1 | AgentPlaneTurnAuthorityRejectedV1; type ActivateAgentPlaneTurnAuthorityResultV1 = AgentPlaneTurnAuthorityArmedV1 | AgentPlaneTurnAuthorityRejectedV1; type CloseAgentPlaneTurnAuthorityResultV1 = AgentPlaneTurnAuthorityClosedV1 | AgentPlaneTurnAuthorityRejectedV1; /** * One server of Claude Code's `--mcp-config`. The header names the local * capability's environment variable as `${NAME}`, which Claude Code fills in * from its environment; the value itself is never in the config, so it is * never on Claude's command line (checked with Claude Code 2.1.307 on * 22 October 2026). */ interface AgentPlaneClaudeMcpServerV1 { type: 'http'; url: string; headers: { Authorization: string; }; } interface AgentPlaneRuntimeConduitBootstrapV1 { protocolVersion: 1; conduitInstanceId: string; /** * Codex only: one capability for the runtime's whole life, read by its * long-lived app-server. A Claude runtime gets a capability of its own for * each admitted turn instead (AgentPlaneRuntimeTurnAuthorityAdmittedV1). */ localCapability?: string; mcpUrl: string; artifactUrl: string; codexMcpServers: Record; /** Present for a Claude runtime only; daemons before 22 October 2026 never send it. */ claudeMcpServers?: Record; environment: Record; } type AgentPlaneRuntimeTurnAuthorityAdmissionV1 = z.infer; interface AgentPlaneRuntimeTurnAuthorityAdmittedV1 { type: 'authority_admitted'; protocolVersion: 1; conduitInstanceId: string; sessionId: string; authorityGeneration: number; activationId: string; promptLocalId: string; state: 'active'; /** * Claude only: the capability of this admitted turn, valid until its disarm * (security review of 22 October 2026). The runtime gives it to that turn's * Claude process alone, so a process left from an earlier turn holds a dead one. */ turnCapability?: string; } interface AgentPlaneRuntimeTurnAuthorityDisarmedV1 { type: 'authority_disarmed'; protocolVersion: 1; conduitInstanceId: string; sessionId: string; authorityGeneration: number; activationId: string; promptLocalId: string; state: 'closed'; } interface SpawnSessionOptions { /** Same normal runtime, with fail-closed network prerequisites before any prompt. */ projectOperationsRequired?: true; machineId?: string; directory: string; sessionId?: string; approvedNewDirectoryCreation?: boolean; agent?: 'claude' | 'codex' | 'gemini'; token?: string; codexMcpServers?: Record; codexUseBuiltInHappyMcp?: boolean; environmentVariables?: Record; /** * `replace` preserves the legacy behavior for a non-empty RPC environment. * `overlay` adds RPC variables on top of the daemon's active local profile. */ environmentVariablesMode?: EnvironmentVariablesMode; /** Fail spawn unless the exact child session attests this terminal protocol. */ requiredTerminalProtocol?: 1; /** Exact first-turn authority retained only by the daemon-local conduit. */ agentPlaneAuthority?: AgentPlaneTurnAuthorityV1; /** * `exclusive` admits at most one live child per canonical workspace. Agent * Plane spawns always use it; interactive Happy spawns keep shared folders. */ runtimeSlot?: 'exclusive'; /** * Agent Plane's Continue on its off-login card (owner's decision 139 C): the conversation and the exact * off-login history it was shown. An isolated start on the owner's login in a conversation with that * history runs only with it (daemon/offLoginHistory.ts); apiMachine.ts checks it strictly. */ offLoginAcknowledgement?: OffLoginAcknowledgement; /** * The caller shows Agent Plane's off-login card: only then does decision 139 C apply (typed refusal, Codex * checked, acknowledgements). Without it the start meets the rule as before 139 C. Agreed with Agent Plane's * maintainer, 22 October 2026, so the other fixes ship before the card; the gate goes once the card is live. */ offLoginAware?: true; } /** Occupant reported by a runtime-slot rejection; nonsecret identity only. */ interface SpawnSlotOccupant { state: 'starting' | 'running' | 'terminating'; sessionId?: string; pid?: number; stopRequestedAt?: number; } /** * Typed spawn failure. `retryable` means the same request may succeed later * without operator action (for example, an occupant that is already exiting). */ type SpawnFailure = { code: 'runtime_slot_occupied'; retryable: boolean; occupant: SpawnSlotOccupant; } | { code: 'runtime_slot_owner_mismatch'; retryable: false; expectedSessionId: string | null; occupant: SpawnSlotOccupant | null; } | { code: 'runtime_slot_stop_timeout'; retryable: true; occupant: SpawnSlotOccupant; } | { code: 'child_exited_before_ready'; retryable: boolean; exitCode: number | null; signal: string | null; /** Typed code the child recorded (for example `codex_context_in_use`). */ childErrorCode: string | null; childErrorMessage: string | null; stderrTail: string; diagnosticsDirectory: string; } | { code: 'child_ready_timeout'; retryable: true; stderrTail: string; diagnosticsDirectory: string | null; } | { code: 'spawn_failed'; retryable: boolean; } | { code: 'execution_contract_not_met'; retryable: false; } | { code: 'isolation_service_unavailable'; retryable: true; } | { code: 'machine_shell_and_files_off'; retryable: false; } | OffLoginHistoryFailure; type EnvironmentVariablesMode = 'replace' | 'overlay'; type SpawnSessionResult = { type: 'success'; sessionId: string; terminalProtocol?: 1; sessionEncryption?: AgentPlaneSessionEncryptionAttestation; conduitInstanceId?: string; turnAuthority?: AgentPlaneTurnAuthorityPreparedV1; codexContextAttestation?: CodexContextAttestation; } | { type: 'requestToApproveDirectoryCreation'; directory: string; } | { type: 'error'; errorMessage: string; failure?: SpawnFailure; }; /** Exact exit of a replaced slot occupant. */ interface SpawnReplacedOccupant { sessionId?: string; pid: number; exit: { code: number | null; signal: string | null; observedAt: number; }; } interface ReplaceSessionResult { result: SpawnSessionResult; /** The previous occupant whose exit was proven, or null for an empty slot. */ replaced: SpawnReplacedOccupant | null; } /** Stop plus optional exact-exit confirmation. */ interface StopSessionAwaitResult { stopRequestAccepted: boolean; processExitConfirmed: boolean; exit?: { code: number | null; signal: string | null; observedAt: number; }; } declare const managedRuntimeConfigSchema: z.ZodEffects; instance: z.ZodString; machineId: z.ZodString; accountId: z.ZodString; serviceUser: z.ZodString; serviceHome: z.ZodString; daemonHome: z.ZodString; isolatorSocket: z.ZodString; programsSha256: z.ZodString; networkPolicyId: z.ZodString; networkPolicySha256: z.ZodString; defaults: z.ZodObject<{ claude: z.ZodString; codex: z.ZodString; }, "strict", z.ZodTypeAny, { claude: string; codex: string; }, { claude: string; codex: string; }>; gateways: z.ZodObject<{ model: z.ZodEffects; localModel: z.ZodEffects; webProxy: z.ZodNullable>; }, "strict", z.ZodTypeAny, { model: string; localModel: string; webProxy: string | null; }, { model: string; localModel: string; webProxy: string | null; }>; webAccess: z.ZodObject<{ mode: z.ZodEnum<["none", "allowlist", "public"]>; hosts: z.ZodArray; }, "strict", z.ZodTypeAny, { mode: "none" | "allowlist" | "public"; hosts: string[]; }, { mode: "none" | "allowlist" | "public"; hosts: string[]; }>; }, "strict", z.ZodTypeAny, { accountId: string; version: 1; machineId: string; instance: string; serviceUser: string; programsSha256: string; networkPolicyId: string; networkPolicySha256: string; webAccess: { mode: "none" | "allowlist" | "public"; hosts: string[]; }; serviceHome: string; daemonHome: string; isolatorSocket: string; defaults: { claude: string; codex: string; }; gateways: { model: string; localModel: string; webProxy: string | null; }; }, { accountId: string; version: 1; machineId: string; instance: string; serviceUser: string; programsSha256: string; networkPolicyId: string; networkPolicySha256: string; webAccess: { mode: "none" | "allowlist" | "public"; hosts: string[]; }; serviceHome: string; daemonHome: string; isolatorSocket: string; defaults: { claude: string; codex: string; }; gateways: { model: string; localModel: string; webProxy: string | null; }; }>, { accountId: string; version: 1; machineId: string; instance: string; serviceUser: string; programsSha256: string; networkPolicyId: string; networkPolicySha256: string; webAccess: { mode: "none" | "allowlist" | "public"; hosts: string[]; }; serviceHome: string; daemonHome: string; isolatorSocket: string; defaults: { claude: string; codex: string; }; gateways: { model: string; localModel: string; webProxy: string | null; }; }, { accountId: string; version: 1; machineId: string; instance: string; serviceUser: string; programsSha256: string; networkPolicyId: string; networkPolicySha256: string; webAccess: { mode: "none" | "allowlist" | "public"; hosts: string[]; }; serviceHome: string; daemonHome: string; isolatorSocket: string; defaults: { claude: string; codex: string; }; gateways: { model: string; localModel: string; webProxy: string | null; }; }>; type ManagedRuntimeConfig = z.infer; /** * Read-only, incarnation-fenced runtime observations for Agent Plane. These are * facts, never grants. A launch setting, child metadata or an absent MCP tool is * not evidence about the provider's native tools or the kernel's network route. */ interface RuntimeCapabilityObservation { version: 1; sessionId: string; runtimeSessionInstanceId: string | null; observedAt: string; process: { pid: number; birth: string; }; workspace: string | null; isolation: { status: 'verified'; runtimeId: string; source: 'root_isolator'; } | { status: 'unknown'; reason: string; }; network: { status: 'verified'; mode: 'default_deny'; policyId: string; policySha256: string; probeSha256: string; gatewayPolicy?: { source: 'root_configuration'; configurationSha256: string; webAccess: ManagedRuntimeConfig['webAccess']; }; } | { status: 'unknown'; reason: string; }; instructions: unknown | null; } type DaemonSessionStatus = 'tracked_alive' | 'tracked_dead' | 'recovered_alive' | 'recovered_dead' | 'unknown'; /** * Proof that a session this daemon has no record of is not running on this machine: no * daemon-started Boujot runtime child exists that the daemon does not track. A session's process * is always such a child (`… --happy-starting-mode … --started-by daemon`), so with none untracked, * an unknown session has no process. A child spawned but not yet tracked counts as untracked, so a * launch in flight withholds the proof. */ interface ProcessScanAbsenceProof { proofVersion: 1; source: 'process_scan'; observation: 'no_untracked_runtime_children'; observedAt: number; } type ClaudeAuthenticationStatus = 'ready' | 'required' | 'unknown'; /** Isolated sessions' own login (the daemon keeps it), or the machine user's login. */ type ClaudeLoginCommand = 'boujot claude-login' | 'claude auth login'; interface ClaudeProviderReadiness { type: 'provider-readiness'; provider: 'claude'; checkedAt: number; ready: boolean; executable: { /** `unavailable_in_isolated_sessions`: installed or not, Claude does not run in this machine's isolated sessions. */ status: 'ready' | 'missing' | 'unknown' | 'unavailable_in_isolated_sessions'; }; authentication: { status: ClaudeAuthenticationStatus; verification: 'claude_auth_status' | 'model_gateway_catalog'; reason: 'authenticated' | 'authentication_required' | 'probe_failed' | 'invalid_response' | 'gateway_not_checked' | 'not_in_isolated_sessions' | 'login_missing' | 'login_ended'; /** * The command the machine's user runs there to log in (agreed with Agent Plane on 21 October * 2026; it shows this field, never a command taken from `detail`). One of a closed set. */ loginCommand?: ClaudeLoginCommand; /** What happened when the check failed, in one short line (exit code, signal, Claude's error). */ detail?: string; authMethod?: string; apiProvider?: string; }; } interface ProviderReadinessRequest { provider: 'claude'; environmentVariables?: Record; environmentVariablesMode?: EnvironmentVariablesMode; token?: string; } type ProviderReadinessResponse = ClaudeProviderReadiness; interface DaemonSshRequest { targetId: string; host: string; port: number; user: string; credentialRef: string; remoteDir: string | null; timeoutMs: number; command?: string; } interface DaemonSshResult { type: 'ssh-check-result' | 'ssh-exec-result'; targetId: string; connected: boolean; exitCode: number | null; signal: NodeJS.Signals | null; stdout: string; stderr: string; timedOut: boolean; truncated: boolean; durationMs: number; } type MachineRpcHandlers = { readProjectOperationRuntimeEvidence?: (request: unknown) => Promise; /** * Whether a Codex chat's thread can be kept across sessions from the context file its session * folder carries: only when runtimes are launched directly, so the daemon's context store is theirs. */ codexContextSessionFile?: boolean; nativeContextVersion?: 1 | (() => 1 | undefined); exportNativeContextChunk?: (request: unknown) => Promise; importNativeContextChunk?: (request: unknown) => Promise; /** Writes Agent Plane session files where the runtime launcher keeps workspaces. */ prepareAgentPlaneSession: (params: PrepareAgentPlaneSessionRequest) => Promise; spawnSession: (options: SpawnSessionOptions) => Promise; stopSession: (sessionId: string) => boolean | Promise; /** Atomic stop-prove-exit-spawn of an exclusive workspace slot. */ replaceSession?: (options: SpawnSessionOptions, expectedSessionId: string | null) => Promise; /** Stop, then wait (bounded) for exact process exit. */ stopSessionAndAwaitExit?: (sessionId: string, timeoutMs: number) => Promise; sessionStatusList: (sessionIds: string[], options?: { includeRuntimeCapabilities?: boolean; }) => Array<{ sessionId: string; status: DaemonSessionStatus | 'absent'; /** Set while this daemon runs, for a runtime it stopped because the contract no longer allows it. */ stoppedBy?: 'execution_contract'; pid?: number; startedBy?: string; trackingSource?: 'memory' | 'registry'; terminalProtocol?: 1; sessionEncryption?: AgentPlaneSessionEncryptionAttestation; runtimeCapabilities?: RuntimeCapabilityObservation; proof?: { proofVersion: 1; source: 'persisted_registry'; observation: 'pid_absent'; processBirthFingerprint: string; observedAt: number; } | ProcessScanAbsenceProof; }> | Promise>; providerReadiness: (request: ProviderReadinessRequest) => Promise; sshCheck?: (request: DaemonSshRequest) => Promise; sshExec?: (request: DaemonSshRequest) => Promise; prepareAgentPlaneTurnAuthority?: (request: unknown) => Promise; activateAgentPlaneTurnAuthority?: (request: unknown) => ActivateAgentPlaneTurnAuthorityResultV1 | Promise; closeAgentPlaneTurnAuthority?: (request: unknown) => Promise; preflightAgentPlaneTurnAuthority?: (phase: AgentPlaneTurnAuthorityPhase, request: unknown) => AgentPlaneTurnAuthorityRejectedV1 | null | Promise; preflightAgentPlaneAuthoritySpawn?: (authority: unknown) => { allowed: boolean; retryable: boolean; } | Promise<{ allowed: boolean; retryable: boolean; }>; agentPlaneTurnAuthorityConduitInstanceId?: string; requestShutdown: () => void | Promise; }; declare const DAEMON_MANAGED_MACHINE_METADATA_KEYS: readonly ["host", "platform", "happyCliVersion", "rpcBinding", "rpcBindingCliVersion", "homeDir", "happyHomeDir", "happyLibDir", "claudeCodeVersion", "claudeCodeLatestVersion", "claudeCodeUpdateCommand", "executionContract", "managedRuntime"]; type DaemonManagedMachineMetadataKey = typeof DAEMON_MANAGED_MACHINE_METADATA_KEYS[number]; declare class ApiMachineClient { private machine; private currentMachineMetadata?; private socket; private keepAliveInterval; private credentialReconnectTimer; private credentialReconnectAttempt; private shuttingDown; private rpcHandlerManager; private readonly socketCredential; private agentPlaneTurnAuthorityConduitInstanceId; private agentPlaneSshSupported; /** The machine's local switches for its shell, files and SSH; nothing until the daemon hands them over. */ private machineAccess; private agentPlaneRuntimeSlotsSupported; private agentPlaneCodexContextSessionFile; private nativeContextVersion?; private readonly codexDeviceLogin; private readonly claudeLogin; constructor(tokenOrExchange: string | SocketCredentialExchange, machine: Machine, currentMachineMetadata?: MachineMetadata | undefined); setRPCHandlers({ readProjectOperationRuntimeEvidence, prepareAgentPlaneSession, spawnSession, stopSession, replaceSession, stopSessionAndAwaitExit, sessionStatusList, providerReadiness, sshCheck, sshExec, prepareAgentPlaneTurnAuthority, activateAgentPlaneTurnAuthority, closeAgentPlaneTurnAuthority, preflightAgentPlaneTurnAuthority, preflightAgentPlaneAuthoritySpawn, agentPlaneTurnAuthorityConduitInstanceId, requestShutdown, codexContextSessionFile, nativeContextVersion, exportNativeContextChunk, importNativeContextChunk, }: MachineRpcHandlers): void; /** * 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; /** The machine's local switches (daemon/machineAccess.ts), read again at each call. */ setMachineAccess(access: MachineAccess): void; /** * Replaces daemon-managed values (the execution contract report) and * writes them to the relay; a failed write is repeated at the next * connection, which compares them again. */ updateDaemonManagedMetadata(changes: Partial>): void; private externalWriteBackTimer; private lastExternalWriteBackAt; private scheduleExternalWriteBack; /** True when it wrote the daemon's keys to the relay. */ private reconcileDaemonManagedMachineMetadata; /** * Update daemon state (runtime info) - similar to session updateAgentState * Simplified without lock - relies on backoff for retry */ updateDaemonState(handler: (state: DaemonState | null) => DaemonState): Promise; private handleUpdate; connect(): void; private startKeepAlive; private stopKeepAlive; private scheduleCredentialReconnect; private clearCredentialReconnect; shutdown(): void; } interface RuntimeBootstrapRequest { pid: number; tag: string; metadata: Metadata; state: AgentState | null; sessionInstanceId: string; codexContext?: CodexBootstrapContext; } interface RuntimeCredentialRequest { pid: number; sessionId: string; sessionInstanceId: string; } interface RuntimeBootstrapResult { session: Session; credential: IssuedSocketCredential; sessionInstanceId: string; agentPlaneConduit?: AgentPlaneRuntimeConduitBootstrapV1; } declare class DaemonRuntimeBootstrapClient { private capability; private readonly daemonStateFile; readonly machineId: string; constructor(capability: string, daemonStateFile: string, machineId: string); bootstrap(request: RuntimeBootstrapRequest): Promise; recoverCredential(request: RuntimeCredentialRequest): Promise; codexLogin(request: RuntimeCredentialRequest & { previousAccountId?: string; }): Promise<{ accessToken: string; chatgptAccountId: string; } | null>; admitAgentPlaneTurnAuthority(request: AgentPlaneRuntimeTurnAuthorityAdmissionV1 & { sessionInstanceId: string; }): Promise; disarmAgentPlaneTurnAuthority(request: AgentPlaneRuntimeTurnAuthorityAdmissionV1 & { sessionInstanceId: string; }): Promise; runtimeRequest(sessionId: string, sessionInstanceId: string): RuntimeSocketCredentialRequest; private post; } interface PushClient { sendToAllDevices(title: string, body: string, data?: Record): void; } declare class ApiClient { private readonly runtimeBootstrap; static create(credential: Credentials): Promise; static createRuntimeBrokered(runtimeBootstrap: DaemonRuntimeBootstrapClient): ApiClient; private readonly credential; private readonly pushClient; private readonly socketCredentials; private readonly runtimeSessionCredentials; private constructor(); /** * Create a new session or load existing one with the given tag */ getOrCreateSession(opts: { tag: string; metadata: Metadata; state: AgentState | null; codexContext?: CodexBootstrapContext; }): Promise; /** * 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; }): Promise; sessionSyncClient(session: Session): ApiSessionClient; machineSyncClient(machine: Machine, currentMachineMetadata?: MachineMetadata): ApiMachineClient; socketCredentialExchange(): SocketCredentialExchange; push(): PushClient; admitAgentPlaneTurnAuthority(request: AgentPlaneRuntimeTurnAuthorityAdmissionV1): Promise; runtimeCodexLogin(sessionId: string, previousAccountId?: string): Promise<{ accessToken: string; chatgptAccountId: string; } | null>; disarmAgentPlaneTurnAuthority(request: AgentPlaneRuntimeTurnAuthorityAdmissionV1): Promise; private requireAccountCredential; private requireSocketCredentials; } /** * 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/.log */ declare class Logger { readonly logFilePath: string; private dangerouslyUnencryptedServerLoggingUrl; constructor(logFilePath?: string); 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 */ type Flavor = 'happy' | 'boujot'; declare class Configuration { readonly flavor: Flavor; /** CLI command name: 'happy' or 'boujot' — use in help text and command examples */ readonly cliName: string; /** Display brand: 'Happy' or 'Boujot' — use in user-facing messages */ readonly brandName: string; /** Config directory name: '.boujot' or '.boujot' */ readonly configDirName: string; /** * Where a user reports a problem with this CLI. The fork has no public * issue tracker; a report filed with the upstream project would show * another party the logs of this installation. */ readonly bugReportEmail = "report@meow.ch"; readonly serverUrl: string; /** * The web app that approves a browser login; undefined when * HAPPY_WEBAPP_URL is not set. There is no default: the login link carries * the terminal's one-time secret to this address, and a guessed address * (the upstream product's site, until now) hands it to someone else. * Only the browser login needs it, so it is checked there (checkedWebappUrl) * and not at startup. */ readonly webappUrl: string | undefined; readonly isDaemonProcess: boolean; readonly happyHomeDir: string; readonly logsDir: string; readonly settingsFile: string; readonly privateKeyFile: string; readonly daemonStateFile: string; readonly daemonLockFile: string; readonly currentCliVersion: string; readonly isExperimentalEnabled: boolean; readonly disableCaffeinate: boolean; constructor(); } declare const configuration: Configuration; export { ApiClient, ApiSessionClient, RawJSONLinesSchema, configuration, logger }; export type { RawJSONLines };