Skip to content

Session API, events, and storage

This page answers a question-oriented slice of cli.js: how are sessions designed, does remote control exist, what API/event/storage surfaces are visible, and how do those pieces compose?

It complements Session resume and transcripts, Remote control and teleport, and Session and remote-control architecture. Those pages explain individual flows; this page is the list/reference view.

Use Data models and frame schemas for the canonical transcript-record, session-layer, and frame-family schema reference.

Short answer

  • A session is designed as a durable local JSONL transcript plus a live runtime envelope addressed by one session ID.
  • Remote control does exist. The visible entrypoints are --remote, --teleport, --remote-control, and --rc; the implementation projects the same session envelope over bridge/session-ingress transports instead of creating a separate remote runtime.
  • API calls are not one neat table in source. cli.js embeds several families: Claude Code cloud/runtime endpoints, Anthropic SDK generated endpoints, MCP JSON-RPC methods, telemetry/OTEL endpoints, and third-party integration endpoints.
  • Events are also plural: hook event names, stream/SDK frames, bridge/control frames, MCP JSON-RPC notifications, telemetry events, and JSONL transcript entries.
  • Internal storage exists and is mostly file-backed: per-session JSONL, per-project metadata, file-history/context-collapse/checkpoint records, task/session queues, optional SDK sessionStore mirroring, scheduled-task files/locks, debug logs, and caches.

Source anchors

