This document describes operator-visible behavior for session export, sharing, conversation reset, lifecycle, fork, and resume operations as currently implemented.
src/slash-commands/builtin-collaboration.ts— export/dump/share command specssrc/slash-commands/builtin-lifecycle.ts— lifecycle command specssrc/modes/controllers/command-controller.ts— TUI executionsrc/modes/controllers/selector-controller.ts— resume/import picker and cwd transitionsrc/session/agent-session.tssrc/session/session-manager.tssrc/export/html/index.tssrc/export/share.tssrc/export/custom-share.tssrc/cli/flag-tables.ts— restart argument rewritingsrc/main.ts
| Operation | Entry path | Session mutation | Session file creation/switch | Output artifact |
|---|---|---|---|---|
/dump [all] |
Slash command (TUI/headless) | No | No | Clipboard/command text plus best-effort temporary JSON sidecar; all: temp zip |
/export [--themes] [path] |
Slash command (TUI/headless) | No | No | HTML file |
--export <session.jsonl> [outputPath] |
CLI startup fast-path | No runtime session mutation | No active session; reads target file | HTML file |
/share |
Slash command (TUI/headless) | No | No | Encrypted share link (gist or share server); temp HTML only for TUI custom handlers |
/new |
Interactive slash command | Yes (starts an empty conversation) | Switches identity and materializes a new header in persistent mode | None |
/fresh |
Slash command (TUI/headless) | Yes (provider-facing in-memory id/state only) | No; keeps current session file/header | None |
/clear |
Interactive slash command | Yes (clears live/model conversation context) | Retains identity/file/history; a lazy session still follows the normal persistence gate | Appends reset_boundary |
/delete |
Interactive slash command | Yes (starts an empty conversation) | Attempts to delete the current persisted session and artifacts, then switches to a lazy successor (no empty file until content) | None |
/fork |
Interactive slash command | Yes (active session identity changes) | Creates new session file and switches current session to it (persistent mode only) | Copies artifact directory to new session namespace when present |
/fork pane, /fork window, /fork tab |
Interactive slash command | No (parent session retained) | Opens a child OMP process from the flushed current transcript in a multiplexer pane/group (tmux window, Zellij/Herdr/Orca tab, or CMUX workspace) | Child receives a separate forked session |
--fork <id|path> |
CLI startup | Yes after session creation | Creates a new session fork from the selected source into current cwd/session dir | Copies source artifacts recursively by default |
/resume [id|@claude|@codex] |
Interactive slash command | Yes (active in-memory state replaced) | Switches to a selected/matched session, or imports a selected foreign session | None |
--resume |
CLI startup picker | Yes after session creation | Opens selected existing session file (picker opens in current-folder scope; the global list is preloaded only for the empty-everything early exit and instant Tab switching) | None |
--resume <id|path> |
CLI startup | Yes after session creation | Opens existing session; a missing recorded cwd may be re-rooted into the current directory | None |
/restart |
Interactive slash command | Yes (process relaunches) | Keeps configuration flags; restores a materialized session (--restore), otherwise starts fresh |
None |
--continue |
CLI startup | Yes after session creation | Opens terminal breadcrumb or most-recent session; creates new one if none exists | None |
Flow:
- The collaboration command spec (
src/slash-commands/builtin-collaboration.ts) parses headless arguments withparseExportArgs; the TUI delegates toCommandController.handleExportCommand, which uses the same parser. --themesselects the configured dark/light TUI themes instead of the standalone web palette. After removing that flag, at most one whitespace-delimited path is accepted; extra tokens produceUsage: /export [--themes] [path].AgentSession.exportToHtml()callsexportSessionToHtml(sessionManager, state, { outputPath, palette, themeNames }).- The TUI shows the path and opens the file in a browser. Headless command execution prints the path without opening it.
In the TUI, /export targets viewSession: a focused subagent exports its own
transcript and descendants, not the main session. /dump and /share still
target the main session.
Behavior details:
--copy,clipboard, andcopyarguments are explicitly rejected with a warning to use/dump.- Export embeds session header/entries/leaf plus current
systemPromptand tool descriptions from agent state.previousSessionFilesis omitted from exported headers. - The viewer uses the
/statsdesign, with Auto/Light/Dark themes; Light uses soft-gray surfaces and high-contrast secondary text. The sidebar lists the main session, nested subagents, and advisors; selecting a session or a task-card agent opens its transcript and conversation tree. Session and message links preserve the selected transcript. - Child transcripts stored next to the session file (
<session>/<AgentId>.jsonl, recursively for nested spawns) are embedded assubSessions, including advisor and gzip-compressed transcripts. Discovery descends only into real child directories and flags tombstoned agents asaborted.includeSubSessions: falseinExportOptionsexcludes child transcripts and their trace tracks. - The bottom Timeline drawer and Trace view reuse
/trace's span assembly and viewer: duration/turn/call axes, idle compression, search, zoom, nested tracks, entry details, and tool aggregates. Jump to transcript opens the corresponding session and message. All transcript and trace data remain embedded; no stats server is needed. Both development and release exports load shared libraries fromstencil.so, so opening the HTML requires network access. - Tool calls use
<omp-tool-view>(shared with collab-web); traces use<omp-session-trace>(shared with stats).bun gen:export-viewerbundles these with the shell, styles and default themes. A source checkout inlines the generated viewer into each export; packaged releases load their versioned viewer frombuild.stencil.so. Both load shared Markdown and highlighting libraries from content-addressedstencil.so/assets/omp/URLs, pinned with Subresource Integrity. Only viewer code is uploaded, never session data. - Packaged exports add roughly 2 KiB of fixed HTML overhead; source exports also contain the generated viewer.
--themesembeds the selected TUI theme overrides in addition to the session data. - No session entries are appended during export.
- The default filename is
omp-session-<session-file-stem>.htmlin the current directory. HTML export is not secret-redacted or encrypted; it can contain raw context, image data, and extension payloads.
Caveat:
- Parsing is whitespace-based, so quoted paths with spaces are not preserved. Use a path without spaces.
- A source checkout needs
bun gen:export-viewerbefore exporting. A missing generated viewer reports the command to run; packaged viewer assets become available when release CI publishes them.
Flow in main.ts:
- Handled early (before interactive/session startup).
- Calls
exportFromFile(inputPath, outputPath?). SessionManager.open(inputPath, ..., { suppressBreadcrumb: true, throwIfMissing: true })loads entries, then HTML is generated and written.- Process prints
Exported to: ...and exits.
Behavior details:
- Missing input file surfaces as
File not found: <path>; empty/malformed-header files fail without creating or replacing the input. - This path does not create an
AgentSession, update terminal breadcrumbs, or mutate any running session. - Standalone export has no live agent state, so it does not add current system-prompt/tool descriptions. It embeds the loaded entries and subagent transcripts.
Flow:
- The command calls
session.formatSessionAsText(). - If it returns an empty string, the command reports
No messages to dump yet. - Otherwise it also attempts
session.dumpLlmRequestToTmpDir()and appends the resulting path to the transcript. The TUI copies the combined text to the clipboard; headless/ACP command execution returns it as command output.
Dump uses the live agent message array, not every branch or every historical
JSONL entry. After /clear or compaction it reflects the current live context;
use HTML export for the persisted conversation graph.
Dump transcript content includes:
- System prompt
- Active model/thinking level
- Tool definitions + parameters
- User/developer/assistant messages
- Thinking blocks and tool calls
- Tool results and execution blocks (except
excludeFromContextbash/python entries) - Custom/hook/file mention/branch summary/compaction summary entries
The best-effort JSON sidecar is named omp-llm-request-<id>.json under the OS temporary directory. It contains the current model, thinking level, service tier, system prompt, wire tool schemas, and LLM-converted messages. It persists after the command and can contain raw context or secrets; protect or remove it accordingly. A sidecar failure does not suppress the transcript (the TUI reports the failure; headless execution silently omits the path).
No session persistence entries are appended by dumping.
/dump all calls session.dumpSessionArchiveToTmpDir(), which writes
omp-dump-<id>.zip under the OS temporary directory with:
session.md— the same main transcript/dumpcopiesllm-request.json— the same payload as the/dumpsidecar (best-effort; omitted if conversion fails)subagents/<path>.md— one file per persisted subagent found bycollectSubSessions(e.g.subagents/Scout.md,subagents/Scout/Helper.md), headed# Subagent: <path>with the persisted model, thinking level,Status: abortedfor killed agents, and the messages on the subagent's last-entry branch, deobfuscated like the main session
Subagent system prompts and tool inventories are not persisted, so subagent files omit them. Subagents with no messages are skipped. If subagent discovery fails, the archive still holds the main dump and the report says why subagents are missing. The TUI copies the archive path to the clipboard and lists its members; headless/ACP returns the same report as command output. Like the sidecar, the archive persists and can contain raw context or secrets.
/share publishes an end-to-end encrypted snapshot of the session and prints
a viewer link. Implementation: ../packages/coding-agent/src/export/share.ts.
The interactive TUI's loadCustomShare() checks the active agent directory
(default ~/.omp/agent) for the first existing candidate:
share.tsshare.jsshare.mjs
Requirements:
- Module must default-export a function
(htmlPath) => Promise<CustomShareResult | string | undefined>.
If present and valid, the legacy contract is preserved: the session is
exported to a temp HTML file (${os.tmpdir()}/${Snowflake.next()}.html),
the handler receives its path, and the temp file is removed afterwards.
Handler result interpretation:
- string => treated as URL, shown and opened
- object =>
urland/ormessageshown;urlopened undefined/falsy => genericSession shared
Critical fallback behavior:
- If custom handler exists but loading fails, command errors and returns.
- If custom handler executes and throws, command errors and returns.
- In both failure cases, it does not fall back to the default flow.
- The default flow runs only when no custom share script exists.
- Headless/ACP slash-command execution does not load custom share scripts; it always uses the default encrypted flow.
Custom handlers receive ordinary HTML export, not the default redacted/encrypted snapshot. Their publishing, encryption, and privacy policy are entirely their own. The HTML-export contract also means a custom handler cannot share an in-memory session through this path.
For headless execution, or in the TUI only when no custom share handler is found, shareSession():
- Builds the main-session snapshot (
header,entries,leafId, plus currentsystemPromptand tool descriptions from agent state), omitting headerpreviousSessionFiles. Unlike HTML export, this flow does not collect subagent transcript files. - If
share.redactSecretsis enabled (default) and the obfuscator has configured or regex-discovered secrets, a typed per-field redaction pass rewrites text-bearing header, prompt, tool, entry, sub-session, and message fields. Inline image bytes remain for the later size pass. Opaque provider replay fields and untyped extension payloads (details,data,outputSchema, compaction preserve data) are dropped rather than traversed. - The JSON is gzipped and sealed with a fresh AES-256-GCM key
(
[12B IV][ciphertext+tag]). - Upload target is chosen by
share.store:- Share server (default,
store: "blob") —POST <share.serverUrl>(defaulthttps://my.omp.sh/s) with the raw blob, capped at 1 MB. Oversized snapshots are trimmed until they fit: inline images first, then long strings (32,768 → 8,192 → 2,048 → 512 character caps), then oldest entries. If the reduced snapshot still exceeds the budget, sharing fails rather than uploading an oversized blob. - Secret gist (
store: "gist") — whenghis installed and authenticated, the sealed blob is pushed base64-encoded assession.ompshare.txt(budget 5 MB sealed; gist raw fetches cap at 10 MB), falling back to the share server whenghis unusable or gist creation fails.
- Share server (default,
- The link is
<share.serverUrl>/<id>#<base64url key>in both cases. The viewer page served there fetches the blob (hex ids via the GitHub gist API, anything else from the server's blob store) and decrypts it client-side; the key lives only in the URL fragment and never appears in any HTTP request.
The UI reports the share URL (plus the underlying gist URL and a truncation
note when applicable). Headless /share prints the same lines. Unlike
/export, /share works for in-memory (--no-session) sessions: the
snapshot is built from live entries, no session file required.
Cancellation/abort semantics in share:
- Loader has
onAborthook that restores editor UI and reportsShare cancelled. - The upload itself is not aborted mid-flight; cancellation is UI-level and checked after the upload returns.
Interactive /new starts a new conversation identity. The TUI first aborts any
active compaction; AgentSession.newSession() emits the cancellable
session_before_switch event, aborts the old run, cancels owned async jobs,
closes provider state, and drains outgoing writes/advisor recorders. Persistent
SessionManager.newSession() writes the new header before returning, even
before the first assistant response.
The new session keeps the current model/settings and configured thinking selector, but clears conversation/queues, todo/checkpoint/tool state, inherited cache identity, advisor spend, and promoted memory context. Workspace roots are seeded from current settings, and project instructions are refreshed from disk. The TUI leaves a focused subagent view and clears its transcript.
/delete uses the same transition with drop: true. It requires a session-file
path, attempts to delete the old JSONL and artifact tree instead of retaining
them, and still starts a new session if deletion fails. Unlike /new, that
successor is lazy: no header is written until it has content, so quitting
without a message leaves no zero-turn session behind. A before-switch hook can
cancel either operation. Both are rejected while vibe mode is active.
/fresh (TUI/headless) resets the provider-facing stream state of the current
session without touching the local transcript, session file, or header. Use
it to recover from a wedged or corrupted provider stream (stale prompt cache,
a mid-turn glitch, or a server-side conversation id that has drifted) while
keeping the conversation you can see.
AgentSession.freshSession():
- Is rejected while the agent is streaming — wait for the response to finish or abort it first.
- Closes every cached provider-session state entry (server-side conversation / prompt-cache handles) and reports how many were pruned.
- Mints a fresh provider session id, re-keys memory state, and invalidates the append-only context so the next turn rebuilds from the local conversation.
- Leaves the local transcript, session file, and OMP session-manager identity
unchanged; the provider-facing
AgentSession.sessionIdchanges.
Because it keeps both the visible and model-facing conversation, /fresh
differs from /clear (clear the live/model conversation in place), /new
(start a brand-new empty session), and /delete (attempt to delete the current
session and start a new one). Only /fresh preserves the existing conversation
while giving the provider stream state a clean slate.
Interactive /clear clears the current conversation context in place. It is
available only in the TUI and is rejected while a response is streaming or a
foreground bash/Python execution is running. If compaction is active, the
command aborts it and waits for it to stop before resetting.
AgentSession.resetSessionContext():
- Drops live messages, queued steer/follow-up turns, pending tool calls, error state, checkpoint/rewind and deferred tool state, and session-stop continuation state. It also cancels this agent's queued continuation work and async bash/task jobs.
- Rotates provider-side session state, re-primes advisors, invalidates append-only model context, and resets memory promotion so the next turn rebuilds from the base system prompt and current project instructions.
- Retains the session id, title, cwd, model, settings, active plan path, and transcript file.
- Appends
reset_boundarythrough the normal persistence pipeline. For an already materialized session it is durable; an in-memory or still-lazy session retains the marker in memory. The collapsed live transcript and rebuilt model context begin after the latest boundary, while persisted JSONL and full-transcript export retain the pre-reset history. - After the reset and system-prompt refresh succeed, awaits the
session_clearnotification to hooks/extensions so they can invalidate context-dependent caches. Empty successful clears also notify; busy/rejected resets do not. This does not emitsession_switchor allow handlers to cancel the clear.
The TUI clears its rendered transcript after a successful clear. This differs
from /fresh, which rotates provider stream state without clearing the
conversation; /new, which creates a new session identity and transcript file;
and /delete, which attempts to delete the old persisted session before starting
a new one.
/btw history is stored alongside session artifacts and remains outside the main
conversation. See the BTW command reference
for keyboard controls, follow-ups, persistence, and migration safety.
Bare /fork creates a new session from the current one and switches the active
session identity. /fork pane opens a separate OMP process in a new pane;
/fork window and /fork tab open it in a new multiplexer group (a tmux
window, Zellij/Herdr/Orca tab, or CMUX workspace). The child starts from the current
persisted transcript, while the parent session stays active and continues
running.
Typing /fork shows [pane|window|tab] as dim inline text, and Enter still
runs the bare in-place fork. Typing a prefix (/fork w) opens the suggestions
with the rest of the selected argument as dim inline text; Tab accepts it.
Placement commands autodetect tmux, Zellij, Herdr, CMUX, or Orca from the terminal;
/fork auto is not a subcommand (valid arguments are pane, window, and
tab). window maps to a tmux window, a Zellij/Herdr/Orca tab, or a CMUX workspace.
Plain terminals, screen, and wmux cannot host this fork placement and receive
an explicit error; use bare /fork there instead.
- Bare
/forkis rejected with a warning while the agent is streaming. - A placement fork during streaming asks before launching. The child can omit the partial response, and confirming does not stop the parent response.
- Forking is rejected while vibe mode is active.
- Placement forks require an already persisted session transcript; pending writes are flushed before the child launches. The parent never switches sessions.
- A CLI
--api-keyoverride cannot be safely passed through a multiplexer command; placement forks refuse it rather than exposing the key. - UI status/loading indicators are cleared only for the original bare
/forkflow.
For a placement command, the controller rebuilds the child CLI command from the
current CLI entry point and restart-safe launch flags (one-shot selectors such
as --goal and positional prompts are dropped). It replaces stale startup
model, thinking, profile, prompt-cache-key, and working-directory flags with the
active session values; the child is pinned to the parent's prompt-cache key so
it reads the cache the parent populated. The child also receives the effective
agent/config directories, the resolved config overlays (which retain their
original paths after /move), and the parent's session-dir and XDG base
directories; scope variables the parent does not set are unset rather than
exported empty. It starts with --fork and the absolute path of the current transcript. The
generic terminal launcher handles provider-specific execution and reports
capability or launch failures in the TUI. CMUX and Orca launches require
explicit confirmation that the destination's configured interactive shell
accepts POSIX syntax; this is never inferred from the local OS or SHELL.
Declining confirmation stops before the session is flushed or a terminal is
launched. window and tab both map to the multiplexer group placement. The Orca
CLI is resolved in Orca's documented order (ORCA_CLI_COMMAND, then orca-dev in an
Orca development checkout, then orca-ide on Linux outside an Orca terminal, then
orca).
Orca's CLI --command accepts shell text, not argv, and has no --cwd; after
confirmation, OMP supplies cd <quoted-cwd> && <quoted-command> using shared
POSIX shell quoting. When Orca cannot show the new tab and starts the child in a
background terminal instead, /fork reports that as a warning rather than a
visible tab.
The original bare /fork uses AgentSession.fork():
- Emits
session_before_switchwithreason: "fork"(cancellable). - Flushes pending bash/session writes and drains/detaches advisor recorders.
- Calls
SessionManager.fork(), preserving the conversation and its usage attribution. - Copies artifacts directory from old session namespace to new namespace (best-effort; non-ENOENT copy failures are logged, not fatal).
- Updates
agent.sessionIdand inherits the previous provider prompt-cache key unless an explicit prompt-cache key is already pinned. - Emits
session_switchwithreason: "fork".
SessionManager.fork() behavior:
- Requires persistent mode and an assigned session-file path; the source need not already be materialized on disk.
- Creates new session id and new JSONL file path.
- Rewrites header with:
- new
id - new timestamp
cwdunchangedparentSessionset to previous session idproviderPromptCacheKeyset to the previous header's inherited key, or the previous session id when none was pinned
- new
- Keeps all non-header entries unchanged in the new file.
- In-memory session manager returns
undefinedfromfork(). AgentSession.fork()returnsfalse.- UI reports
Fork failed (session not persisted or cancelled).
AgentSession.fork(entryId) forks from a transcript point instead of the whole session. The RPC fork command calls it when entryId is given and plain fork() otherwise.
- Like the whole-session fork, it is rejected while vibe mode is active.
entryIdmust be amessageentry (user, assistant, or any other message role); anything else throwsInvalid entry ID for forking.- It throws
SessionBusyErrorwhileAgentSession.isBusyForSnapshotis true (a response is streaming, or user bash/eval, compaction, handoff, or retry work is running). The check runs beforesession_before_branch, again after it, and once more after pending bash output and session writes flush. That last check comes before anything of the old session is discarded (pending next-turn messages, async jobs, the auto-learn capture), so a refused fork leaves the session as it was. A prompt admitted during the remaining drain awaits is dropped by the prompt-generation bump at the cut, as forbranch()./btwbranches use the same predicate. - When
entryIdsits inside an assistant tool-call batch (the assistant message, or a tool result answering it), the cut extends through the batch's recorded tool results, following the tree fromentryIdand stepping over lone non-message entries between results. A fork therefore never ends on tool calls whose results exist in the source session; calls that never got a result stay as they are. - The transition is the one
AgentSession.branch()uses, cut at the resolved entry rather than before it:session_before_branchwith reason"fork"(cancellable;entryIdis the last kept entry, not a dropped one as forbranch()),SessionManager.createBranchedSession(leafId, { copyArtifacts: true }), rebuilt agent messages, thensession_branchwith reason"fork". - The new file keeps the root-to-entry path including the resolved entry, carries labels for kept entries, keeps the title, and sets
parentSessionto the previous session file. The whole artifact directory is copied in the background (including artifacts only cited by dropped entries), and the new session's artifact manager waits for the copy before allocating ids or resolvingartifact://, so keptartifact://Nreferences still resolve and new artifacts get fresh ids. Unlike the whole-session fork, the provider prompt-cache key is not inherited (same asbranch()). - Works in non-persistent mode (in-memory replacement), unlike the whole-session fork.
AgentSession.fork(undefined, { requireIdle: true })applies the same idle rule to the whole-session fork (beforesession_before_switchand again after the flushes). RPCforkpasses it for both variants, so both reject withcode: "session_busy". Interactive/forkdoes not, so it can still carry a running bash command into the new session.
Startup --fork is resolved before normal session creation:
--forkis rejected with--no-session.- Path-like values (
/,\, or.jsonl) fork directly from the given path. - Other values resolve via
resolveResumableSession(...): local sessions first, then global search whensessionDiris not forced. Matching accepts lowercased session id prefixes, full JSONL filename prefixes, and timestamp-stripped filename id suffixes. - The forked file is created in the current cwd/session-dir scope and becomes the active session manager for startup. Source artifacts are copied recursively by default. Missing source files fail instead of producing an empty fork. An unresolved tool call on the copied active branch is paired with an outcome-unknown result in the child, rather than being marked never executed. For a length stop, the never-executed guard is retained only when no execution-start marker exists. A source whose process exit was recorded after its last message is not repaired here: the child warns about the pending calls and pairs them through the normal process-exit recovery. The parent transcript is unchanged.
- Full-context forks automatically seed
providerPromptCacheKeyfrom the source header's inherited key, falling back to the source session id. Startup drops that automatic inheritance for explicit--model,--thinking,--system-prompt,--system-prompt-template,--append-system-prompt,--tools, or--no-toolsoverrides, or an applicable scoped-model override.
Use --prompt-cache-key <key> to pin the provider prompt-cache identity explicitly and independently from both the OMP session id and --provider-session-id. --provider-session-id continues to control provider session/routing headers and sticky credential selection; --prompt-cache-key controls the OpenAI Responses prompt_cache_key payload where supported.
Without an argument:
- Opens the session selector populated via
SessionManager.listForPicker(currentCwd, currentSessionDir). Pinned sessions come first; untitled, prompt-less zero-turn stubs are hidden unless pinned. The picker always opens in current-folder scope; the empty state invites Tab into all-projects instead of auto-switching. - Tab toggles to all-projects scope, lazily loading and caching
SessionManager.listAllForPicker(). - On selection,
SelectorController.handleResumeSession(sessionPath, { followContinuation: true })first followsfindSessionContinuationto the copy with the newest turn (see CLI--resume <value>), then callssession.switchSession(<that path>). If the switch is rejected, it returnsfalseand the selector stops without applying the new-session UI state. - After a successful switch, UI clears/rebuilds chat and todos, then reports
Resumed session(orResumed session in <dir>when the resumed session belongs to another project, in which case the process cwd and cwd-derived caches are re-pointed viaapplyCwdChange).
With an argument:
/resume <id>resolves an id/filename prefix with local-first, then global fallback, and opens the copyresolveResumeTargetpicks, the same one the CLI's--resume <id>opens (see CLI--resume <value>); an unknown value reportsSession "<value>" not found./resume @claudeand/resume @codexopen a foreign-session picker. Selecting one converts and persists it under a fresh OMP session identity, then switches to that new session.
main.tsusesSessionManager.listForPicker()for the current cwd/sessionDir and opens the picker in current-folder scope. When that list is empty it preloadsSessionManager.listAllForPicker()so a user-initiated Tab switch is immediate; it does not auto-switch scopes.No sessions foundis printed only when the global picker list is also empty.- Selected path is opened with
SessionManager.open(selectedPath)before session creation; the process/project scope then switches to the resumed session's cwd (switchToResumedProject), reloading cwd-scoped settings and plugin caches and re-resolving scoped models.
createSessionManager() resolution order:
- If value looks like path (
/,\, or.jsonl), open directly. A path that does not exist fails withSession "<path>" not found.rather than creating a session there. - Else
resolveResumableSession(...)searches:- current scope (
SessionManager.list(cwd, sessionDir)) - global sessions (
SessionManager.listAll()) only when no explicitsessionDirwas provided
- current scope (
- Matching accepts case-insensitive session id prefixes, full JSONL filename prefixes, and the id suffix after the timestamp in
<timestamp>_<sessionId>.jsonl. - When nothing matches, the resolver (
resolveResumeTarget) looks in the same scopes for a<timestamp>_<sessionId>.jsonlfile whose name matches but which no longer reads as a session (the listing skips it), and takes the copy that continues it (see below). Otherwise resolution fails withSession "<value>" not found.
Both forms then follow the session's continuations (findSessionContinuation, through resolveResumeTarget for a key): when its conversation went on in another file of the same directory (a sibling whose header names it in continuationOf), the copy with the newest turn opens instead, unless the named file has turns of its own that copy lacks, and a notice names both files. A file that no longer holds the session its generated <timestamp>_<sessionId>.jsonl name records was replaced under that session (conflict recovery leaves it as it found it); resume then opens the copy that continues the named session, when one exists. That applies to a path whose file no longer parses, and to a key that matched only the file name (the file holds another session) or found an unlisted file in step 4. A path whose file holds another session opens that session; a file without a generated name records no session id and is never taken as replaced.
Id/filename-prefix match behavior (local or global):
- If the matched session's recorded directory no longer exists, CLI asks
Session's directory no longer exists (...). Move (re-root) it into the current directory? [Y/n].- On yes (default),
SessionManager.open()is anchored at the missing source cwd withinitialCwd, thenmanager.moveTo(cwd, sessionDir)re-roots the existing session without duplicating it. - On no, startup is cancelled. In non-TTY mode, startup fails with an error directing the user to run interactively.
- On yes (default),
- If the recorded directory still exists, the matched session is opened directly. Startup later changes the process/project scope to the resumed session's cwd and reloads cwd-scoped settings and plugin caches. It is not implicitly forked.
Path-valued resume opens directly rather than using the missing-directory move
prompt. If its recorded cwd is missing or permission-blocked, startup retains
the launch cwd without relocating the transcript; a failed cwd switch/rescope
also prints a fallback warning.
The same enterability policy applies to picker selections. A missing direct path
fails with Session "<path>" not found.; an existing empty file or malformed
non-empty headers fail closed without modifying the file, unless the file was
replaced under a session that went on in a sibling (see above).
--restore [value] selects and opens its session exactly as --resume [value]
does, then, once the interactive TUI is up, goes on with what the session's last
process left unfinished when it ended (task/restore.ts, restoreSession). Tern's
session daemon relaunches omp panes with it after a crash: omp reports
omp_restore=1 (OSC 1337 user variable) beside its session file to say it
understands the flag. /restart relaunches with it too.
A subagent whose turn the process teardown cut off counts as left mid-turn, even
though the teardown was clean: its owner's shutdown aborts the run with
INTERRUPTED_TURN_ERROR and records its session_exit as a process exit
(postmortem.Reason.EXIT), both for a first run the task executor drives and for
a revived agent's turn the lifecycle teardown disposes.
- Subagents first. Every persisted subagent transcript under the session
(
<session>/<AgentId>.jsonl, nested ones included) that its process left mid-turn, that was not killed (no tombstone) and that a cold revive can rebuild (asession_initcontract, not isolated) runs one more monitored turn as a background job of its parent, under the subagent's id. The lifecycle reviver rebuilds it from its transcript, the turn goes on as below, and the parent receives the result as the job's ordinaryasync-result, so a parent waiting on that job finds it again. - Then the session's own turn (
AgentSession.restoreInterruptedTurn). A turn cut off without asession_exitrecord (a crash, SIGKILL or power loss records none) is first closed the way exit recovery closes one whose exit was recorded: unfinished tool calls get "outcome unknown" results and an interrupted-turn abort ends it. That turn is then retried as/retrydoes: a batch whose every call was cut off runs again; otherwise the model answers from where the transcript stops.
Nothing is continued when the last turn finished, failed, or the user interrupted
it, or when a normal exit was recorded after it (the user quit with it
interrupted). --restore is interactive only, takes no prompt, and cannot be
combined with --continue, --fork, imports, --goal or --no-session.
/restart drops a launch --restore like the other one-shot selectors and adds
its own for the current session.
SessionManager.continueRecent(cwd, sessionDir):
- Resolves the session directory for the current cwd.
- Reads the terminal-scoped breadcrumb. A fresh breadcrumb whose lazy JSONL is still absent starts fresh rather than reopening an older conversation. Explicit
newSession()boundaries already have a durable header. - If it points into a nested artifact/subagent session, resolution walks up to the top-level interactive parent session (up to eight levels).
- A matching-cwd breadcrumb is used when it lies within an explicitly supplied session directory, if any. Otherwise discovery chooses the newest session with resumable content, skipping untitled, prompt-less zero-turn stubs.
- For a different, missing recorded cwd, automatic re-rooting additionally requires the current directory's device/inode to match the breadcrumb's recorded directory identity and no genuine current-project session to take precedence. A deleted/unmounted path, legacy breadcrumb without identity, or cross-filesystem move is not enough evidence to relocate history.
- When the chosen session's conversation went on in another file of the same directory (its header names the chosen session in
continuationOf), chooses that copy instead and reports it to theonSessionContinuationoption (the CLI prints a notice); step 5 re-roots that copy, not the file the breadcrumb names. A session the breadcrumb names is kept when it has turns its continuation lacks, as with--resume; a pick by write time takes the linked copy with the newest turn in either direction. - Opens the chosen session, or creates a new one when no candidate exists.
For compatibility, --continue <full-UUID> is normalized to --resume <UUID> when the UUID is the sole positional message. The autoResume setting invokes the same continueRecent behavior when no explicit session flag/session directory is supplied, and restores session model/thinking state when a prior transcript was found.
If implicit interactive auto-resume exhausts the saved models and model-fallback policy forbids substitution, startup closes the skipped session, warns, and starts a new session without its history or provider cache identity. It does not retry older transcripts or weaken restoration policy. When --max-time is set, the new session keeps the launch's original absolute deadline; time spent on the failed restore is not added back to the budget. Explicit --continue/--resume, runtime /resume, and headless/SDK hosts still fail closed under the same policy; an explicit model override remains an intentional way to restore the transcript with another model.
This is startup-only behavior; there is no interactive /continue slash command.
Interactive /restart performs normal teardown, flushes postmortem cleanup and
stdout, then relaunches the CLI. restartArgv() preserves launch configuration
flags but strips original prompts/@file positionals and one-shot session
selectors (--session, --resume, --restore, --continue, --fork, and
foreign imports). It adds --restore <session-file> only when the session
actually exists on disk, so the subagents the teardown cut off mid-turn go on in
the new process (see CLI --restore); an in-memory or
never-materialized session restarts fresh.
POSIX uses process-image replacement when available. Windows or a failed exec falls back to spawning the replacement with inherited terminal streams.
AgentSession.switchSession(sessionPath) does the runtime transition used by resume-like operations:
- Emit
session_before_switchwithreason: "resume"andtargetSessionFile(cancellable). - Disconnect the agent event subscription, abort in-flight work, and run the optional pre-switch reconciler.
- Flush pending bash/session writes and capture rollback state: session manager state; agent messages and all queues; model/thinking/service tiers; tools and prompts; provider/cache ids; memory promotion; and checkpoint rewind state.
- Clear agent and next-turn queues. For a different file, drain/detach advisor recorders.
sessionManager.setSessionFile(sessionPath), update provider-cache/session ids and memory keys, build the display context, resolve the recorded model, and rehydrate checkpoint state. When no recorded model can be restored for a different file, the switch fails here withCould not restore model <provider/id>(see below).- Emit
session_switchwithreason: "resume". - Replace agent messages, reset advisor state, and synchronize todos. Close cached provider sessions for a different file, or for a same-file reload whose replay messages changed.
- Apply the resolved (or explicitly requested) model. If the loaded branch ended with an interrupted turn, append its synthetic abort message and rebuild context.
- Restore configured/effective thinking and per-family service tiers, falling back to current settings when the target branch has no corresponding entries.
- For a different transcript, reset memory context; for any conversation rewrite, clear session-scoped tool state.
- Reconnect agent events, run the optional session-switch reconciler (interactive mode uses it to re-enter persisted modes such as plan), and best-effort refresh the workspace-root system-prompt block. Reconciler/prompt-refresh errors are logged rather than rolling back the committed switch.
- Restore target advisor cost state, finish the bash transition, notify session-change callbacks when the session id changed, and return
true.switchSession()returnsfalsewhen a before-switch hook cancels or cwd policy rejects the transition. A cross-project switch without a cwd-change callback is rejected rather than silently adopting the target cwd; callback rejection is also cancellation. The interactive selector checks this result and leaves the existing session/UI unchanged.
If a throwing step in the guarded transition fails, switchSession() restores the captured session, agent queues/messages, tools/prompts, model/thinking/service-tier, provider/cache, memory, and checkpoint state; it reconnects the prior agent subscription and re-runs mode reconciliation before rethrowing.
Normal resume switching opens an existing transcript. Because it delegates to
setSessionFile(), a missing/empty explicit target can instead materialize a
new session at that path; malformed non-empty headers are rejected.
Model restoration fails closed, like startup resume: a switch never silently moves a transcript to a model it did not record. Only a session created with hasUI and allowSessionModelFallback (the TUI), with retry.modelFallback on, keeps its current model instead, and warns Could not restore model <provider/id>. Using <provider/id>. An explicit model option (RPC open_session/switch_session with provider/modelId) replaces the recorded model, and a same-file reload keeps the current one.
For newSession, fork, and switchSession:
- Before event:
session_before_switch- reasons:
new,fork,resume - cancellable by returning
{ cancel: true }
- reasons:
- After event:
session_switch- same reason set
- includes
previousSessionFile
ExtensionRunner.emit() returns early on the first cancelling before-event result.
When a before-switch hook cancels, switchSession() returns false and does not emit the after-switch event.
SDK bridges extension session events to custom tool onSession callbacks:
session_switch->onSession({ reason: "switch", previousSessionFile })session_branch->reason: "branch"session_start->reason: "start"session_tree->reason: "tree"session_shutdown->reason: "shutdown"
These callbacks are observational; they do not cancel switch/fork.
/forkis blocked while streaming (user must wait/abort current response first)./resumeselector can be cancelled by user closing selector.- Cross-project
--resume <id>can be cancelled by declining the missing-directory move/re-root prompt. /sharehas a UI abort path (Share cancelled); the upload itself is not killed mid-flight.
When session manager is created with SessionManager.inMemory() (--no-session):
- Session file path is absent.
/exportfails withCannot export in-memory session to HTML(propagated to command error UI)./sharestill works: the snapshot is built from live entries./forkfails becauseSessionManager.fork()requires persistence./dumpstill works because it serializes in-memory agent state.- Native CLI
--resume,--continue, and--forkare rejected with--no-session; the preliminary startup parse may allocate an in-memory manager, but validation rejects these combinations before normal execution.
/sharecustom-share failures do not degrade to the default encrypted share flow; they terminate the TUI command with an error./exportargument tokenization does not preserve quoted paths with spaces./deletetreats deletion as best-effort: it attempts to delete the current session JSONL and artifact directory, logs any deletion failure, and still creates and switches to a new session. A failed or partial deletion can leave the old session or its artifacts on disk, so/deleteis not a guaranteed erasure boundary.