import * as z from 'zod'; import { z as z$1 } from 'zod'; import { EventEmitter } from 'node:events'; import { Socket } from 'socket.io-client'; import { CreateEnvelopeOptions, SessionEnvelope, SessionTurnEndStatus } from 'shifft-wire'; import { ExpoPushMessage } from 'expo-server-sdk'; /** * Simplified schema that only validates fields actually used in the codebase * while preserving all other fields through passthrough() */ declare const UsageSchema: z$1.ZodObject<{ input_tokens: z$1.ZodNumber; cache_creation_input_tokens: z$1.ZodOptional; cache_read_input_tokens: z$1.ZodOptional; output_tokens: z$1.ZodNumber; service_tier: z$1.ZodOptional; }, z$1.core.$loose>; declare const RawJSONLinesSchema: z$1.ZodDiscriminatedUnion<[z$1.ZodObject<{ type: z$1.ZodLiteral<"user">; isSidechain: z$1.ZodOptional; isMeta: z$1.ZodOptional; uuid: z$1.ZodString; message: z$1.ZodObject<{ content: z$1.ZodUnion; }, z$1.core.$loose>; }, z$1.core.$loose>, z$1.ZodObject<{ uuid: z$1.ZodString; type: z$1.ZodLiteral<"assistant">; message: z$1.ZodOptional; cache_read_input_tokens: z$1.ZodOptional; output_tokens: z$1.ZodNumber; service_tier: z$1.ZodOptional; }, z$1.core.$loose>>; model: z$1.ZodOptional; }, z$1.core.$loose>>; }, z$1.core.$loose>, z$1.ZodObject<{ type: z$1.ZodLiteral<"summary">; summary: z$1.ZodString; leafUuid: z$1.ZodString; }, z$1.core.$loose>, z$1.ZodObject<{ type: z$1.ZodLiteral<"system">; uuid: z$1.ZodString; }, z$1.core.$loose>], "type">; type RawJSONLines = z$1.infer; /** * Minimal persistence functions for shifft CLI * * Handles settings and private key storage in ~/.shifft/ or local .shifft/ */ declare const SandboxConfigSchema: z.ZodObject<{ enabled: z.ZodDefault; workspaceRoot: z.ZodOptional; sessionIsolation: z.ZodDefault>; customWritePaths: z.ZodDefault>; denyReadPaths: z.ZodDefault>; extraWritePaths: z.ZodDefault>; denyWritePaths: z.ZodDefault>; networkMode: z.ZodDefault>; allowedDomains: z.ZodDefault>; deniedDomains: z.ZodDefault>; allowLocalBinding: z.ZodDefault; }, z.core.$strip>; type SandboxConfig = z.infer; type Credentials = { token: string; encryption: { type: 'legacy'; secret: Uint8Array; } | { type: 'dataKey'; publicKey: Uint8Array; machineKey: Uint8Array; }; }; /** * Permission mode type - includes both Claude and Codex modes * Must match MessageMetaSchema.permissionMode enum values * * Claude modes: default, acceptEdits, bypassPermissions, plan * Codex modes: read-only, safe-yolo, yolo * * When calling Claude SDK, Codex modes are mapped at the SDK boundary: * - yolo → bypassPermissions * - safe-yolo → default * - read-only → default */ type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'read-only' | 'safe-yolo' | 'yolo'; /** * Usage data type from Claude */ type Usage = z$1.infer; /** * Session information */ type Session = { id: string; seq: number; encryptionKey: Uint8Array; encryptionVariant: 'legacy' | 'dataKey'; metadata: Metadata; metadataVersion: number; agentState: AgentState | null; agentStateVersion: number; }; /** * Machine metadata - static information (rarely changes) */ declare const MachineMetadataSchema: z$1.ZodObject<{ host: z$1.ZodString; platform: z$1.ZodString; shifftCliVersion: z$1.ZodString; homeDir: z$1.ZodString; shifftHomeDir: z$1.ZodString; shifftLibDir: z$1.ZodString; cliAvailability: z$1.ZodOptional>; resumeSupport: z$1.ZodOptional>; }, z$1.core.$strip>; type MachineMetadata = z$1.infer; /** * Daemon state - dynamic runtime information (frequently updated) */ declare const DaemonStateSchema: z$1.ZodObject<{ status: z$1.ZodUnion, z$1.ZodString]>; pid: z$1.ZodOptional; httpPort: z$1.ZodOptional; startedAt: z$1.ZodOptional; shutdownRequestedAt: z$1.ZodOptional; shutdownSource: z$1.ZodOptional, z$1.ZodString]>>; }, z$1.core.$strip>; type DaemonState = z$1.infer; type Machine = { id: string; encryptionKey: Uint8Array; encryptionVariant: 'legacy' | 'dataKey'; metadata: MachineMetadata; metadataVersion: number; daemonState: DaemonState | null; daemonStateVersion: number; }; declare const UserMessageSchema: z$1.ZodObject<{ role: z$1.ZodLiteral<"user">; content: z$1.ZodObject<{ type: z$1.ZodLiteral<"text">; text: z$1.ZodString; }, z$1.core.$strip>; localKey: z$1.ZodOptional; meta: z$1.ZodOptional; permissionMode: z$1.ZodOptional>; model: z$1.ZodOptional>; fallbackModel: z$1.ZodOptional>; customSystemPrompt: z$1.ZodOptional>; appendSystemPrompt: z$1.ZodOptional>; allowedTools: z$1.ZodOptional>>; disallowedTools: z$1.ZodOptional>>; }, z$1.core.$strip>>; }, z$1.core.$strip>; type UserMessage = z$1.infer; /** * File event message — sent by the app as a session envelope before the text message. * Contains a ref pointing to the encrypted blob on the server. */ declare const FileEventMessageSchema: z$1.ZodObject<{ role: z$1.ZodLiteral<"session">; content: z$1.ZodObject<{ type: z$1.ZodLiteral<"session">; data: z$1.ZodObject<{ id: z$1.ZodString; time: z$1.ZodNumber; role: z$1.ZodLiteral<"user">; ev: z$1.ZodObject<{ t: z$1.ZodLiteral<"file">; ref: z$1.ZodString; name: z$1.ZodString; size: z$1.ZodNumber; mimeType: z$1.ZodOptional; image: z$1.ZodOptional; }, z$1.core.$strip>>; }, z$1.core.$strip>; }, z$1.core.$strip>; }, z$1.core.$strip>; }, z$1.core.$strip>; type FileEventMessage = z$1.infer; type Metadata = { /** * ACP session config option value (normalized for UI metadata consumers). */ models?: Array<{ code: string; value: string; description?: string | null; }>; currentModelCode?: string; operatingModes?: Array<{ code: string; value: string; description?: string | null; }>; currentOperatingModeCode?: string; thoughtLevels?: Array<{ code: string; value: string; description?: string | null; }>; currentThoughtLevelCode?: string; path: string; host: string; version?: string; name?: string; os?: string; summary?: { text: string; updatedAt: number; }; machineId?: string; claudeSessionId?: string; codexThreadId?: string; tools?: string[]; slashCommands?: string[]; mcpServers?: Array<{ name: string; status: string; }>; skills?: string[]; homeDir: string; shifftHomeDir: string; shifftLibDir: string; shifftToolsDir: string; startedFromDaemon?: boolean; hostPid?: number; startedBy?: 'daemon' | 'terminal'; lifecycleState?: 'running' | 'archiveRequested' | 'archived' | string; lifecycleStateSince?: number; archivedBy?: string; archiveReason?: string; flavor?: string; sandbox?: SandboxConfig | null; dangerouslySkipPermissions?: boolean | null; /** Lineage for sessions created via the fork / duplicate flow. */ parentSessionId?: string; forkedFromMessageId?: string; }; type AgentGoalStatus = { source: 'claude' | 'codex'; observedAt: number; sourceSessionId?: string; sourceRevision?: string | number; } & ({ status: 'unavailable'; reason?: 'unsupported' | 'not_loaded' | 'stale' | 'malformed' | 'error' | 'unknown'; } | { status: 'inactive'; reason?: 'none' | 'cleared' | 'completed' | 'unknown'; } | { status: 'active'; sourceSessionId: string; text: string; capabilities?: { clear?: boolean; stop?: boolean; edit?: boolean; }; progress?: { currentStep?: number; totalSteps?: number; steps?: Array<{ text: string; status: 'pending' | 'in_progress' | 'completed'; }>; }; }); type AgentState = { controlledByUser?: boolean | null | undefined; requests?: { [id: string]: { tool: string; arguments: any; createdAt: number; }; }; completedRequests?: { [id: string]: { tool: string; arguments: any; createdAt: number; completedAt: number; status: 'canceled' | 'denied' | 'approved'; reason?: string; mode?: PermissionMode; decision?: 'approved' | 'approved_for_session' | 'denied' | 'abort'; allowTools?: string[]; }; }; agentGoalStatus?: AgentGoalStatus; }; /** * 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; /** * RPC request data from server */ interface RpcRequest { method: string; params: string; } /** * Configuration for RPC handler manager */ interface RpcHandlerConfig { scopePrefix: string; encryptionKey: Uint8Array; encryptionVariant: 'legacy' | 'dataKey'; logger?: (message: string, data?: any) => void; } /** * Generic RPC handler manager for session and machine clients * Manages RPC method registration, encryption/decryption, and handler execution */ declare class RpcHandlerManager { private handlers; private readonly scopePrefix; private readonly encryptionKey; private readonly encryptionVariant; private readonly logger; 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): void; unregisterHandler(method: string): void; /** * Handle an incoming RPC request * @param request - The RPC request data * @param callback - The response callback */ handleRequest(request: RpcRequest): Promise; onSocketConnect(socket: Socket): void; onSocketDisconnect(): void; /** * Get the number of registered handlers */ getHandlerCount(): number; /** * Check if a handler is registered * @param method - The method name (without prefix) */ hasHandler(method: string): boolean; /** * Clear all handlers */ clearHandlers(): void; /** * Get the prefixed method name * @param method - The method name */ private getPrefixedMethod; } /** * 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: 'tool-call'; callId: string; name: string; input: unknown; id: string; } | { type: 'tool-result'; callId: string; output: unknown; id: string; isError?: boolean; } | { type: 'file-edit'; description: string; filePath: string; diff?: string; oldContent?: string; newContent?: string; id: string; } | { type: 'terminal-output'; data: string; callId: string; } | { type: 'task_started'; id: string; } | { type: 'task_complete'; id: string; } | { type: 'turn_aborted'; id: string; } | { type: 'permission-request'; permissionId: string; toolName: string; description: string; options?: unknown; } | { type: 'token_count'; [key: string]: unknown; }; type LocalImageAttachment = { data: Uint8Array; mimeType: string; name: string; }; declare class ApiSessionClient extends EventEmitter { private readonly token; readonly sessionId: string; private metadata; private metadataVersion; private agentState; private agentStateVersion; private socket; private pendingMessages; private pendingMessageCallback; private pendingFileEvents; private pendingFileEventCallback; private blobKey; /** * In-flight attachment download promises that belong to the *current* * (not-yet-drained) batch. Each promise resolves to the decoded blob (or * null on failure), so per-message ownership is intrinsic — there is no * shared push-array between batches that a late download could leak into. */ private pendingDownloads; readonly rpcHandlerManager: RpcHandlerManager; private agentStateLock; private metadataLock; private encryptionKey; private encryptionVariant; private reconnectInterval; private ignoreArchiveSignal; private skipInitialMessages; private claudeSessionProtocolState; private lastSeq; private pendingOutbox; private readonly sendSync; private readonly receiveSync; constructor(token: string, session: Session); onUserMessage(callback: (data: UserMessage) => void): void; onFileEvent(callback: (data: FileEventMessage) => void): void; /** * Derive (and cache) the blob decryption key for this session. * Legacy sessions use deriveKey(masterSecret, 'Shifft Blobs', ['master']). * DataKey sessions use deriveKey(dataKey, 'Shifft Blobs', ['session']). */ getBlobKey(): Promise; private requestAttachmentUpload; private uploadEncryptedAttachmentBlob; uploadLocalImageAttachmentEnvelope(attachment: LocalImageAttachment, opts?: Pick): Promise; /** * Download an encrypted attachment blob via the request-download flow: * POST /request-download → { downloadUrl } → GET downloadUrl. Local mode * downloadUrl points back at our server (Bearer required); S3 mode is a * presigned URL that does not accept extra headers. */ downloadAttachment(ref: string): Promise; /** * Download and decrypt an attachment blob. * Returns the decrypted binary data or null if decryption fails. */ downloadAndDecryptAttachment(ref: string): Promise; /** * Track an attachment download whose promise resolves to the decoded blob * (or null on failure). The download stays in the current batch until the * next drainAttachmentsForUserMessage call swaps the bucket out — file * events that arrive after the swap go into a fresh bucket bound to the * next user-text message. */ trackAttachmentDownload(promise: Promise<{ data: Uint8Array; mimeType: string; name: string; } | null>): void; /** * Atomically claim every download started before this call, wait for them * to resolve, and return the successful ones. The swap-then-await order * guarantees that a late-arriving file event cannot leak into this batch. */ drainAttachmentsForUserMessage(): Promise>; private authHeaders; private routeIncomingMessage; private fetchMessages; private static readonly MAX_OUTBOX_BATCH_SIZE; private flushOutbox; private enqueueMessage; private enqueueSessionProtocolEnvelopes; private applyClaudeSessionMessageSideEffects; /** * Send message to session * @param body - Message body (can be MessageContent or raw content for agent messages) */ sendClaudeSessionMessage(body: RawJSONLines): void; sendClaudeSessionMessageFromLocalTranscript(body: RawJSONLines): Promise; closeClaudeSessionTurn(status?: SessionTurnEndStatus): void; sendCodexMessage(body: any): void; private enqueueSessionProtocolEnvelope; sendSessionProtocolMessage(envelope: SessionEnvelope): void; /** * Send a generic agent message to the session using ACP (Agent Communication Protocol) format. * Works for any agent type (Gemini, Codex, Claude, etc.) - CLI normalizes to unified ACP format. * * @param provider - The agent provider sending the message (e.g., 'gemini', 'codex', 'claude') * @param body - The message payload (type: 'message' | 'reasoning' | 'tool-call' | 'tool-result') */ sendAgentMessage(provider: 'gemini' | 'codex' | 'claude' | 'opencode' | 'openclaw', body: ACPMessageData): void; sendSessionEvent(event: { type: 'switch'; mode: 'local' | 'remote'; } | { type: 'message'; message: string; } | { type: 'permission-mode-changed'; mode: 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan'; } | { 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; /** * Returns the latest session metadata known to the client. */ getMetadata(): Metadata | null; /** * Update session metadata * @param handler - Handler function that returns the updated metadata */ suppressNextArchiveSignal(): void; skipExistingMessages(): void; 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 startSmartReconnect; } interface SpawnSessionOptions { machineId?: string; directory: string; sessionId?: string; approvedNewDirectoryCreation?: boolean; agent?: 'claude' | 'codex' | 'gemini' | 'openclaw'; environmentVariables?: Record; token?: string; /** * If set, the daemon spawns the agent with `--resume ` so the new * Shifft session continues from an existing Claude conversation file. * Used by the session fork / duplicate flow: the fork RPC produces a * new Claude JSONL on disk, the spawn RPC then attaches a fresh Shifft * session to it. */ resumeClaudeSessionId?: string; /** * If set, the daemon spawns Codex with `--resume ` so a fresh Shifft * session attaches to a forked Codex app-server thread. */ resumeCodexThreadId?: string; /** Shifft session id this fork was branched from (lineage). */ parentSessionId?: string; /** Shifft message id used as the rewind point (only set for "duplicate"). */ forkedFromMessageId?: string; } type SpawnSessionResult = { type: 'success'; sessionId: string; } | { type: 'requestToApproveDirectoryCreation'; directory: string; } | { type: 'error'; errorMessage: string; }; /** * WebSocket client for machine/daemon communication with Shifft server * Similar to ApiSessionClient but for machine-scoped connections */ type MachineRpcHandlers = { spawnSession: (options: SpawnSessionOptions) => Promise; resumeSession?: (sessionId: string, options?: { model?: string; permissionMode?: string; }) => Promise; stopSession: (sessionId: string) => boolean; requestShutdown: () => void; }; declare class ApiMachineClient { private token; private machine; private socket; private keepAliveInterval; private lastKnownCLIAvailability; private lastKnownResumeSupport; private rpcHandlerManager; private resumeSessionHandler; private reconnectInterval; constructor(token: string, machine: Machine); setRPCHandlers({ spawnSession, resumeSession, stopSession, requestShutdown }: MachineRpcHandlers): void; private syncResumeSessionRpcRegistration; /** * 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; /** * Update daemon state (runtime info) - similar to session updateAgentState * Simplified without lock - relies on backoff for retry */ updateDaemonState(handler: (state: DaemonState | null) => DaemonState): Promise; connect(): void; private startKeepAlive; private startSmartReconnect; private stopKeepAlive; shutdown(): void; } interface PushToken { id: string; token: string; createdAt: number; updatedAt: number; } type SessionNotificationKind = 'done' | 'permission' | 'question'; declare class PushNotificationClient { private readonly token; private readonly baseUrl; private readonly expo; constructor(token: string, baseUrl?: string); /** * Fetch all push tokens for the authenticated user. * Retries up to 3 times with exponential backoff on transient errors. */ fetchPushTokens(): Promise; /** * Send push notification via Expo Push API with retry * @param messages - Array of push messages to send */ sendPushNotifications(messages: ExpoPushMessage[]): Promise; /** * Send a push notification to all registered devices for the user * @param title - Notification title * @param body - Notification body * @param data - Additional data to send with the notification */ sendToAllDevices(title: string, body?: string, data?: Record): void; /** * Routes session-event pushes through the server so it can apply * presence-based suppression (active desktop/web, mobile foreground). * Falls back to direct Expo send only when sessionId is missing — that * shouldn't happen for session notifications but guards against regressions. */ sendSessionNotification(params: { kind: SessionNotificationKind; metadata: Metadata | null | undefined; data?: Record; }): void; } declare class ApiClient { static create(credential: Credentials): Promise; private readonly credential; private readonly pushClient; private constructor(); /** * Create a new session or load existing one with the given tag */ getOrCreateSession(opts: { tag: string; metadata: Metadata; state: AgentState | null; }): 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): ApiMachineClient; push(): PushNotificationClient; /** * Register a vendor API token with the server * The token is sent as a JSON string - server handles encryption */ registerVendorToken(vendor: 'openai' | 'anthropic' | 'gemini', apiKey: any): Promise; /** * Get vendor API token from the server * Returns the token if it exists, null otherwise */ getVendorToken(vendor: 'openai' | 'anthropic' | 'gemini'): Promise; /** * Mark a session as inactive on the server (active=false). Does NOT * change `lifecycleState`, so the session remains visible in the app * and resumable — same effect as the in-app "Archive" button hitting * the /archive endpoint, but without the extra metadata. * * Used during graceful shutdown (Ctrl-C / SIGTERM) as a synchronous * fallback for the socket-based session-end signal: even if the * socket emit doesn't drain before the process exits, the HTTP * response confirms the deactivate landed. */ deactivateSession(sessionId: string): Promise; } /** * 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 shifft CLI * * Centralizes all configuration including environment variables and paths * Environment files should be loaded using Node's --env-file flag */ declare class Configuration { readonly serverUrl: string; readonly webappUrl: string; readonly isDaemonProcess: boolean; readonly shifftHomeDir: string; readonly logsDir: string; readonly settingsFile: string; readonly privateKeyFile: string; readonly daemonStateFile: string; readonly daemonLockFile: string; readonly sessionsFile: string; readonly currentCliVersion: string; readonly isExperimentalEnabled: boolean; readonly disableCaffeinate: boolean; constructor(); } declare const configuration: Configuration; export { ApiClient, ApiSessionClient, RawJSONLinesSchema, configuration, logger }; export type { RawJSONLines };