Semantic aliasSourceApproximate locationString or symbolMeaning
LocalJsonlTranscriptSourcecli.jsline ~11, byte 0xd67ctranscriptSource:"local-jsonl"Sessions default to local JSONL transcript storage.
ProjectStateRootcli.jsline ~143, byte 0xf20f0projectsPer-project state helper under the Claude config root.
CurrentSessionJsonlNamecli.jsline ~486, byte 0x30ac6c`${v$()}.jsonl`Current-session JSONL file naming.
SessionDiscoverycli.jsline ~2773, byte 0x79bffeasync function jHHResume/latest-session discovery.
TranscriptRestorecli.jsline ~9514, byte 0xc8b15aasync function OG8Transcript restore into the live envelope.
TranscriptRecordercli.jsline ~8884, byte 0xb8b07arecordTranscriptDurable transcript append/export surface.
FileHistorySnapshotRecordercli.jsline ~8884, byte 0xb8b108recordFileHistorySnapshotFile-history snapshot storage.
ContextCollapseSnapshotRecordercli.jsline ~8884, byte 0xb8b12arecordContextCollapseSnapshotContext-collapse snapshot storage.
SdkSessionStoreAdaptercli.jsline ~7249, byte 0xb3aaa5sessionStoreSDK/external storage adapter hook.
SessionStorePersistenceGuardcli.jsline ~7249, byte 0xb3ac38sessionStore cannot be used with persistSession: falseExternal mirroring depends on local persistence.
RemoteSessionFlagcli.jsline ~19550, byte 0xdcb633`—remote [descriptionsession_id
TeleportSessionFlagcli.jsline ~19550, byte 0xdcb5c1--teleport [session]Teleport resume flag.
RemoteControlFlagcli.jsline ~19550, byte 0xdcb6f2--remote-control [name]Remote Control flag.
RemoteControlAliasFlagcli.jsline ~19550, byte 0xdcb785--rc [name]Remote Control alias.
DisableRemoteControlPolicycli.jsline ~185, byte 0x11a7a3disableRemoteControlManaged policy gate for Remote Control.
BridgeMainEntrypointcli.jsline ~7679, byte 0xb4b41dbridgeMainBridge entrypoint family.
ReplBridgeInitializercli.jsline ~9335, byte 0xc148bcinitReplBridgeRemote Control bridge initializer.
RemoteSessionConfigcli.jsline ~9573, byte 0xcd6d9bremoteSessionConfigRemote session config surface.
SessionAccessTokencli.jsline ~2624, byte 0x6519e7CLAUDE_CODE_SESSION_ACCESS_TOKENSession access token env hook.
WebSocketAuthFdcli.jsline ~2624, byte 0x6516a5CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTORWebSocket auth file-descriptor env hook.
BridgeStateFramecli.jsline ~19356, byte 0xdaf5aabridge_stateRemote bridge state stream frame.
ControlRequestFramecli.jsline ~2004, byte 0x519ca7control_requestHost/SDK control request frame.
PermissionResponseFramecli.jsline ~64, byte 0x39a71permission_responsePermission response/control frame.
ApiRequestLoggercli.jsline ~404, byte 0x2c1a5c[API REQUEST]API request debug logging.
SseTransportHintcli.jsline ~404, byte 0x2c1b55text/event-streamSSE transport hint.
ClientRequestIdHeadercli.jsline ~404, byte 0x2c1dd8x-client-request-idRequest correlation header.
PreToolUseHookcli.jsline ~185, byte 0x10b6b4PreToolUseHook event list begins.
SessionEndHookcli.jsline ~185, byte 0x10b73bSessionEndHook session lifecycle event.
SessionStateFramecli.jsline ~2004, byte 0x518f8csession_state_changedRuntime/session state stream frame.
TranscriptMirrorFramecli.jsline ~2004, byte 0x517c48transcript_mirrorLocal/remote transcript mirror frame.
PromptSuggestionFramecli.jsline ~2004, byte 0x519dafprompt_suggestionPredicted next-prompt frame.

Session design

cli.js uses the session ID as the common address for these layers:

flowchart TD
Flags[CLI flags and env] --> Resolver[Session discovery]
Resolver --> Restore[Session restore]
Restore --> Envelope[Live runtime envelope]
Envelope --> Jsonl[local-jsonl: sessionId.jsonl]
Envelope --> Tools[Tool + permission runtime]
Envelope --> Hooks[Hook event runtime]
Envelope --> Remote[Remote / teleport / Remote Control bridge]
Envelope --> SDK[Headless / SDK stream]
Jsonl --> Resume[future continue/resume/fork/rewind]
LayerEvidenceResponsibility
Session identity`${v$()}.jsonl` and --session-id <uuid>Gives every local and remote projection one stable key.
Durable transcripttranscriptSource:"local-jsonl", recordTranscript, loadTranscriptFromFileStores message/event history as append-only JSONL.
Restore/discoverySessionDiscovery, SessionRestoreTurns --continue/--resume/picker/search into a restored envelope.
Live envelopesession_state_changed, permission/model/agent restore pathsHolds process-time state: model, cwd, permissions, agents, tools, hooks, queues.
External mirroringsessionStore, transcript_mirrorAllows SDK/remote consumers to mirror local writes.
Retention/cleanupcleanupPeriodDaysBounds how long local project/session files remain.

Two important constraints fall out of the source:

  1. sessionStore is not a replacement for local writes. The explicit error says it cannot be used with persistSession: false; mirroring is fed from the local transcript stream.
  2. Remote variants do not bypass the session envelope. They add bridge frames and tokens around the same session model.

Remote control and remote sessions

The visible remote-control features are:

SurfaceSource anchorRole
`—remote [descriptionsession_idurl]`
--teleport [session]line ~19550, byte 0xdcb5c1Resume a teleport session.
--remote-control [name]line ~19550, byte 0xdcb6f2Start an interactive session with Remote Control enabled.
--rc [name]line ~19550, byte 0xdcb785Alias for --remote-control.
disableRemoteControlline ~185, byte 0x11a7a3Managed setting/policy gate.
CLAUDE_CODE_SESSION_ACCESS_TOKENline ~2624, byte 0x6519e7Session token passed through env.
CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTORline ~2624, byte 0x6516a5WebSocket auth handoff through a file descriptor.
initReplBridgeline ~9335, byte 0xc148bcBridge initializer for Remote Control.
remoteSessionConfigline ~9573, byte 0xcd6d9bRemote-session configuration object.

Remote Control is implemented through bridge/control frames. The high-signal frames visible in cli.js are:

Frame/eventDirectionPurpose
bridge_stateruntime → host/SDKAnnounces bridge state changes such as connecting, failed, or ready.
control_requestruntime → hostAsks the host to perform/approve control-plane work.
permission_responsehost → runtimeReturns a tool-permission/control decision.
control_responsehost → runtimeResolves a prior control request.
keep_alivehost/runtimeKeeps the bridge alive; ignored by the message loop once consumed.
update_environment_variableshost → runtimeRemote env update frame; consumed by bridge handling.
bash_commandhost → runtimeInjects a command into the headless bash path and posts the output back as user-visible content.
transcript_mirrorruntime → host/SDKMirrors local transcript records to external consumers.

The bridge path also wires callbacks such as inbound prompt message handling, permission responses, interrupt, model changes, and max-thinking-token changes. That makes Remote Control a control-plane projection over the session, not just screen sharing.

API call surfaces

The bundle contains API paths from several layers. The table below is a source-visible API surface list, not a guarantee that every path is exercised in every local run.

Claude Code runtime/cloud endpoints

CategoryPaths visible in cli.jsNotes
Auth/profile/settings/api/claude_cli_profile, /api/oauth/profile, /api/claude_code/settings, /api/auth/trusted_devices, /api/oauth/account/settingsLocal CLI account/profile/settings flows.
OAuth/API-key bootstrap/v1/oauth/token, /oauth/token, /oauth/authorize, /oauth/code/callback, /api/oauth/claude_cli/create_api_key, /api/oauth/claude_cli/roles, /api/claude_cli/bootstrap, /api/hello, /v1/oauth/helloLogin/bootstrap surfaces.
Sessions and remote environment/v1/code/sessions, /v1/code/sessions/, /v1/environment_providers, /v1/environment_providers/cloud/create, /v1/environments/bridge, /v1/environments/bridge/, /v2/ccr-sessions/, /v1/session_ingress/session/Remote/hosted code-session and bridge family.
Session ingress/MCP ingress/v2/session_ingress/shttp/mcp/, /v2/session_ingress/mcp/ws/, /mcp/start-auth/, /v1/mcp_servers?limit=1000, /v1/toolbox/shttp/mcp/{server_id}, /v1/mcp/{server_id}Remote MCP/session ingress.
Files/uploads/shared transcripts/v1/files, /v1/files?beta=true, /api/oauth/file_upload, /api/oauth/files/, /api/claude_code_shared_session_transcriptsFile upload and shared-transcript support.
Team/project memory/api/claude_code/team_memory?repo=, /api/claude_code/skillsProject/team memory and skill surfaces.
Web/domain helper/api/web/domain_info?domain=Web/domain metadata path used around web features.
Hosted review / triggers/v1/ultrareview/preflight, /v1/code/triggers, /v1/code/triggers/{trigger_id}, /v1/code/triggers/{trigger_id}/runHosted review and code-trigger family.
Metrics/events/traces/logs/api/event_logging/v2/batch, /api/claude_code/metrics, /v1/traces, /v1/logsTelemetry/OTEL/exporter endpoints.
Notifications/api/claude_code/notification/preferencesNotification preference backend.

Embedded Anthropic SDK endpoint declarations

These look like generated SDK/resource declarations inside the bundle. Treat them as SDK surface evidence, not necessarily Claude Code local-session internals.

Resource familyPaths visible
Messages/models/v1/messages, /v1/messages?beta=true, /v1/messages/count_tokens, /v1/models, /v1/models?limit=1000, /v1/models/{id}
Sessions/v1/sessions, /v1/sessions/{session_id}, /v1/sessions/{session_id}/archive, /v1/sessions/{session_id}/events, /v1/sessions/{session_id}/events/stream, /v1/sessions/{session_id}/threads, /v1/sessions/{session_id}/threads/{thread_id}, /v1/sessions/{session_id}/threads/{thread_id}/events, /v1/sessions/{session_id}/threads/{thread_id}/stream, /v1/sessions/{session_id}/resources
Agents/v1/agents, /v1/agents/{agent_id}, /v1/agents/{agent_id}/archive, /v1/agents/{agent_id}/versions
Environments/v1/environments, /v1/environments/{environment_id}, /v1/environments/{environment_id}/archive
Files/v1/files, /v1/files/{file_id}, /v1/files/{file_id}/content
Memory stores/v1/memory_stores, /v1/memory_stores/{memory_store_id}, /v1/memory_stores/{memory_store_id}/memories, /v1/memory_stores/{memory_store_id}/memory_versions
Skills/vaults/v1/skills, /v1/skills/{skill_id}, /v1/skills/{skill_id}/versions, /v1/vaults, /v1/vaults/{vault_id}, /v1/vaults/{vault_id}/credentials

Third-party and integration paths

IntegrationPaths visibleNotes
GitHub/api.github.com, /api.github.com/graphql, /repos/, /api/graphql, /v1/code/github/, /v1/code/github/import-tokenGitHub REST/GraphQL and Claude Code GitHub integration.
Slack/v1/code/slack/Slack code integration surface.
Google/Azure OAuth/oauth2.googleapis.com/token, /oauth2.googleapis.com/revoke, /oauth2/v2.0/token, /oauth2/v2.0/authorizeAuth-provider support.
Hosted MCP directories/mcp.linear.app/mcp, /mcp.notion.com/mcp, /mcp.sentry.dev/mcp, /api.githubcopilot.com/mcp/MCP server/directory references.

Notably, a search for /v1/remote did not find a matching path in the analyzed artifact; the remote/session-ingress paths above are the observed remote families.

Event surfaces

There is no single event bus. The code exposes several event families.

Hook events

The hook event array at line ~185 contains this source-visible list:

FamilyEvents
Tool lifecyclePreToolUse, PostToolUse, PostToolUseFailure, PostToolBatch
Prompt/session lifecycleUserPromptSubmit, UserPromptExpansion, SessionStart, SessionEnd, Stop, StopFailure, Setup
Subagent/task lifecycleSubagentStart, SubagentStop, TaskCreated, TaskCompleted, TeammateIdle
Context/compactionPreCompact, PostCompact, InstructionsLoaded
Permission/elicitationPermissionRequest, PermissionDenied, Elicitation, ElicitationResult
Config/worktree/fileConfigChange, WorktreeCreate, WorktreeRemove, CwdChanged, FileChanged
Misc notificationNotification

Stream/headless/SDK frames

FrameMeaning
session_state_changedSession state changed, e.g. idle/running/requires-action surfaces.
transcript_mirrorTranscript line mirrored to host/SDK/remote consumer.
bridge_stateRemote bridge state update.
control_request / control_responseHost/runtime control-plane request/response pair.
permission_deniedTool call was denied without an interactive approval path.
task_startedTask registered in the runtime task state.
task_updatedPatch-style task update emitted after task state mutation.
task_progressProgress notification for task-like work.
task_notificationLong-running monitor stdout line delivered to the model.
prompt_suggestionPredicted next prompt emitted when suggestions are enabled.
rate_limit_eventRate-limit state surfaced to clients.
relevant_memoriesMemory recall supervisor surfaced memories for a turn.
elicitation_completeMCP URL-mode elicitation completed.

MCP request/notification methods

These are protocol methods rather than Claude Code hook names, but they are visible in the same artifact:

Method familyExamples
Toolstools/list, tools/call
Resourcesresources/list, resources/read, resources/templates/list
Promptsprompts/list, prompts/get
Tasks/cancel/progresstasks/list, tasks/cancel, notifications/cancelled, progress notification handlers

Telemetry events

Telemetry strings mostly use the tengu_* prefix, for example scheduled-task, auto-mode, updater, worktree, and bridge events. The exact sink schema is not stable, so this wiki treats them as operational signal names rather than public API.

Internal storage

Storage areaEvidenceWhat is stored
Project/session transcriptsprojects, `${sessionId}.jsonl`, recordTranscriptAppend-only JSONL transcript and session records.
Session metadata/indexlistSessions, getSessionInfo, recordSessionAlias, restoreSessionMetadataSummary/title/cwd/git branch/tag/session alias data used by resume/picker.
File history/checkpointsrecordFileHistorySnapshot, persistLeafCheckpoint, --rewind-filesSnapshots used for rewind/checkpoint restore.
Context-collapse datarecordContextCollapseSnapshot, recordContextCollapseCommit, recordContentReplacementCompaction/collapse metadata and replacement records.
Sidechain/subagent transcriptsrecordSidechainTranscript, loadSubagentTranscripts, loadAllSubagentTranscriptsFromDiskSubagent/sidechain history separate from the main transcript view.
Remote metadatareadRemoteAgentMetadata, listRemoteAgentMetadata, saveBridgeSessionRemote/bridge/agent metadata linked to a local session.
Permission/model/agent statesavePermissionMode, saveMode, saveAgentSetting, saveAgentName, saveAgentColorEnvelope fields restored alongside transcript history.
QueuesrecordQueueOperation, task message queue handlingPending task/control messages for SDK/task flows.
SDK external mirrorsessionStore, sessionStoreFlush, transcript_mirrorOptional external storage adapter fed by local persistence.
Scheduled tasks.claude/scheduled_tasks.lock, durable scheduled-task prompt mentions .claude/scheduled_tasks.jsonSession/durable scheduled prompt state and scheduler lock.
Debug/ops logsCLAUDE_CODE_DEBUG_LOGS_DIR, debug latest symlinkSupport/debug log files outside the transcript.

The main design pattern is append and replay. Runtime code appends transcript/internal records; resume restores by scanning those records into a live envelope; remote/SDK consumers can mirror the same stream.

Mental model

flowchart LR
Jsonl[Local JSONL transcript] --> Restore[Replay / restore]
Restore --> Envelope[Live session envelope]
Envelope --> Events[Hook + stream + bridge events]
Events --> Jsonl
Events --> SDK[SDK/headless host]
Events --> Remote[Remote Control / teleport]
Envelope --> Storage[metadata, snapshots, queues]
Storage --> Restore

The important implementation takeaway: session, API, event, and storage logic are intentionally coupled by the session ID. A local session can become a remote-controlled session because the bridge adds control frames around the same envelope rather than translating it into a different object model.

Caveats

  • cli.js is bundled/minified. Exact anchors behind SessionDiscovery and SessionRestore are version-specific search handles, not stable API names.
  • The API list includes embedded SDK declarations and integration constants. It is a source-visible endpoint inventory, not a network trace.
  • Event names span hooks, stream frames, bridge control frames, MCP methods, and telemetry. Consumers should not assume one subscription mechanism receives all of them.
  • Remote/session ingress paths are documented from static strings. A live run may choose different paths depending on account, policy, feature gates, and environment.

Created and maintained by Yingting Huang.