Skip to content

Host ​

AgentHost serves the chats of one data folder, with their CLIs, accounts and usage, over ports. wireAgents is the same without ports, for an app with its own wire.

ts
import { AgentHost } from '@adecore/agents/host';

const host = await AgentHost.open({ dataDir });
const disconnect = host.connect(port);

AgentHost.open(options) reads the accounts. Unless background is false, it also starts periodic checks of sign-ins and plan limits. host.chats, providers, accounts, usage and limits are the services. host.close() drops every client, writes every thread and ends every CLI. It settles once they exited, and a second call returns the same promise.

Options ​

AgentHost.open takes these options. wireAgents takes the same, without background.

Option
dataDirWhere the chats, attachments, bookmarks, visuals, accounts and usage history go. See Storage.
envThe environment the CLIs start in. Without it, this process's own, filtered by cliEnvironment.
environmentPolicyMore to filter out. With it, a passed env is filtered too.
systemNoteWhat every agent is told once, at the start of its process.
clientHow the host names itself to Codex.
accountsHostThe host's name in refusals, the variable prefixes no account may set, and its keychain prefix. See Accounts.
claude{ allowedTools, apiKey, entrypoint }: tool patterns Claude Code may use without asking, in every mode, how to run it on an API key, and the name the CLI gives your app. See Providers.
codexRulesCommand prefixes Codex may run without asking, written to its rules in every Codex home.
coreMakes the ChatCore from the options a plain one would get, for a core of your own.
backgroundAgentHost only. true by default.
command, codexCommand, spawn, detectWhat is started, how, and how a CLI is found. Tests point these at fakes.

allowedTools and codexRules grant permissions, so tie them to what your app allows. Nothing is allowed by default.

Clients ​

host.connect(port) serves one client over a FramePort and returns a disconnect function. A frame or payload that does not parse gets bad-request. An unknown name gets unknown-request. A coded error from a handler returns its code. Any other error returns internal, and the host logs it.

A client gets every chat's status, the accounts, the limits, and the thread events of chats it attached. Disconnecting detaches its chats and usage page, and the chats go on. The port has no authentication, timeout or reconnect. Whoever hands the host a port has already decided who is on the other end.

What a plain host refuses ​

A fork needs a place in the app, so a host that only runs chats answers chat.fork, chat.forkInfo, chat.summarize and chat.continueOn with chat-unsupported. It has no tasks or messages between chats either (see Coordination). An app with a place for forks replaces those handlers.

wireAgents ​

ts
import { wireAgents } from '@adecore/agents/host';

const wiring = wireAgents({ dataDir });
await wiring.accounts.load();
wiring.start();

const release = wiring.connect(clientId, (event) => socket.send({ type: 'event', event: event.event, payload: event.payload }));
const result = await wiring.handlers['chat.send'](payload, clientId);

wiring.handlers has a (payload, clientId) => result handler for every agent request. connect(clientId, send) streams one client its events until you call the returned function. A handler checks nothing itself, so your wire must validate the frame and payload and check who asks. Load the accounts before the first request. start() runs the periodic checks and stop() ends everything. chatHandlers, accountHandlers and usageHandlers are the three parts of handlers. ClientSinks is the per-client fan-out behind connect, and WatchedSinks the same for events that only go to clients that called watch.

wireAgents returns an AgentWiring. Its handlers are AgentHandlers, one AgentHandler per request, with the payload and the result typed from the request's name. chatHandlers answers every request but the accounts.* and usage.* ones. The send of connect receives an AgentEvent, the { event, payload } before framing, with the payload typed from the event's name.

ChatCore ​

The chats are a ChatCore. A host adds what it knows through ChatCoreOptions.hooks, an object with every hook optional, and passes a factory as core:

ts
import { resolve } from 'node:path';
import { ChatCore, type ChatCoreOptions, ChatError } from '@adecore/agents/chat';
import { narrowerMode } from '@adecore/agents/providers';

function projectHooks(folders: ReadonlySet<string>): NonNullable<ChatCoreOptions['hooks']> {
    return {
        admit: async (_chatId, cwd) => {
            if (!folders.has(resolve(cwd))) {
                throw new ChatError('folder-denied', 'This folder is not one of the projects.');
            }
        },
        runtimeModeFor: (_chatId, mode) => narrowerMode(mode, 'auto')
    };
}

const host = await AgentHost.open({ dataDir, core: (options) => new ChatCore({ ...options, hooks: projectHooks(projectFolders) }) });

admit runs on every create and load, from disk too. resolve only normalizes a path, so check what a folder really is before it goes in the set.

