Skip to content

Session API, events, and storage

This page reverse-engineers a question-oriented slice of cli.renamed.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 local session is designed as a durable local JSONL transcript plus a live runtime envelope addressed by one local UUID. Hosted sessions and Remote Control bridge sessions add distinct service-side IDs.
  • Remote control does exist, but the entrypoints are not aliases for one implementation. --cloud (deprecated alias --remote) owns a hosted loop, --teleport imports hosted history into a local loop, and --remote-control / --rc expose a running local loop through a resumable hosted bridge.
  • API calls are not one neat table in source. cli.renamed.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: ordered per-session JSONL, per-project metadata, file-history/context-collapse/checkpoint records, task/session queues, optional downstream SDK sessionStore mirroring, scheduled-task files/locks, debug logs, and caches.

Source anchors

Semantic aliasString or symbolMeaning
LocalJsonlTranscriptSourcetranscriptSource:"local-jsonl"Sessions default to local JSONL transcript storage.
ProjectStateRootprojectsPer-project state helper under the Claude config root.
CurrentSessionJsonlName`${v$()}.jsonl`Current-session JSONL file naming.
SessionDiscoveryasync function loadConversationForResumeResume/latest-session discovery and transcript normalization.
TranscriptRestoreasync function f7oApplies discovered state to the current live envelope.
TranscriptRecorderrecordTranscriptDurable transcript append/export surface.
OrderedTranscriptStoreclass ROd, drainQueuesOncePer-file queued/batched local append.
TranscriptShutdownFlushflushSessionStorageAtExitDrains transcript and auxiliary queues during coordinated shutdown.
MetadataCheckpointbytesSinceMetadataReAppend, LITE_READ_BUF_SIZE / 2Periodically re-appends cached metadata after approximately 32 KiB of successful current-session writes.
TranscriptRelocationrelocateSessionTranscript, cOdBuffers both in-process writer families while moving transcript and associated state.
CcrHydrationAndBackfillhydrateFromCCRv2InternalEvents, .ccr-tip.json, EpfReconciles server internal events into local JSONL and starts backfilling missing local suffix entries.
FileHistorySnapshotRecorderrecordFileHistorySnapshotFile-history snapshot storage.
ContextCollapseSnapshotRecorderrecordContextCollapseSnapshotContext-collapse snapshot storage.
SdkSessionStoreAdaptersessionStoreSDK/external storage adapter hook.
SessionStorePersistenceGuardsessionStore cannot be used with persistSession: falseExternal mirroring depends on local persistence.
CloudSessionFlag--cloud [description|session_id|url]Hosted session creation/attach flag.
RemoteSessionAlias--remote [description|session_id|url]Deprecated alias for --cloud.
TeleportSessionFlag--teleport [session]Teleport resume flag.
RemoteControlFlag--remote-control [name]Remote Control flag.
RemoteControlAliasFlag--rc [name]Remote Control alias.
DisableRemoteControlPolicydisableRemoteControlManaged policy gate for Remote Control.
BridgeMainEntrypointbridgeMainBridge entrypoint family.
ReplBridgeInitializerinitReplBridgeRemote Control bridge initializer.
RemoteSessionConfigremoteSessionConfigRemote session config surface.
SessionAccessTokenCLAUDE_CODE_SESSION_ACCESS_TOKENSession access token env hook.
WebSocketAuthFdCLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTORWebSocket auth file-descriptor env hook.
BridgeStateFramebridge_stateRemote bridge state stream frame.
ControlRequestFramecontrol_requestHost/SDK control request frame.
PermissionResponseFramepermission_responsePermission response/control frame.
ApiRequestLogger[API REQUEST]API request debug logging.
SseTransportHinttext/event-streamSSE transport hint.
ClientRequestIdHeaderx-client-request-idRequest correlation header.
PreToolUseHookPreToolUseHook event list begins.
SessionEndHookSessionEndHook session lifecycle event.
SessionStateFramesession_state_changedRuntime/session state stream frame.
TranscriptMirrorFrametranscript_mirrorSuccessful local transcript append mirrored to an SDK host.
TranscriptRetentionSweepasync function kIp()mtime-based local retention cleanup controlled by cleanupPeriodDays.
RetentionHousekeepingstartBackgroundHousekeeping, .last-cleanupStarts process-local transcript heartbeats and schedules deferred cleanup work.
RemoteControlSsefrom_sequence_num, seenSequenceNums, H6uRemote Control numeric receipt cursor, heuristic numeric-ID tracking, and separate fixed-capacity envelope-UUID filtering.
HostedRemoteSseSessionsV2Client, catch_up_truncatedSeparate hosted --cloud sequence/reconnect client.
PromptSuggestionFrameprompt_suggestionPredicted next-prompt frame.
MessageDisplayHookMessageDisplayDisplay-only assistant-stream transformation; stored/model-visible content is unchanged.

