Chats and turns
A chat is one CLI session with a thread. ChatCore keeps a ChatSession per chat, which owns the CLI process, the thread items, the queue and the open requests. The requests below are those of the contracts, and host.chats has a method for each.
Creating and attaching
chat.create makes a chat or loads it from disk. Defaults for a new chat:
| Setting | Default |
|---|---|
provider | Claude Code |
cwd | The environment's HOME, else the user's home |
| Model | The catalog's default |
| Account | The CLI's default, or the one last picked |
runtimeMode | full-access |
Set all of them in an app. A loaded chat keeps its provider, folder, account and model. Change those with chat.configure, which runs admit and runtimeModeFor again.
The CLI starts on the first message, not on create, and stays up between turns. A CLI that went down restarts with its session on the next message. chat.attach returns the thread and streams its events to that client.
Sending
chat.send returns { queued, turnId }. During a turn, a message waits in info.queue (delivery: "queue", the default). With delivery: "steer" it joins the running turn, and the reply carries that turn's id. Slash commands, settings changes, backends without steerTurn and turns not yet started still queue. If a steer goes unconfirmed, the queue pauses until an explicit retry.
ChatSession.sendInput delivers what a person sends. ChatSession.send queues the host's own follow-ups for a new turn. chat.unqueue takes a message back for editing, or fails with request-not-found when it already went. chat.sendNow moves a queued message to the front and stops the running turn. Stopping a turn or hitting the usage limit can pause the queue (queuePaused), so check the info before you count on the rest going out.
Clients get deltas joined into fewer events. The host's thread always holds the whole text. chat.status goes to every client with the chat's info and a summary of open requests. A turn is running, done, aborted or error. info.running only says whether the process lives. An idle chat can still run a background shell or subagent.
Approvals and questions
A pending approval or question is an item with a requestId. chat.approve answers with allow, allow-always or deny, plus an optional reason. allow-always grants the rule the CLI proposed, nothing wider. chat.answer answers a question by question id. chat.dismiss leaves an async question by item id. A request already settled elsewhere fails with request-not-found.
Stopping a turn settles its open requests. Optional Codex questions outlive their turn and keep the chat at needs-you until answered or dismissed. The answer starts a new turn if Codex has finished.
For a question the CLI never asked, such as a card a context command waits on, call holdForPerson(chatId, key). The chat shows needs-you while its turn runs, and releaseHold(chatId, key) clears it once the last key is released. The card, its answer and its timeout stay with your app.
relocate(chatId, cwd, during?) moves a loaded chat to another folder on the same conversation:
- The CLI ends before
duringruns, so your app can move files freely. admitchecks the new folder first. A refusal leaves the CLI running.- Messages sent meanwhile queue and go out in the new folder. Outbox wakes are turned away.
- It resolves with the chat's info once the new record is on disk, then emits an info event.
- A throw from
duringor the write keeps the old folder. - It fails with
chat-busywhile a turn, background work, an open request, a hold, an active goal, a start or another relocation holds the chat. - Until it settles,
clear,restart,compactand account changes fail withchat-busy, andkillwaits. CheckisRelocating(chatId)before your own forks and copies. An outbox handler that opens a turn answerswaitwhileWakeChat.relocating?.()is true, asdeliverMessageHandlerdoes.
Subagents
chat.subagent reads a delegated agent's conversation from the CLI's transcript, a page at a time. With watch: true it sends chat.subagentChanged as it grows. chat.stopSubagent stops a subagent a task opened, and its parent and siblings go on. It fails with subagent-stale during a turn of another process. Otherwise it only marks the row stopped. chat.stopTask stops one background shell or monitor, where the CLI supports it.
A subagent row with origin: HOST_TASK_ORIGIN and a childId reads that child's chat instead of a CLI transcript. Stored children load on demand. Watches report changes against the parent row and end when the client disconnects, releases the watch or the parent is removed. subagentItems reads the full child conversation. Pass stopNode(nodeId, reason) as the third argument of stopSubagent to stop host-managed work; the host decides how a node stops. A task whose child has no stored chat remains a host operation.
Task rows
The core writes the row of each task a chat gave, so a host writes none. The taskRows(chatId) hook returns the chat's Tasks. The core lays a row for each when the chat opens and syncTaskRow(task) rewrites one when its task changes. A row is a background subagent item with the id taskRowId(task.id) (task-<id>), which is also its toolUseId, and origin: HOST_TASK_ORIGIN. A client reads the task back from a row with taskIdOfRow(row), which is null for a row the CLI opened itself. A cancelled task also gets one warning note; ChatCoreOptions.taskRemovedReason words the reason when the task has no result, and defaults to "it was removed".
A clear hides the rows of the tasks the chat gave at that moment for good. The core keeps those ids in the record's extras as clearedTaskIds, so a reload and a later syncTaskRow leave the rows hidden.
Sidecars
A sidecar is what a host keeps per chat beside its record, as a ChatSidecar with three optional members. owns(name) says whether a file in the chats folder is one of its files, so the chat list skips it. removeChat(chatId) removes what is kept when the chat is cleared, deleted or removed. copyChat(from, to, kept) gives a fork its part, where ForkKept says which messages (item) and visuals (visual) the fork took over. The core registers its bookmarks and visuals itself; pass the rest in ChatCoreOptions.sidecars and fork with core.copySidecars.
const plans: ChatSidecar = {
owns: (name) => name.endsWith('.plans.json'),
removeChat: (chatId) => rm(planFile(chatId), { force: true }),
copyChat: (from, to) => copyFile(planFile(from), planFile(to))
};
new ChatCore({ ...options, sidecars: [plans] });Goals
/goal <objective> sets a goal and /goal alone shows its state. /goal pause, /goal resume and /goal clear act on it. The goal is info.goal. Claude Code pursues it within one turn. Its check sees only the CLI's own background work, so while a task the chat gave still owes it a wake (taskRows), the turn ends at the check instead of sending the agent on, and the goal stays active until the wake's turn checks it again. Codex opens further turns itself until the goal is met. Stopping a Codex turn pauses its goal first.
While a goal is active, messages queue, delivery: "steer" included. chat.goal pauses, resumes or clears without a turn on a CLI with goal calls. Otherwise it sends /goal as a turn and fails with chat-busy during a turn. A met goal clears from info.goal on the next message.
Searching and resuming
searchThreadItems(items, query, { limit }) from @adecore/agents/chat returns up to limit hits, each with a snippet, for the user and assistant messages that match. findClaudeSession(projectsDir, sessionId, cwd?) returns the path of a Claude session's transcript, searching cwd's project folder first. It caches the location, so call it as often as you need.
listClaudeSessions and listCodexSessions from @adecore/agents/chat list CLI sessions started outside your app, newest first, as ExternalSession records. They read through a SessionFs, and nodeSessionFs() reads the real disk. Both leave out Codex forks and subagents (isForkOrSubagent).
Visuals
A visual is a page an agent publishes in a chat, through a command of your app. That command calls host.chats.publishVisual(chatId, { title, html, maxHeight?, layout?, heights?, turnId? }) and gets the ChatVisual back. The chat need not be loaded. A visual published during a turn belongs to it unless the input names another. listVisuals(chatId) returns the visuals in publish order, and chat.removeVisual removes one.
VisualStore keeps the list in chats/<id>.visuals.json and each page as an attachment, so host.chats.attachment(chatId, visualId) returns it as text/html. Publishing injects the bootstrap of injectVisualBootstrap and checks VISUAL_LIMITS. A page that breaks one fails with visual-invalid or visual-too-large and a message for the agent. Changes reach attached clients as chat.visuals, and chat.attach returns the list too.
Clear and chat.kill remove a chat's visuals. A core of your own that forks chats copies them with visuals.copyChat(fromChatId, toChatId, keep?). removeChat(chatId) cleans up after a failed fork. Never serve an attached text/html file on your app's own origin (see Serving a page).
Stopping and removing
| Request | |
|---|---|
chat.cancel | Stops the turn and keeps the conversation. With subagents, also ends the agents the chat opened. |
chat.clear | Starts the chat over. Refused with chat-busy during a turn, unless force. |
chat.compact | Folds the context, natively or by prompt, as the CLI's compaction capability says. Either way it opens a turn without a message of the person, which leaves one compaction item and moves usage to the size after the fold. |
chat.restart | Ends the CLI and keeps the conversation. The next message resumes it in a fresh process that reloads skills, plugins and servers. Fails with chat-busy while a turn, request or background work holds the process. |
chat.kill | Removes the chat (record, log, attachments, bookmarks, visuals) and ends its CLI. |
| Detaching or disconnecting | Stops streaming to that client. The chat goes on. |
ChatCoreOptions.unloadAfterMs | Takes a chat out of memory once nobody read it for that long and it has no turn, request, hold, move or owed resume, and its CLI holds no background work or goal. A CLI left idle ends with it. Its info stays in chat.list; the next create, attach or note loads it from its record, as after a restart, and the next message resumes the conversation in a new process. unloadIdle(chatId) does it at once. Needs a store. |
ChatCoreOptions.releaseProcessAfterMs | Ends the idle CLI of a chat that said nothing for that long, whoever reads it, under the conditions of releaseProcess. The chat stays, and its next message resumes the conversation in a new process. A CLI that still holds work is asked again after the next thing the chat says. |
releaseProcess(chatId) | Ends the CLI of a loaded chat under the same conditions and keeps the chat in memory, for a host that knows a chat's work is over. Answers whether a process ended. |
host.close(), ChatCore.shutdown() | Writes every thread, ends every CLI and settles once they exited. |
Ending a CLI closes its input, then sends SIGTERM and SIGKILL to its process group. chat.kill does not wait. shutdown does. Process groups are POSIX, so check ending on every platform you ship.
Restarts
A turn running when the host went down loads as aborted, with a note from notResumedNote. If onInterruptedRun returns true, the host owes a resume instead and calls recoverInterrupted() and resumeRun(chatId, turnId, attempt) when ready. endedAt, unownedReason and resumeWords mark deliberate stops and word the resume.
A turn that hit the usage limit or an overloaded model ends as an error turn with a limit. Resuming it when the limit lifts needs limitResume on the core, which AgentHost does not install. resumeAtReset on a chat turns it off for that chat. Moving the chat to another account is always the person's choice.
Background work goes down with the host too. A chat that loads after a restart tells its agent in one note what it lost: the turn it was in, every command and monitor by its full text, and every subagent and workflow, with the advice to restart what is still needed. A resumed turn hears that note with its resume prompt. recoverInterrupted() also loads a chat that still listed commands in the background. When no turn of such a chat is taken up again, the core hands the LostWork to the lostWork hook. A host that wants the agent to hear it right away owes the chat a turn, and checks owesRestartWake(noteId) on the session before opening it.
A turn that was running when the host went down is an InterruptedRun: the chat, the turn and the attempt that would take it up. A session decides which turn it takes up, or why that turn ends. ResumeWords say how: what the CLI is told and the note a person reads.
limitedTurn(items) returns the last turn of a thread when it stopped on a limit. limitResumeAt(items, turn, now) returns when the host takes it up again, or null: a usage limit at its reset, an overload after 1, 5 and 15 minutes. A session also needs the host's switch, a clock and a way to owe the resume.
Parts of the core
These are the pieces a host meets when it assembles a core or a backend of its own:
PromptNotesis what a host says in front of the next prompt, andChatReferencesthe chats a person attached to a message and what the agent is told about them.ChatSendExtras.brief, andbriefonChatSession.wake, is the host's instruction for that one prompt: it comes toPromptNotes.next(brief), which places it among the rest (without notes it is heard as it is). A slash command hears nothing in front of it, so there the session puts the brief after the command, as<command>\n\n---\n<brief>, and the thread shows that message. A brief queued with its message goes out with it and no other, and is not kept across a restart.ChatThreadis the state of one chat as a client sees it. Every change returns the event that describes it, so the host sends exactly what it applied.- A backend gets a
TurnInputper turn, answers an approval with anApprovalDecision(allow,allow-alwaysordeny), and reports to aBackendHostthroughonEvent. ChatSpawnOptionsstart a CLI withspawnChatProcess, and aChatChildwraps one. A backend talks to the part of the child process that moves lines in and out, takes a signal and reports an exit, which a test replaces with a CLI in the same process.- The two built-in backends take options of their own.
CodexClientInfois how the host names itself to the Codex app-server. forkThreadOnce(spec, params)forks a Codex thread up to a turn in a process of its own (CodexProcessSpec) and returns the new id.ClaudeTitleReaderreads the title Claude Code gave a session from its transcript; a title a person set with/renamewins.claudeProjectSlug(cwd)is the folder name Claude Code gives a working folder.suggestChatTitleasks a CLI in its one-shot mode for a title, from aChatTitleInput, and returnsnullwhen none answers in time.runningInBackground(items)returns the work a CLI goes on with after its turn ended: background subagents and workflows.chatOpener(deps)returns a function that opens the chat a turn is owed in.ComposerPreferenceis a stored runtime mode and model selection.ChatErrorCodeis the union of the codes aChatErrorcarries; Error codes explains them.
Visual working files
VisualStore.writeSource(chatId, name, html) saves a source in <home>/chats/<encodedChatId>.visuals/, apart from the published page. The name ends in .html and has no folder. Sources share the visual byte limit. writePreview(chatId, png) writes a preview there.
workspacePath(chatId) returns the folder, and prepareWorkspace(chatId) creates it, owner-readable only. removeChat removes sources and previews with the visuals. Forks copy only published pages.
Live UI sources
ChatCoreOptions.uiFenceLanguage sets the fence info string sessions compile (default UI_FENCE_LANGUAGE), and core.uiFence reads the name back. Write the agent's session note (uiSessionNote) with that name, so the note and the compiler cannot disagree. ChatCoreOptions.intelligentUi takes a ChatUiHost from @adecore/agents/chat. The host records what the writing chat may read and registers a fixed list of ChatUiSource entries. Each has argument and result schemas, authorize, and an abortable read. authorize checks both the recorded and the current rights, also before serving a cached value. Throw a ChatUiRefusal(code, reason) to give a refusal or failed read a stable code.
ChatUiQueries compiles against those schemas and freezes the first results and text fallback in the reply. It answers ui.query only for a client attached to that chat, after checking the stored block and bound inputs. Reads are rate limited and slow sources time out. Nothing refreshes in the background.
The recorded access lives in the chat record under uiAccess and never reaches a client. A fork records its own rights. After a restart, a read without complete saved access fails. ChatCore.choose passes only host-issued query values, and a client read id grants nothing.
A reply that drew UI keeps the block source in its text. readableAssistantText(item) from @adecore/agents/chat returns the text with each block replaced by its fallback. Use it wherever your app hands a reply to another agent, a notification or a search index.
ChatUiHost.link checks File, Diff, Commit and Node targets against what the writer could reach then and now. ui.link answers only for a stored, visible node in an attached chat. A missing or refused link stays plain text. Live queries and Links cover both sides.
Choosing how a chat is named
Without a host policy, native titles stay native, and a CLI that names nothing itself (Codex, Grok and the other CLIs with a one-shot mode) uses ChatCoreOptions.nameChat after its first successful turn. A host that chooses a writer can also provide titlePolicy(chatId, provider), returning generated or native. The callback is read when a title arrives or a generation begins, so an already open chat follows a changed choice.
Under generated, nameChat can name any provider's newly unnamed chat. Native backend titles and transcript reads wait for that result. A null result or a failed request allows an available native title afterward; it starts no second writer. Existing titles are retained. A clear invalidates pending generation and transcript reads, even before a backend reports a session id. Without nameChat, native titles remain available under either policy.
buildTitlePrompt(prompt, answer) and parseTitle(output) let a host use its own bounded, account-aware generator while keeping the package's title format. They cap the conversation input and accept a JSON title object; output without a valid title returns null.