HookWhat the host adds
admit(chatId, cwd)Throws for a folder the chat may not work in.
admitUi(chatId, clientId)Throws for a client that may not have this chat's UI blocks resolved, before a link or a query is read.
opening(payload)The start of a chat as the host planned it before the client asked; the core reads what it returns.
runtimeModeFor(chatId, mode)Narrows the mode a chat runs in, whatever its record or its client says.
openingSelection(chatId, kind)The model a new chat starts on.
openingAccount(chatId, kind, named)The account a new chat starts on, given the one its start named; throw an AccountError to refuse it. Undefined leaves it to the order of the accounts.
instructionsFor, resumeNoteFor, resumeInstructionsForWhat an agent is told at process start, before a resumed thread, and as new instructions to a thread that keeps its first.
foldersFor(chatId)Extra folders beside the working folder. Asked before every turn, and a change starts a new process. Claude Code gets them as --add-dir.
projectConfigFor(chatId)false runs the chat's CLI without the configuration of its working folder; see Folders you do not trust.
promptSuggestionsFor(chatId)true has the chat's CLI predict the next prompt after each turn, sent as chat.suggestion. Each prediction costs a model request; asked at process start.
subagentFor(chatId)true for a chat another agent delegated its work to. Codex from 0.129.0 marks the new thread as a subagent's; asked at process start.
envFor(chatId, base)The environment of the chat's CLI before its account adds its own.
promptNotesFor, referencesForNotes in front of the next prompt, and how chats a message points at are named to the agent.
promptHeardFor(chatId, text)What the agent hears in front of a prompt for what its text says, on every way a prompt is sent (a person's message, a steer, a wake). The thread shows none of it, and a slash command hears nothing.
hostSkillsFor(chatId)The names of the host's own skills. A message picks them like a CLI's skills and keeps $name in its text, but no CLI gets one as a skill to run.
cliTitleFor(chatId, title)A title the chat's CLI gave its session, pushed as an event or read from its transcript, as the host wants it stored. Without it the title stays as the CLI wrote it.
hiddenFor(chatId)Leaves the chat out of every list.
openingNotes, opened, recordExtrasWhat the host lays down in a loaded chat above its task rows and below them, and keeps in its record beside the thread.
taskRows(chatId)The tasks a chat gave. The core lays a row for each when the chat opens and hides them for good on a clear. While one still owes the chat a wake, a goal's check does not send the agent on (goals).
clearing, cleared, forgotten, deleted, removed, broadcastedWhat goes along with a clear, with the record of a chat nobody loaded (deleted) or a removal, and a look at every event.
endedAt, unownedReason, resumeWordsTaking up a turn the host went down in; see Restarts.
lostWork(chatId, lost)Background work a restart took from a chat that no resumed turn tells; see Restarts.

No hook knows the client. Checking who asks belongs on the wire.

A host holds a ChatCore and gives it its hooks; it does not subclass it. What the host adds beside the core is its own object over core, and the state of threads, clients and writes stays private. ChatCoreOptions.codexSideCommand is the command of the app-server opened beside a chat to read or fork a thread, for a host whose chats run Codex with more on its command line. The host calls the public methods:

MethodWhat a host does with it
get(chatId), isLoading(chatId)The loaded chat, and whether a create of it is under way.
readChat(chatId), hasStored(chatId)A chat as it stands in memory or on disk, and whether it has a record.
history(chatId, cursor?, limit?)A page of a loaded chat's thread, the newest without a cursor.
writeRecord(chatId, info, items, preambles?)Writes the whole record of a chat nobody loaded, such as a fork, with its files copied over.
deleteRecord(chatId)Removes what a chat nobody loaded keeps on disk; false for a loaded one, which kill removes.
sendTo(clientId, event)Sends one client an event of the host's own.
loaded(chatId), require(chatId)Waits for a create under way, and returns the loaded chat or throws chat-not-found.
switchAccount(session, account)Moves a chat to another account, under the rules of an account switch.
findAttachment(chatId, id)The file behind an attachment id, also of a chat nobody loaded: its thread, its queue or a visual's page.
copySidecars(from, to, kept)Gives a fork what every sidecar keeps of the original; kept says which messages and visuals went along.
syncTaskRow(task)Writes the row of a task into the chat that gave it, when that chat is loaded.
uiFenceThe fence name the core compiles replies under, for the note that teaches an agent the UI language.

ChatCoreOptions also takes checkpoints, skills, onInterruptedRun, limitResume, sidecars and taskRemovedReason. checkpoints is an object with take, diff and settle for a tree per turn. Its optional head records the commit at turn start and end, so a card can show that the branch moved. Without checkpoints a turn has none. The package runs no git itself.

Electron ​

Run the host in a utility process and keep the window to the contracts and views. The main process starts the utility process with the data folder and makes a MessageChannelMain per window. After it checked which window and frame asked, it hands one port to the utility process and the other to the window. The utility process wraps its MessagePortMain as a FramePort (postMessage to send, on('message') with { data } to receive, start()), calls host.connect, and disconnects when the window goes.

On quit, wait for host.close() before the utility process exits, so the host writes every thread and ends every CLI. Give it a time limit in case it hangs. The channel names and window checks are your app's. The package registers none.

Reading plan limits ​

UsageMonitor.refresh(true) reads all eligible accounts on request. If an ordinary pass is already running, callers share one forced follow-up; they do not inherit the ordinary pass's recent-use filter. A new forced caller joins a forced pass already running. Stopping the monitor ends its timer, not a pass already requested. The original ordinary callers keep their own error if listing providers fails; a queued forced pass still gets its own attempt.

A live update wins over any older in-flight probe result for that account. A failed read without a newer live update retains its last windows and their update time, with unavailable.reason set to failed. Clients can show those numbers as last known, with the failure beside them. They must not offer that account as known room until a later read succeeds. The normal five-minute pass, backoff and recent-account eligibility are unchanged.

Licenses and third-party notices are listed in each package.