Bundle module in cli.renamed.js

Semantic aliasLoader lineRepresentative renamed exportsAtlas entry
SessionRuntimeStateHub3398, 118553switchSession, setUserMsgOptIn, waitForScrollIdle, setSessionOverridesGetter, regenerateSessionId, getParentSessionId, setTracerProvider, setTeleportedSessionInfo, snapshotOutputTokensForTurn, setThinkingTypeOverride, setTerminalFocusForState, setTeamMemoryServerStatus, setSystemPromptSectionCacheEntryBundle module map — session, transcript, agent metadata, and teammate IPC

Session design

cli.renamed.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 --> RemoteControl[Remote Control bridge]
Hosted[Hosted --cloud session] --> Teleport[Teleport import]
Teleport --> Restore
Envelope --> SDK[Headless / SDK stream]
Jsonl --> Resume[future continue/resume/fork/rewind]
LayerEvidenceResponsibility
Session identity`${v$()}.jsonl` and --session-id <uuid>Gives the local transcript/envelope a stable UUID; hosted and bridge objects retain separate IDs.
Durable transcripttranscriptSource:"local-jsonl", recordTranscript, loadTranscriptFromFileStores message/event history as queued, append-oriented ordered JSONL; UUID removal can rewrite it.
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 an SDK host to mirror records only after local append succeeds.
Retention/cleanupcleanupPeriodDays, kIpActively sweeps stale transcripts, recordings, sidecars, and associated session state.

This is a reference view, so it records three boundaries without duplicating their algorithms:

  1. sessionStore supplements rather than replaces local persistence; the SDK rejects it with persistSession:false.
  2. SDK transcript_mirror follows a successful local append, while CCR internal-event upload is a separate queue/acknowledgement path.
  3. Remote Control wraps a local envelope; hosted --cloud, teleport, Direct Connect, and the Chrome bridge remain distinct protocols.

For write ordering, metadata checkpoints, removal, relocation, and hydration, use Session resume and transcripts. For transport retry/cursor behavior, use Remote control and teleport.

Remote control and remote sessions

The visible remote-control features are:

SurfaceSource anchorRole
`—cloud [descriptionsession_idurl]`
`—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.renamed.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 callback family confirms that Remote Control is a bidirectional control-plane projection, not screen sharing. This reference intentionally stops at frame/endpoint discovery; bridge identity, numeric receipt cursors, UUID filtering, reconnect, hosted --cloud, and teleport behavior are canonical in Remote control and teleport. The durable bridge-session shape is canonical in Data models and frame schemas.

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.renamed.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
Display/notificationMessageDisplay, Notification

Stream/headless/SDK frames

FrameMeaning
session_state_changedSession state changed, e.g. idle/running/requires-action surfaces.
transcript_mirrorTranscript entries mirrored to a registered SDK/host listener after local append.
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.

Assistant transcript records in this build also carry the reasoning effort level used for that message. OpenTelemetry correlation fields (message.uuid, client_request_id) and tool provenance (tool_source) let external consumers tie the durable message to request/tool events without treating telemetry as the transcript itself.

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-oriented JSONL transcript and session records, with queued UUID-removal rewrites.
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.
CCR hydration anchor.ccr-tip.json, getValidatedCCRTip, updateCCRTipFromAckedBatchBest-effort foreground internal-event anchor validated against UUIDs in the last 64 KiB of local JSONL.
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 table above is the canonical storage-area inventory. Lifecycle mechanics are intentionally delegated:

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 --> RemoteControl[Remote Control]
Hosted[Hosted --cloud] --> Teleport[Teleport import]
Teleport --> Restore
Envelope --> Storage[metadata, snapshots, queues]
Storage --> Restore

The important implementation takeaway: local session, event, and storage logic are coupled by the local UUID, while remote services add explicit foreign identities and replay cursors. A local session can become remote-controlled because a bridge is linked to the envelope; a hosted --cloud session is not thereby the same object.

Caveats

  • cli.renamed.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.
  • Client code establishes local ordering, retry budgets, cursor persistence, and archive requests. It does not establish server-side retention, exactly-once delivery, archive erasure, or cross-version replay guarantees.
  • In-process append chains are not cross-process locking. Concurrent processes targeting one JSONL file have no source-visible global ordering guarantee.

Created and maintained by Yingting Huang.