* mcp: free memory and disk in the status line
* mcp: free memory and disk in the end line of answers
* mcp: ❗️ after a low part of the end line, RAM below 5%
128 KiB
SimpleX MCP server: flows
Sequence diagrams of the main flows of
@simplex-chat/mcp0.3.0, each with notes and source locations.serveis shown in flows 1-16, and the Claude Code plugin in flows 17-38.Related specs: README | Architecture | API
Participants:
| Letter | Participant |
|---|---|
| P | the person at the terminal |
| A | the agent in Claude Code |
| H | the HTTP listener with the MCP SDK |
| T | AgentTools |
| X | Actions |
| K | Control |
| C | the SimpleX core behind ChatApi |
| O | the owner in the SimpleX app |
| D | a peer |
In flows 1-16, #G is the agent control chat, USER the agent's user ID, DATA the data folder. Calls to the core are shown as the ChatApi methods the server calls, with their arguments in short. Card and progress texts with a semicolon are shown with a comma in the diagrams; the exact texts are in API.
Table of contents
- First start and the owner joins
registerconnectwith approvalsendwith responsesreceivewithwaitsendunder a standing approval, and/revokeleave- Mode
host - Expiry
- A lost call and its re-attachment
- Shutdown with pending actions
--ownerssetupdownloadwith approval/forwardsendwith a file/leaveand/delete CHAT files
Claude Code plugin (participants):
- First session start and the owner joins
- Session process start and attach
- A tool call with approval in the session group
- A prompt from the session group
- A terminal prompt and the answer
- A tool use approved in the session group
- Mode
hostfor a session /givereset-owners- Idle close, idle stop and a newer version
/clear,--continueand/resumein one session- A member joins the Main group and a session's group, and a person is added to it
reply- A run that is not interactive
- A prompt of Claude Code
- The steps of a turn
- A reaction in the session group
- A tool approved for the rest of a session
- A summary of the session's context
- The list of sessions
- The texts of a turn
- The status line command
1. First start and the owner joins
sequenceDiagram
participant P as Person
participant S as serve.ts
participant C as Core
participant K as Control
participant O as Owner
P->>S: simplex-mcp serve my-agent --display-name "My Agent"
S->>S: DATA mode 0700, lock, token, headers.json
S->>C: ChatApi.init DATA/simplex
S->>P: version line, data folder, approval mode
S->>C: apiGetActiveUser (none)
S->>C: apiCreateActiveUser {displayName: "My Agent", fullName: "", peerType: agent}
S->>C: apiSetNetworkConfig smpProxyMode always, smpProxyFallback allowProtected
S->>C: /_temp_folder DATA/tmp
S->>S: DATA/files/sent deleted
S->>C: startChat, events buffered
S->>C: apiListGroups USER (no control marker)
S->>C: apiNewGroup USER {My Agent, history on, menu pending, list and leave}
S->>C: apiSetGroupCustomData #35;G {"simplexMcp":{"control":true,"nextAction":1}}
S->>P: Agent control chat "My Agent" created.
S->>K: load
K->>C: apiListMembers #35;G
S->>S: HTTP listens on 127.0.0.1:5226, /mcp answers 503 until the control chat is started
S->>S: server.json
K->>C: apiDeleteGroupLink #35;G (groupLinkNotFound ignored)
K->>C: apiCreateGroupLink #35;G member
K->>P: join line, QR code, link, QR hint, owner line
S->>P: Listening on http://127.0.0.1:5226/mcp
O->>C: joins by the link
C->>S: joinedGroupMember
S->>K: onEvent, queued
K->>C: apiListMembers #35;G
K->>C: apiDeleteGroupLink #35;G
K->>C: apiSetMembersRole #35;G [3] owner
K->>C: apiListMembers #35;G
K->>O: I'm your agent. I ask here before I connect, send, download a file or leave a chat.
K->>P: Alice joined (member 3) and is now an owner. The link is deleted.
K->>P: Add the agent to Claude Code: npx -y @simplex-chat/mcp register my-agent
Notes:
- At first use, libsimplex and the Node.js add-on are downloaded, with one
Downloading ...line each on stderr (installLibs,installAddon). - With
--data,--data <folder>is appended to the register hint, shell-quoted (registerHint). - With
--qr-code small, the lineIf the QR code does not scan, ...is printed after the link (Control.openLink). - Events that arrive before the HTTP listener starts are buffered and handled in order (
bufferEvents). - The server runs
ownerJoinedfor everyjoinedGroupMemberevent of a human without--owners, and the link is deleted in that handler (Control.onEvent,ownerJoined).
Source: main, readStdin, startServer, startAgent, prepareCore, deletePresetContacts, updatedUser, bufferEvents, setTempFolder, createDataFolder, acquireLock, releaseLock, serverToken, headersFile, writeHeadersFile, writeServerFile, startHttp, Control.load, rename, describe, updateProfile, start, startOwners, openLink, deleteLink, findControlGroup, controlDataOf, createControlChat, createGroup.
2. register
sequenceDiagram
participant P as Person
participant R as register.ts
participant L as claude CLI
participant CC as Claude Code
participant H as HTTP
P->>R: simplex-mcp register my-agent [--scope local] [--data DIR]
R->>R: read DATA/server.json
alt server.json missing
R->>P: Agent "my-agent" was never started. Start it with: ... (exit 1)
end
R->>L: claude mcp remove --scope user simplex-my-agent
R->>L: claude mcp add-json --scope user simplex-my-agent {"type":"http","url":"http://127.0.0.1:5226/mcp","headersHelper":"cat DATA/headers.json","timeout":169800000}
alt claude not found
R->>P: Add this entry under "mcpServers" in ~/.claude.json: {...} (exit 1)
else add-json exit status other than 0
R->>P: claude mcp add-json failed: STDERR (exit 1)
end
R->>P: Added to Claude Code: scope user, server simplex-my-agent.
CC->>CC: headersHelper: cat DATA/headers.json
CC->>H: POST /mcp with Authorization: Bearer TOKEN
Notes:
simplex-mcpignores the exit status ofclaude mcp removeand stops at that step only when theclaudebinary is missing (register).- On Windows, a missing
claudeis run again throughcmd.exe, with each argument quoted for it (runCommand,runInCmd,cmdArgument). timeoutis(expireHours + 24) × 3600000 + 600000ms fromserver.json(registryEntry).- With
--scope local, the project folder in the manual entry is the git repository root, the main repository of a worktree, or the current folder outside a repository (manualEntryText,projectRoot,gitRoot,repositoryRoot).
Source: registerOptions, main, register, registryEntry, manualEntryText, readServerFile.
3. connect with approval
sequenceDiagram
participant A as Agent
participant H as HTTP and SDK
participant T as AgentTools
participant X as Actions
participant K as Control
participant C as Core
participant O as Owner
participant D as Peer
A->>H: tools/call connect {target: "@directory.simplex", wait, idle}
H->>T: validated input, abort signal, progress token
T->>X: find(key): none
T->>C: apiConnectPlan USER @directory.simplex
C-->>T: contactAddress ok, planSimplexName
T->>T: classifyPlan: prepareContact with domain
T->>X: create(key, connect fields)
X->>K: refusal: none
X->>K: saveCounter: apiSetGroupCustomData #35;G
X->>K: postCard
K->>O: I want to connect to bot X (@directory.simplex), as myself. /'approve N' or /'reject N'
T->>X: decided(action, call)
X-->>A: progress: Action N waits for an approver until TIME.
O->>C: /approve N
C->>K: newChatItems
K->>X: approve(action, "Alice")
X->>T: performConnect
T->>C: apiConnectPlan USER @directory.simplex
T->>C: apiPrepareContact USER LINK linkData directory.simplex
T->>C: apiConnectPreparedContact @C incognito false
C-->>T: startedConnectionToContact
D->>C: accepts the request
C->>T: contactConnected: markConnected, collect @C
T-->>X: perform ends
X->>K: outcome
K->>O: card edited: I connected to bot X (@directory.simplex), as myself. Approved by Alice.
T->>C: apiGetChat @C count 50
T->>T: wait until idle or startedAt + wait
T->>C: apiChatItemsRead @C, new item IDs
T->>X: remove(action)
T-->>A: {action: N, status: done, chat: @C, connected: true, messages}
Notes:
- The plan is read again in the perform step (
AgentTools.performConnect). - Join methods per plan (
AgentTools.join,classifyPlan):
| Plan | Methods |
|---|---|
| known prepared contact or group | apiConnectPreparedContact(C, incognito, message)apiConnectPreparedGroup(G, incognito, message) |
channel link (direct false, with link data) |
apiPrepareGroup(USER, LINK, false, linkData, domain)apiConnectPreparedGroup(G, incognito) |
| contact address with link data, and a SimpleX name or a message | apiPrepareContact(USER, LINK, linkData, domain)apiConnectPreparedContact(C, incognito, message), or apiConnectPreparedGroup for a business |
contactViaAddress |
apiConnectContactViaAddress(USER, incognito, CONTACT_ID) |
| other links | apiConnectPreparedLink(USER, incognito, LINK) |
- After a failed prepared connect, the server deletes the prepared chat without notifying (
AgentTools.connectPrepared). - The connection is matched by
contactConnectedoruserJoinedGroup: by contact or group ID, or by the pending connection ID (AgentTools.onContactConnected,onUserJoinedGroup,completeConnect). In the plugin, the pending connection ID is also recorded in the session group's custom data. When the connection completes after the call returned, within a day of the record, its chat becomes the session's (AgentTools.performConnect,Session.claimPending,Hub.onEvent). - In the perform step the server waits for the other side until
startedAt + wait, at most untilcreated + 23 h 50 min, and then reportsconnected: false(editWindow,AgentTools.performConnect). - Without
message, the idle time is counted from the connection; withmessage, from the first reply (AgentTools.markConnected,awaitResponses). - For a target the agent is connected to, the result is
status: knownwith its chat fields, and no action is created (AgentTools.connect). In the plugin, the chat becomes the session's when it has no owner (AgentTools.ownChat). - Exact progress texts:
Action N waits for an approver until TIME., thenAction N waits for the connection until TIME., thenK messages in CHAT; waiting until TIME.(progressText,AgentTools.connectedChat).
Source: AgentTools.connect, action, ownChat, connectResult, actionResult, connectedChat, plan, performConnect, join, connectPrepared, completeConnect, markConnected, Actions.create, decided, approve, Control.postCard, outcome.
4. send with responses
sequenceDiagram
participant A as Agent
participant T as AgentTools
participant X as Actions
participant K as Control
participant C as Core
participant O as Owner
participant D as Peer
A->>T: send {chat: #35;15, text, reply_to, mention: [44], wait, idle, limit}
T->>C: apiGetChat #35;15 count 0
T->>C: apiGetChat #35;15 around REPLY_TO count 0
T->>C: apiListMembers #35;15
T->>C: apiGetChat #35;15 count 0
T->>K: standingApprover(chatInfo, messages): none
T->>X: create(key, send fields)
X->>K: card size check and approvers
K->>O: I want to send a message to group X: `text` replying to ... mentioning @Switchback /'approve #35;15 N', /'approve #35;15 all' or /'reject #35;15 N'
O->>C: /approve #35;15 N
K->>X: approve(action, "Alice")
X->>T: performSend
T->>T: collect #35;15 items with ID above the sent item
T->>C: apiSendMessages #35;15 [{msgContent, mentions, quotedItemId}]
C-->>T: sent item S
D->>C: replies S+1, S+2
C->>T: newChatItems: collected
X->>K: outcome
K->>O: card edited: I sent a message to group X: `text` ... Approved by Alice.
T->>T: wait until idle seconds after the last reply, or sentAt + wait
T->>C: apiChatItemsRead #35;15 [S+1, S+2]
T->>X: remove(action)
T-->>A: {action: N, status: done, chat: #35;15, item: S, responses, more: 0}
Notes:
- Checks before the action:
textorfile, the chat connected, roleobserverorrelayrefused,reply_toitem a message, mentioned members present and the chat a group, and the message length with its quote (AgentTools.send). - The server starts collecting before the send and, after it, drops items with IDs up to the sent item (
AgentTools.performSend). - Mentioned names missing from the text are prefixed as
@name(messageText). - While a collected message is live, the server waits for its final update; live items are left out of
responsesand counted inmore(awaitResponses,AgentTools.sendResult). - At most 100 replies are kept per action; later ones are counted as overflow (
maxCollected,ChatItemsWatch.collect).
Source: AgentTools.send, sendResult, performSend, ChatItemsWatch.collect, awaitResponses, requestLines.
5. receive with wait
sequenceDiagram
participant A as Agent
participant T as AgentTools
participant W as ChatItemsWatch
participant C as Core
participant D as Peer
A->>T: receive {chat: #35;12, wait: 3600, limit: 50}
T->>W: collect #35;12 into arrived
T->>C: apiGetChat #35;12 initial 1
C-->>T: chatStats.unreadCount 0
T-->>A: progress: No new messages in #35;12, waiting until TIME.
D->>C: post, item 40
C->>W: newChatItems: arrived
T->>C: apiChatItemsRead #35;12 [40]
T->>W: stop collecting
T-->>A: {chat: #35;12, messages: [40], more: 0}
Notes:
- With unread items the server reads
aroundthe first unread item,count0, then pages ofafterthe last item,count100, until it holdslimit + 1unread, non-live messages or a page is short (unreadItems,isNewMessage). - Unread items other than messages in the read pages are marked read with the returned messages (
AgentTools.receive). more: the arrived messages not returned, the overflow and the unread items not read (AgentTools.receive).- Items received while the pages are read are returned once (
AgentTools.receive). - Exact progress text:
No new messages in CHAT; waiting until TIME.(AgentTools.receive).
Source: AgentTools.receive, unreadItems, isNewMessage, reportProgress, nextChange, awaitResponses.
6. send under a standing approval, and /revoke
sequenceDiagram
participant A as Agent
participant T as AgentTools
participant X as Actions
participant K as Control
participant C as Core
participant O as Owner
O->>C: /approve #35;9 all (on a pending send card)
C->>K: newChatItems
K->>C: apiGetChat #35;9 count 0
K->>C: apiSetGroupCustomData #35;9 {"simplexMcp":{"approvedBy":"Alice","approvedById":3,"approvedAt":"..."}}
K->>X: approve each pending send to #35;9 with a card
K->>O: Approved for business X (#35;9) by Alice. /'revoke #35;9'
A->>T: send {chat: #35;9, text}
T->>C: apiGetChat #35;9 count 0
T->>K: standingApprover: Alice
T->>X: create(key, fields, "Alice"): performing, standing
X->>K: saveCounter (no card)
X->>T: performSend
T->>C: apiSendMessages #35;9 [...]
X->>K: outcome
K->>O: I sent a message to business X: `text` Approved for this chat by Alice. /'revoke #35;9'
T-->>A: {action, status: done, chat: #35;9, item, responses, more}
O->>C: /revoke #35;9
K->>C: apiGetChat #35;9 count 0
K->>C: apiSetGroupCustomData #35;9 {other keys}
K->>O: Messages to business X (#35;9) need approval again.
Notes:
- The approval is used in mode
requestswhile memberapprovedByIdis an approver (Control.standingApprover). - For sends that were pending at
/approve CHAT all, the card ends with the plainApproved by Alice.(cardText). connectandleaveactions are created without the standing approver, so they stay pending (AgentTools.connect,leave)./receive CHAT N alland/receive CHAT offwork the same way for downloads, with the keysimplexMcpFiles, except that download N alone is performed, and the other pending downloads of the chat stay pending (standings,Control.approveChat,AgentTools.download).
Source: Control.approveChat, revoke, setCustomData, AgentTools.send, Actions.create, afterPosting, runPerform.
7. leave
sequenceDiagram
participant A as Agent
participant T as AgentTools
participant X as Actions
participant K as Control
participant C as Core
participant O as Owner
A->>T: leave {chat: #35;9}
T->>X: find(key): none
T->>C: apiGetChat #35;9 count 0
T->>X: create(key, leave fields)
K->>O: I want to leave business X (#35;9). /'approve #35;9 N' or /'reject #35;9 N'
O->>C: /approve #35;9 N
K->>X: approve(action, "Alice")
X->>T: leaveChat(#35;9)
T->>C: apiGetChat #35;9 count 0
T->>C: apiLeaveGroup #35;9 (membership current or pending)
T->>C: apiDeleteChat #35;9 full, notify
T->>T: DATA/forwarded/group-9 deleted
X->>K: outcome
K->>O: card edited: I left business X (#35;9). Approved by Alice.
K->>O: Files from business X (#35;9) are kept in `DATA/files/group-9`: K files, SIZE. /'delete #35;9 files' (when the folder has files)
T-->>A: {action: N, status: done, chat: #35;9}
Notes:
- For a contact, the card text is
I want to delete KIND NAME (@N)., and the perform step callsapiDeleteChatfor the contact, full, with notify (requestLines,AgentTools.leaveChat). - The delete notifies, so the core notifies the contact or the members (
AgentTools.leaveChat). - The server looks for an attached action before it reads the chat, so a repeated call after the deletion is attached to the done action (
AgentTools.leave).
Source: AgentTools.leave, leaveResult, leaveChat, Control.outcome, leftChatFilesNote.
8. Mode host
sequenceDiagram
participant P as Person
participant A as Agent
participant H as HTTP and SDK
participant T as AgentTools
participant X as Actions
participant K as Control
participant O as Owner
Note over P,H: the person started serve my-agent --approve host
A->>H: tools/list
H-->>A: connect, send, download, leave with _meta {"anthropic/requiresUserInteraction": true}
A->>A: Claude Code asks its user
A->>T: send {chat: @4, text}
T->>X: create: performing
X->>K: saveCounter (no card)
X->>T: performSend
X->>P: Action N: performed without approval (mode host).
X->>K: outcome
K->>O: I sent a message to bot X: `text` Performed without approval (mode host).
T-->>A: {action: N, status: done, ...}
Notes:
- New actions are still refused unless the control chat has an approver (
Control.refusal). - In mode
host,standingApproverreturnsundefined, so standing approvals are ignored bysend,download,listand/list, and/approve CHAT allstores nothing; downloads get no card, so/receive CHAT N allhas no card to act on (Control.standingApprover,ownerCommand). - A download in mode
hostis received without the approval of unknown servers, and it gets no card and no outcome post (AgentTools.downloadTo,startDownload,hasOutcomeCard). - The kept-files message also follows a done
leavein modehost(Control.outcome).
Source: AgentTools.register, Actions.create, runPerform, Control.outcome, cardText.
9. Expiry
sequenceDiagram
participant A as Agent
participant X as Actions
participant K as Control
participant O as Owner
A->>X: send call creates pending action N at T
K->>O: card N
Note over X: expires = T + expireHours, timer set for expires - now, at most 60 s
X->>X: timer fires, or expireDue before an owner command
X->>X: pending and due: expired
X->>K: outcome
K->>O: card edited: ... Expired.
X-->>A: {action: N, status: expired}
X->>X: removed with the result
O->>K: /approve N
K->>O: Action N is not pending.
Notes:
- A decided action with an open count of 0 is removed at its timer, at a later decision or at the close of its last call, once its expiry time has passed (
Actions.forgetExpired). A pending action ofservethat expires without a call stays until the next owner command, or until its check 60 s later. A repeated call before then attaches to it, and its status isexpired, as in 0.2 (Actions.expire,expireDue). - A timer waits at most 60 s, on the monotonic clock. When it fires before the expiry time, it is set again. So an action whose expiry time passes while the computer sleeps expires within 60 s after the computer wakes (
expiryCheck,Actions.expire). - Expiry times are listed in the
/pendingreply (pendingLine). - The server ends the connect wait at
created + 23 h 50 min, within the 24 hours in which a message can be edited (editWindow,AgentTools.performConnect).
Source: Actions.create, expireDue, scheduleExpiry, expire, forgetExpired, Control.ownerCommand.
10. A lost call and its re-attachment
sequenceDiagram
participant A as Agent
participant H as HTTP and SDK
participant T as AgentTools
participant X as Actions
participant O as Owner
A->>H: send {chat: @4, text: "t"}
H->>T: call
T->>X: create: pending, open 1
A->>H: closes the response stream
H->>T: ctx.mcpReq.signal aborted
T->>X: decided: false, open 0
Note over H: result discarded by the SDK
A->>T: list
T-->>A: actions: [{action: N, tool: send, input, state: pending, open: false}]
O->>X: /approve N
X->>X: perform, done, replies collected
A->>T: send {chat: @4, text: "t"}
T->>X: find(key): action N
T->>T: doneAtCall: wait counted from now
T->>X: remove(action)
T-->>A: {action: N, status: done, item, responses, more}
Notes:
- The key is made of the session number,
undefinedforserve, the tool name and the action fields (AgentTools.connect,send,leave,download,actionKey):connect:target,incognito,messagesend:chat,text,file,as,reply_to,mentiondownload:chat,itemleave:chat
- The
wait,idleandlimitof the attaching call are used (AgentTools.sendResult). - For a call aborted before
create, the server returns before it creates an action (AgentTools.connect,send,leave,download). - Abort path in the SDK: on
resclose the web request is aborted (toNodeHandler); the per-request transport is closed (PerRequestHTTPServerTransport.handleMessage); the handler signal is aborted (Protocol._onclose).
Source: AgentTools.actionResult, sendResult, listChats, Actions.decided, nextChange.
11. Shutdown with pending actions
sequenceDiagram
participant P as Person
participant S as serve.ts
participant X as Actions
participant K as Control
participant H as HTTP
participant C as Core
participant O as Owner
P->>S: Ctrl-C (SIGINT)
S->>S: stopped: events ignored
par actions
S->>X: stop()
X->>X: stopping, timer cleared, cards being posted awaited
X->>X: pending and performing: interrupted, performs aborted
X->>K: outcome of each
K->>O: pending: ... Cancelled: the server stopped.
K->>O: performing: ... Approved by Alice, interrupted: the server stopped.
and HTTP
S->>H: close, closeAllConnections (open calls aborted)
end
S->>P: Cancelled 2 actions.
S->>P: Stopping: sending 2 cancelled cards, up to 10 s. Ctrl-C to stop now.
S->>S: wait 10 s, or until a second Ctrl-C
S->>C: close
S->>S: remove DATA/lock
S->>P: Stopped.
Note over P,O: next start: counter continues, /approve of an old number: Action N is not pending.
Notes:
- The interrupted card line is
DECIDER; interrupted: the server stopped.(cardText). - An action of mode
hostor of a standing approval whose counter is being written at the stop is set topendingand cancelled without a perform (Actions.afterPosting). - After a crash, the cards of that run are left with their commands;
/approveof their numbers gets the replyAction N is not pending.(Control.ownerCommand). - The stop signal of the performs is aborted after the actions are marked interrupted: a
connectwaiting for its connection ends, and an interrupted perform logs no line (Actions.stop,runPerform,AgentTools.performConnect). - The wait applies only when cards were edited or posted at the stop, a
downloadwithout a card excluded, and--stop-waitis above 0 (stopinstartAgent,waitForCancelledCards).
Source: serve, startAgent, waitForCancelledCards, Actions.stop, stopHttp, cardText.
12. --owners setup
sequenceDiagram
participant P as Person
participant K as Control
participant C as Core
participant O as Owner Alice
participant B as Member Bob
P->>K: serve my-agent --owners
K->>C: apiCreateGroupLink #35;G observer
K->>P: The link adds an observer. Its ID and name are printed when it joins.
O->>C: joins by the link
C->>K: joinedGroupMember
K->>C: apiDeleteGroupLink #35;G
K->>P: Alice joined (member 3). Restart the server with --owners 3:Alice
K->>O: Alice joined (member 3). Restart the server with `--owners 3:Alice`
P->>K: Ctrl-C, then serve my-agent --owners 3:Alice
K->>C: apiSetMembersRole #35;G [3] owner
K->>C: apiRemoveMembers #35;G [ID], for each other human
K->>C: apiDeleteGroupLink #35;G
K->>P: Owners: 3:Alice.
K->>P: Add the agent to Claude Code: ...
O->>C: adds Bob, makes Bob an owner
C->>K: memberRole
K->>P: Bob (member 7) is now an owner and can't approve actions yet. Restart ... --owners 3:Alice,7:Bob
K->>O: same line, the --owners part as code
B->>K: /approve N
K->>B: Only the owners listed in --owners approve actions.
Notes:
- Until the restart with a list, new actions are refused:
The agent has no approving owner. ...(Control.refusal). - An entry must match a human by member ID and display name, folded to one line as the restart line prints it, or the server exits with code 2 (
Control.startListed,listsMember). - With
--reset-owners, the server deletes the control chat for all members and creates a new one with the same counter; the CLI refuses the option with an--ownerslist (resetControlChat,deleteGroup,controlGroup,serveOptions). - When a listed owner leaves and none remains:
... is no longer an owner. No owners remain: restart the server with --reset-owners --owners(Control.reportOwnerChanges).
13. download with approval
sequenceDiagram
participant A as Agent
participant T as AgentTools
participant X as Actions
participant K as Control
participant C as Core
participant O as Owner
A->>T: download {chat: #35;15, item: 30}
T->>X: find(key): none
T->>C: apiGetChat #35;15 count 0
T->>C: apiGetChat #35;15 around 30 count 0
T->>C: apiGetChatItemInfo #35;15 30: fileXftpServers
opt no servers yet
T-->>A: progress: The sender is uploading the file of item 30 in #35;15, waiting until TIME.
C->>T: rcvFileDescrReady
T->>C: apiGetChatItemInfo #35;15 30
end
T->>C: apiGetUserServers USER: no unknown servers
T->>C: apiGetChat #35;15 count 0
T->>K: standingApprover(chatInfo, files): none
T->>X: create(key, download fields)
K->>O: I want to download a file from Switchback in group Trail (#35;15): `report.pdf`, 2.4 MB, Servers: known. /'receive #35;15 N', /'receive #35;15 N all', /'forward #35;15 N' or /'reject #35;15 N'
O->>C: /receive #35;15 N
K->>X: approve(action, "Alice")
X->>T: performDownload: downloadFile
T->>C: apiGetChat #35;15 around 30 count 0
T->>C: apiReceiveFile 7 DATA/files/group-15/7.pdf
C->>T: rcvFileComplete
T->>T: a file at the download path: resolved
X->>K: outcome
K->>O: card edited: I downloaded a file from ... Approved by Alice.
T-->>A: {action: N, status: done, chat: #35;15, item: 30, path}
Notes:
- A check every 60 s reads the item: a deleted message or chat fails the download; 30 minutes without a rise of
rcvProgressfail and cancel it (AgentTools.checkDownload,currentFile). - A download still running
waitseconds after the perform starts returnsstatus: performing; the same call again attaches to the action (AgentTools.downloadResult). /approve #15 Non a download card gets the replyAction N is a download: ...with the card's command line (Control.ownerCommand).- A file on unknown servers gets a card that names their hosts and leaves out
/'receive CHAT N all'(requestLines,commandsLine,serversLine). Only such a card approves the relays; the core checks the complete description of every other download, which fails at the acceptance, or at the next check when the description completes later (AgentTools.downloadTo,checkDownload). - The card of an image or video shows the sender's preview (
Control.cardContent,fittedImage). - In a plugin session group, the core refuses a card that the group's preferences do not allow (
Control.postCardContent,sessionRefusal,postRefusal,refusedCardSubject,Actions.runPerform):- While the group's preference does not allow files and media, a card with a preview is posted as text and edited as text.
- A card refused by another preference before the decision is replaced by
Action N:and the text that names the preference. The action then fails. - The outcome card of an action performed in mode
hostor under a standing approval is posted after the decision. When it is refused, it is replaced byAction N was performed; its card was not posted:orAction N failed; its card was not posted:, and that text. - A refused edit of a card is replaced by
Action N OUTCOME; its card was not updated:and that text. OUTCOME iswas performed,failed,was rejected,expiredorended. - After the decision, the action is not changed by a refused card.
- A file the core receives without a request, a short voice message, also in a member chat of a group, is moved into the chat's folder at
rcvFileComplete; one whose transfer started before a restart, only when it has its full size. Its message then shows it asoffered, anddownloadreturns its path after the approval (AgentTools.onNewItems,onFile,onFileComplete,moveReceived,messageFile,receivedFileError).
Source: AgentTools.download to settleDownload, AgentTools.onEvent, requestLines, commandsLine.
14. /forward
sequenceDiagram
participant A as Agent
participant T as AgentTools
participant K as Control
participant C as Core
participant O as Owner
O->>C: /forward #35;15 N (on a pending download card)
C->>K: newChatItems
K->>T: forwardFile(action N)
T->>C: apiReceiveFile 7 DATA/forwarded/group-15/7.pdf
C->>T: rcvFileComplete: resolved with the forwarded path
T->>T: copy for the post: DATA/files/sent/send-XXXXXX/report.pdf
K->>C: apiSendMessages #35;G [{fileSource: the copy, msgContent: file, quotedItemId: card N when the message fits}]
C->>T: sndFileCompleteXFTP: the copy's folder deleted
Note over K,O: the card stays pending#59; the agent's message shows the file as offered
O->>C: /receive #35;15 N
K->>T: performDownload: downloadFile
T->>T: the forwarded file moved to DATA/files/group-15/7.pdf
T-->>A: {action: N, status: done, chat: #35;15, item: 30, path}
Notes:
/forwardgets no reply; a download or post that fails is posted asAction N: the file was not received: `ERROR`., and a failed post deletes the copy (Control.forward). In a plugin session group, the core may refuse the post withfeature not allowed NAME, as forFiles and mediaorVoice messages. Claude then postsAction N: NAME are off in the group of this session; its owners can turn them on in the group's preferences.- The copy is named by the name the sender gave (
AgentTools.copyForSending). - The post keeps the sender's preview of an image or video; it replies to the card when the message, with the card as its quote, is within 15602 bytes by the length rule of
send(Control.forward,fitsMessage,quoteContent). - The download is shared with the agent's: one download per file ID; the move to the download path waits for the copy of the post (
AgentTools.downloadFile,forwardFile,downloadTo). - The forwarded path is outside
DATA/files/, sosendrefuses the file there; it is deleted when the agent leaves the chat, and by/delete CHAT files(AgentTools.isRefused,deleteChatFiles,leaveChat).
Source: Control.ownerCommand, forward, AgentTools.downloadFile, forwardFile, onSentFile, deleteSentCopy, isSentCopy, copyForSending.
15. send with a file
sequenceDiagram
participant A as Agent
participant T as AgentTools
participant X as Actions
participant K as Control
participant C as Core
participant O as Owner
A->>T: send {chat: #35;15, text: "trail map", file: "/home/alice/trail.jpg"}
T->>C: apiGetChat #35;15 count 0
T->>T: real path, size, inode, change time
T->>T: refused paths checked
T->>T: preview: core.resizeImage(file, MessagePreview)
T->>T: message length checked
T->>X: create(key, send fields with the file)
K->>O: image card with the preview: I want to send a message to group Trail: `trail map`, attaching image `/home/alice/trail.jpg`, SIZE /'approve #35;15 N', ...
O->>C: /approve #35;15 N
X->>T: performSend
T->>T: the file again: same real path, size, inode, change time
T->>T: core.resizeImage(file, Image): DATA/files/sent/send-XXXXXX/trail.jpg
T->>C: apiSendMessages #35;15 [{fileSource: the copy, msgContent: image with the preview}]
C->>T: sndFileCompleteXFTP: the copy's folder deleted
Notes:
- A refused file ends the call with an error, and the refusal is posted to the control chat and logged (
AgentTools.attachment,Control.refusedFile). - A video's preview is the first frame from
ffmpegand its duration comes fromffprobe; a GIF or WebP gets the fixed preview (attachmentMedia,messagePreview,videoFrame,videoDuration). - A changed file fails the perform:
file: PATH changed after the request.(AgentTools.fileToSend). sndFileErrordeletes the copy too, and the failure is posted to the control chat and logged (AgentTools.onEvent,startAgent,Control.fileNotSent).
Source: AgentTools.send, performSend, onSentFile, deleteSentCopy, isSentCopy, attachment, isRefused, fileToSend, resizedCopy, Control.cardContent, fittedImage, requestLines.
16. /leave and /delete CHAT files
sequenceDiagram
participant P as Person
participant T as AgentTools
participant X as Actions
participant K as Control
participant C as Core
participant O as Owner
participant D as Peer
O->>C: /leave #35;9
K->>T: knownChat #35;9
K->>T: leaveChat #35;9
T->>C: apiLeaveGroup #35;9, apiDeleteChat #35;9 full, notify
C->>D: the agent left the group
T->>T: DATA/forwarded/group-9 deleted
K->>P: Left business Ridgeline (#35;9), requested by Alice.
K->>X: reject each pending action of #35;9 with a card
K->>O: Left business Ridgeline (#35;9), requested by Alice.
K->>O: Files from business Ridgeline (#35;9) are kept in `DATA/files/group-9`: 3 files, 2.1 MB. /'delete #35;9 files'
O->>C: /delete #35;9 files
K->>T: deleteChatFiles #35;9
T->>T: each download of #35;9: failed, apiCancelFile, its partial file deleted
T->>C: apiGetChat #35;9 count 100, then before the first item, while a page has 100
T->>C: apiCancelFile for each other file in rcvAccepted, rcvTransfer or rcvWarning
T->>T: DATA/files/group-9 and DATA/forwarded/group-9 deleted
K->>O: Deleted 3 files from #35;9, 2.1 MB.
Notes:
/leaveacts at once in both modes, and works for a contact asDeleted bot X (@4), requested by Alice.(Control.leave).- The line
Left ...goes to the log and to the owners; the members of #9 see only that the agent left. - The files message is posted after the reply, and only when the folder has files (
Control.leave,queueAfterReplies). /delete CHAT filesworks for a current or a left chat; the failed downloads returnYour owner deleted the files of this chat., and the reply counts the forwarded files too (AgentTools.deleteChatFiles).- The paged reads find the downloads the core continues after a restart, which have no download in memory; for a left chat they find none (
receivingFiles,AgentTools.deleteChatFiles).
Source: Control.leave, leftChatFilesNote, deleteFiles, AgentTools.chatFiles, deleteChatFiles, leaveChat.
Claude Code plugin flows
Participants of the plugin flows:
| Letter | Participant |
|---|---|
| CC | Claude Code |
| HK | a hook, node dist/cli.js hook ... in the plugin's folder |
| DH | the display hook, node dist/display.js in the plugin's folder |
| S | the session process, simplex-mcp session |
| D | the service, with its socket routes and entries |
| M | MainGroup |
| N | the Session of session N, with its Control and Actions |
| T | the session's AgentTools |
| C | the core _hub with the profile Claude |
| U | User with the core _user |
| O | an owner in the SimpleX app |
#M is the Main group, #G the group of session N, ROOT the data root.
17. First session start and the owner joins
sequenceDiagram
participant CC as Claude Code
participant HK as SessionStart hook
participant D as Service
participant M as MainGroup
participant N as Session 1
participant C as Core _hub
participant U as User
participant O as Owner
CC->>HK: {session_id, session_title, cwd, model}
HK->>D: GET /status: not running
HK->>D: spawn simplex-mcp service through a launcher, which exits at once
D->>D: lock, stored sessions, socket listens
D->>C: openCore ROOT/_hub "Claude" agent
D->>C: apiNewGroup "Claude Control", short description and welcome of trust, {simplexMcpMain: true}
M->>C: apiGetGroupLinkStr #35;M: none, apiCreateGroupLink #35;M member
D->>U: openCore ROOT/_user "User" human
U->>C: joins the hub's one-time link#59; the contact of its connection marked simplexMcpUser
D-->>HK: ready
HK->>D: POST /title {id, pid, at, name, project, model, config}
D->>D: ROOT/_sessions/ID/session.json {number: 1, name}
D->>N: Hub.session
N->>C: apiNewGroup "1 · NAME", {simplexMcpSession: {session: 1}}
N->>C: apiAddMember #35;G User
U->>C: apiJoinGroup #35;G, marked {simplexMcpSession: 1}
N->>C: apiUpdateGroupProfile #35;G shortDescr MODEL
D-->>HK: {mainGroup, owner: {owners: [], link}}
HK-->>CC: systemMessage: scan this QR code ..., QR code, link
O->>C: joins #35;M by the link
C->>M: joinedGroupMember
M->>C: apiDeleteGroupLink #35;M, apiSetMembersRole #35;M owner
M->>O: I'm Claude. Each Claude Code session has its own group ...
M->>O: Alice joined. They can join the group of any Claude Code session here, prompt Claude and approve its actions.
M->>N: inviteOwner: apiAddMemberViaGroup #35;G via #35;M, role owner
O->>C: joins #35;G from the invitation in #35;M
C->>N: joinedGroupMember
N->>O: Alice is an owner and can send prompts to Claude and the group's commands, and approve tool use.
M->>O: within 2 s, the list of sessions, silent, as in flow 36
Notes:
- Only the person gets the link. It is passed in the hook's
systemMessage, and it is in no hook context or tool result (sessionStart). - The service is spawned by a launcher,
node -e LAUNCHER COMMAND ARGS, which exits at once, so the service is no descendant of the hook. When Claude Code exits during the hook, it ends the hook and the hook's descendants, and the service keeps starting. The service drops its ready line when the hook is gone, and the next session start shows the link (launcher,spawnService,writeReady). - The Main group's name is
main_group,Claude Controlby default, followed by- MACHINEwhenSIMPLEX_MCP_MACHINEis set (readConfig,withMachine). - The service deletes the preset contact of a new profile, in
_huband in_user(openCore,deletePresetContacts). - At each start,
openCoresets the peer type of each profile:agentfor Claude andhumanforUser. In a data folder of 0.3.0,Useris changed fromagenttohumanat the first start, and the core sends the change to the hub's contact ofUserat once. Members who join a session group later gethuman; members already in a session group get it withUser's next post there, as the eventupdated profile(openCore,updatedUser,Hub.open,User.open). Userconnects only at the first start. At later starts, the service finds the hub's contact markedsimplexMcpUser, the contact whose connection belongs to the invitation that the hub created. WhenUserdoes not connect within 60 s, the service runs without it, and terminal prompts are not posted (User.open,connect,userContact,Hub.open).- At a later start without owners, the service keeps the Main group's link (
MainGroup.start). - Owners are invited to the groups of the open sessions when they join the Main group. The groups of closed sessions are joined with
/join N(Hub.inviteOwner,join). - The trust given to the Main group's members is stated in the group's short description and welcome message, which Claude sets when it creates the group (
welcome,joinRights,shortDescr,createMainGroup). Claude also states it in a post at each human'sjoinedGroupMemberorconnectedToGroupMember(MainGroup.handleEvent). The joiner is found as in flow 28. - Claude changes only the name and the menu of the Main group's profile, and starts each change from the group's current profile. So the short description, the welcome message and the preferences that owners set are kept (
MainGroup.load,updateGroupProfile,changeGroupProfile). - At each join other than
User's, Claude posts in the session group the rights of the joiner's role. For a role that can send, other than owner, the post ends with the command that makes the joiner an observer (Session.announceRights,Hub.onEvent). - The service reads the hub's contact of
UserafterUseropens, so that the sessions recognizeUser's messages (Hub.open).
Source: sessionStart, ServiceClient.ensureService, stopService, status, serviceCommand, spawnService, Service.start, onTitle, markUnattended, refuseUnattended, applyTitle, Hub.open, session, createSessionGroup, MainGroup.handleEvent, ownerJoined, User.open, post, close, connect, onEvent.
18. Session process start and attach
sequenceDiagram
participant CC as Claude Code
participant S as Session process
participant D as Service
participant N as Session N
CC->>S: node dist/cli.js session, with CLAUDE_CODE_SESSION_ID
CC->>S: initialize
S-->>CC: tools, instructions, capabilities claude/channel and claude/channel/permission
S->>D: GET /status, version and protocol
S->>D: POST /session {id, pid: parent process, project, config}
D->>D: resolve id: alias#59; id with session.json#59; session of pid, or a wait of up to 10 s for the title of pid
D->>N: configure, requestMode(approve)
D-->>S: {number, displayName, owner}
S->>D: POST /attach {id}
D-->>S: {version, protocol}
D->>N: onLine = the entry's writers
D-->>S: the /attach stream ends: the service stopped
S->>S: after 1 s, then twice as late after each failure, up to 30 s
S->>D: GET /status, spawn when none runs, POST /session, POST /attach
Notes:
- With an invalid option, or in a run that is not interactive, the session process does not connect to the service, even at a permission request of Claude Code. For every call, it returns the option's error. In a run that is not interactive, the text of flow 30 is returned instead, also with an invalid option (
startSession). - For a session without a folder, the service creates the folder at
/session, and answers/attach,/call,/permissionand/turnwith 409. After a 409 to a call, the session process registers again incalland repeats the call once (Service.openAgent,ServiceLink.call). - When the
/attachstream ends, or a connection or a spawn fails, the session process drops the connection and connects again. So the channel works again without a tool call. A single timer is set for each attempt, so the delay doubles once per failed attempt. The session process stops retrying at another protocol version, theProtocolError, and at a 403 of/session(ServiceLink.start,close,reconnect,open,ServiceClient.ensureService).
Source: startSession, ServiceLink.open, Service.onSession, onTitle, markUnattended, refuseUnattended, applyTitle, canonical, resolve, attachedSession, processSession, alias, rename, onAttach.
19. A tool call with approval in the session group
sequenceDiagram
participant CC as Claude Code
participant S as Session process
participant D as Service
participant T as AgentTools
participant N as Session N
participant C as Core _hub
participant O as Owner
CC->>S: tools/call connect {target}
S->>D: POST /call {id, tool: connect, input}
D->>T: call, signal of the request
T->>N: Actions.create, mode of the session
N->>O: card in #35;G: I want to connect to bot X, as myself. /'approve N' or /'reject N'
D-->>S: {progress: Action N waits for an approver until TIME.}
S-->>CC: notifications/progress
O->>C: /approve N in #35;G
C->>N: newChatItems: Control.onMessage
N->>T: perform: performConnect
T->>C: apiSetContactCustomData @C {simplexMcpOwner: {session: ID}}
N->>O: card edited: I connected to bot X, as myself. Approved by Alice.
D-->>S: {result}
S-->>CC: the result
Notes:
- Approvers in the session group are its active members with the role
adminorowner, other than Claude andUser, however they joined (Session.approves,isUser,Control.approvers). - Without an approver in
#G, the action is refused with the text of API 4.4. - The session's ID is set as the owner of the connected chat (
AgentTools.claim,performConnect).
Source: Service.onCall, the constructor of Session, AgentTools.connect, action, ownChat.
20. A prompt from the session group
sequenceDiagram
participant O as Member
participant C as Core _hub
participant N as Session N
participant D as Service
participant S as Session process
participant CC as Claude Code
O->>C: message in #35;G, with a file
C->>N: newChatItems: Session.onMessage
alt one-line "/" text from a moderator, member or author
N->>N: delivery = delivery then the reply
N->>O: reply: Only admins and owners of this group can send / commands.
else one-line "/" text
N->>N: Control.onMessage: from User, dropped, else a command of the group, queued
else another message
N->>N: replyTo of a reply = toReplyTo of its quote
N->>N: delivery = delivery then prompt: after the earlier messages of the session
alt from User
N->>N: nothing
else a prompt
opt no attachment, in the first 30 s after the hub opened
N->>N: wait for an attachment until then
end
opt attached, with a file
N->>C: apiReceiveFile FILE_ID ROOT/_sessions/ID/files/group/FILE_ID.EXT, relays approved
alt rcvFileComplete within 10 minutes
C->>N: rcvFileComplete: fileDone
else rcvFileError, a failed receive, or 10 minutes
N->>O: reply: The file of this message was not received: ERROR
end
end
alt no attachment now
N->>O: reply: Session N is not running.
else attached
N->>N: text = quote line of replyTo, a line break and the text, for a reply
N->>N: pushed += (text, item), at most 20
N->>D: onLine {prompt: {text, from, item, file?, replyTo?: {item?, from?}}}
D->>S: the line on /attach
S->>CC: notifications/claude/channel {content, meta: {from, item, file?, reply_to?, reply_to_from?}}
end
end
end
Notes:
- Every message of a member other than
Useris a prompt, however the member joined, except a one-line/text. Claude answers a one-line/text of a moderator, member or author withOnly admins and owners of this group can send / commands.From an admin or owner, a one-line/text is a command of the group. For one outside the group's requests, such as/model sonnet, the reply isUnknown command.(Session.onMessage,prompt,refusesCommand,approves,Control.ownerCommand,parseCommand). - The session handles messages in arrival order. So a prompt is delivered after the file of an earlier prompt. The reply to a one-line
/text of a moderator, member or author is posted after the earlier prompts (Session.onMessage,queue). - After a service start, a prompt that arrives before its session attaches again is held up to 30 s from the hub's open. So a prompt sent while the service was stopped is still delivered to the session (
Session.deliver,Hub.open). - In a session started without the channel flag, Claude Code receives the notification and drops it.
- A reply reaches Claude after a quote line,
>and the type of a quoted message other than a text and the first line of its text, up to 200 characters with…when it is cut.reply_tois the quoted item's ID when the group has it, andreply_to_fromits sender when the group knows it. The pushed prompt holds the quote line, so the channel tag of the reply matches it (Session.onMessage,deliver,toReplyTo,replyText,quoteLine,trimmed,channelNotification).
Source: Session.onMessage, prompt, deliver, receive, Service.onAttach, startSession, channelNotification.
21. A terminal prompt and the answer
sequenceDiagram
participant P as Person
participant CC as Claude Code
participant HK as Turn hook
participant T as Transcript
participant D as Service
participant N as Session N
participant U as User
participant C as Core _hub
participant O as Owner
P->>CC: prompt typed in the terminal
CC->>HK: UserPromptSubmit {session_id, transcript_path, prompt_id, prompt}, in the background
CC->>T: the prompt's entry, with origin human, after the synchronous UserPromptSubmit hooks
loop up to 600 reads, 100 ms apart, until the entry of prompt_id is found
HK->>T: read the last 1 MiB and twice the prompt's bytes, a missing file as empty
end
HK->>D: ensureService, POST /turn {id, pid, at, prompt, typed}
D->>N: turn
N->>N: end pending permissions created before at
N->>N: no pushed prompt matched: turns += (at, null), unless at is below answeredAt
N->>U: post(N, parts), when typed and not a "/" command
U->>O: the prompt in #35;G, from User
N->>C: apiSendMessages #35;G [{text: "", priority: -1}], live: the opening message, after User's post
C->>O: the opening message, from Claude, with typing dots
CC->>CC: turn ends
CC->>HK: Stop {session_id, transcript_path, prompt_id, last_assistant_message, effort}
CC->>T: the answer's entry, within about 100 ms
loop up to 20 reads, 100 ms apart, until Claude's last entry is the answer
HK->>T: read the last 1 MiB and twice the answer's bytes
end
opt the tail has no prompt entry of prompt_id
HK->>T: read the last 4, 16 and 64 MiB, until one has it
end
HK->>D: ensureService, POST /turn {id, pid, at, answer, model, effort, usage}
D->>N: turn
N->>N: end pending permissions created before at
N->>N: quote = the newest turn record before at#59; it and the older ones leave turns
N->>N: a changed model or effort, when at is not older than that of the value taken last: description, session.json
opt a known effort level changed
N->>C: apiSendMessages #35;G [{text: "!- Effort changed to LEVEL!", priority: -1}]
end
N->>N: claim: no text of Claude streamed the answer, as without the display hook (flow 37)
N->>N: available memory, and statfsSync of ROOT or its nearest existing parent
N->>N: parts = withLine(parts(answer), "!- Done in USAGE · 5 h: N% · week: N% · RAM SIZE free · disk SIZE free!")
alt the opening message of the turn was posted
N->>C: /_update item #35;G the opening message, the first part, live off, priority 1 when it is the only part
N->>C: apiSendMessages #35;G the other parts, priority -1, the last priority 1
else
N->>C: apiSendMessages #35;G parts, priority -1, the last priority 1, the first quoting the quote when it came from the group and fits with the first character
opt the core refuses the quote
N->>C: apiSendMessages #35;G parts without the quote
end
end
C->>O: the answer ending with the end line, from Claude, one alert
N->>C: apiUpdateGroupProfile #35;G shortDescr MODEL · effort LEVEL, when it changed
Notes:
-
atisperformance.timeOriginof the hook process, the hook's start time. In an answer, the hub quotes the newest prompt record whose hook started before the answer's hook. This record is quoted also when the request of the next prompt arrives first, and while the answer's request waits for the short description (turn,Session.turn,turnQuote). -
Userdoes not post a prompt that came from the group. The hub matches a pushed prompt to the terminal prompt in either case:- its item and its text are in a
<channel source="plugin:simplex:simplex" ... item="I" ...>tag of the prompt; - its text is equal to the raw prompt, and it was pushed in the last 60 s.
Matched prompts are removed from the pushed prompts, and the oldest of them becomes the item of the turn record (
promptEcho,channelPrompt,Session.turn,pushedIn). - its item and its text are in a
-
For an answer without an earlier turn record, the hub quotes the oldest pushed prompt not quoted yet that was pushed at or after the latest answer's hook start, and marks it quoted. An older prompt that no prompt request matched belongs to an earlier turn and is not quoted. The quoted prompt stays pushed, so the hub still matches it to a prompt request handled after the Stop request, and
Userdoes not post it (Session.turnQuote). -
For an empty answer, the hub removes the turn record as for any other answer. It posts nothing, and fills the turn's opening message, when one is open, with the end line, live off and silent (
Session.turn,answer). -
At a prompt that starts a turn, Claude posts the opening message: empty, live and silent. The hub keeps it before
User's post and sends it after that post, so a text or a step that arrives meanwhile waits for it. It replies to the member's prompt that the terminal prompt matched, when the quote fits. It is not posted for a prompt added to the running turn, a/command, a prompt thatUserdoes not post and that matched no pushed prompt, as Claude Code's own prompts, or a prompt whose hook started before the latest answer's hook. The turn's first post fills it: a text of Claude, a step's line, the answer's first part, or the end line of an empty answer, of a hook that started no earlier than the prompt's hook and before the next prompt's hook that starts a turn. When a group preference refuses that post, the text in its place fills the opening message. When the update fails for another reason, as after an admin deleted the opening message, the hub drops the opening message, logs the failure, updates it with⏹️ Stopped, and sends that post as a new message. That update fails without harm for a deleted message, and after a transient failure it ends the message's live state. An opening message that no post fills gets⏹️ Stoppedat the first answer of a hook that started no earlier than the next prompt's hook that starts a turn, or than its own prompt's hook while no such prompt came, at the last detach, at the hub's stop, or 23 hours after its send by the wall clock (Session.openTurn,takeOpening,fill,closeOpenings). -
The last part of a non-empty answer ends with the end line
!- Done in USAGE!after a line break. When the line does not fit in the last part, the last part's last N + 1 characters, N the line's length, move into a new last part before the line. A posted last part has priority 1, the turn's alert, and the other parts priority -1. A last part that fills the opening message, or completes a streamed text, is sent with/_update itemandpriority: 1in itsUpdatedMessage, becauseapiUpdateChatItemtakes no priority; a core without update priority ignores the key and keeps priority -1. The chat list shows the answer, not the end line. USAGE is the Stop hook's usage text, such as2 min 51 s · 16K output tokens · 673K tokens in context. Without it, the line has DURATION, the time from the newest turn record not added mid-turn to the Stop hook's start, asdurationformats it, and the line is!- Done!without such a record. The plan's usage of the newest status line report follows, as· 5 h: N% · week: N%, without a window whose reset time has passed (flow 38). Last come the free memory and the free disk of the data folder's volume on the service's machine, read when the Stop request is handled, as· RAM 12 GB free · disk 3.4 GB free❗️, each followed by❗️below 5% of the memory or 5 GB of disk, inside the small-print span (Session.turn,answer,postAnswer,endLine,withLine,small,Hub.machine,machineState,machineParts,duration). -
No turn record is made for a prompt request whose hook started before an answer that was already handled. So that prompt is not quoted in a later answer (
Session.turn). -
The UserPromptSubmit hook runs for every prompt of the session that queries the model, also for Claude Code's own prompts. It marks a prompt as typed only when the prompt's record in the transcript has the origin
human. Task notifications, messages of other sessions and channel prompts have other origins. The record is the newest one whose text is the prompt: a user entry, or aqueued_commandattachment of a prompt that Claude Code added to a running turn. It is the entry withprompt_idaspromptId, or a record after the first entry with that ID, tool results included, so a long turn whose first entry is out of the tail is found by its tool results. While aqueue-operationenqueueentry with the prompt's text follows the record, the hook waits: the prompt is a later one with that text, still queued. Claude Code writes the entry only after the synchronous UserPromptSubmit hooks end, such as a slow hook in the user's settings, and it creates the transcript file with the session's first entry. So the hook reads the transcript up to 600 times, 100 ms apart, and it treats a missing file as empty. Until the entry withprompt_idis in the tail, the hook waits for it; at the last read it takes any record with the prompt's text, and withoutprompt_idit does so at once. Claude Code runs the hook of a person's prompt when it is submitted, and of its own prompts only when they are taken. So at the last read, the hook classifies a record still followed by such anenqueueentry by the record, and marks a typed one mid-turn: the queued prompt is the typed prompt itself, or a later prompt with the text of Claude Code's own prompt, as a repeated monitor event. When no record is written within the reads, anenqueueentry with the prompt's text after the entry withprompt_id, or anywhere without that entry, makes the prompt typed and mid-turn. Otherwise the prompt is typed when an entry withprompt_idhas the originhuman(promptReads,transcriptReadMs,turn,promptKind,findInTranscript,promptRecord,isPrompt,recordText,recordKind). -
Claude Code adds a prompt that arrives during a turn to that turn, and gives its hook the running turn's prompt ID. The hook sends
midTurn: truefor a prompt whose record is not the entry withprompt_id. A mid-turn prompt ends no tool-use card. A prompt adds a turn record only when its hook started no earlier than the hook of the last answer handled (answeredAt), and a mid-turn prompt only when it also matched a pushed prompt. So the answer of the turn quotes the turn's prompt, or an owner's prompt added to the turn (Session.turn). -
The hook sends
note, a line about one of Claude Code's own prompts, and Claude posts it without a quote, silent (recordKind,noteOf,taskNote,teammateNote,idleNotification,peerName,shortened,Session.turn). A typed prompt, a channel prompt and a teammate's prompt of idle notifications only have no note, nor has another record without origin that is not scheduled. The line is cut to 200 characters and ends with…. A note that a group preference refuses is replaced byClaude's note was not posted:and the preference's text.Kind Record Line task notification origin task-notification, or aqueued_commandattachment without origin whosecommandModeistask-notificationan emoji, the first line of <summary>, and:with the first line of<event>when there is one, with entities decoded. The emoji is ✅ for<status>completed, ❌ for failed, ⏹️ for stopped or killed, and without a status 📡 with an event or 🔔 without. Without a<task-notification>block: 🔔 and the first linemessage of another session origin peer✉️ Message from NAME:and the first line ofbodymessage of a teammate no origin, a <teammate-message teammate_id="NAME" ...>tag afterAnother Claude session sent a message✉️ Message from NAME:and the tag'ssummary, or the first line of the message, from the first tag that is not an idle notification; nothing for idle notifications onlysubagent report origin peerwithhandback📋 Report from subagent NAME:and the first line ofhandbackReportText, or ofbodyscheduled prompt no origin, turnOriginscheduled⏰ Scheduled prompt:and the first lineautomatic prompt origin auto-continuation🔄 Automatic prompt:and the first lineanother kind another origin ⚙️ Claude Code:and the first line -
These terminal prompts are not posted (
Session.turn):- a prompt with
typed: false, such as a notification of a background task. A request withouttyped, from an older plugin, is posted as typed; - a blank prompt, which Claude Code sends for a prompt with images only;
- a prompt made only of this plugin's channel tags, as after the pushed prompts were lost in a service restart;
- a one-line
/command, such as/compact.
- a prompt with
-
An answer and a terminal prompt are posted in parts. Each part is the longest run of whole characters that fits in one message, as
sendmeasures it, and the first part of an answer is measured with its quote. The hub searches each part among the next 15602 characters. No command reply is posted to a part thatUserposts and that starts with/(Session.turn,answer,postRefusal,textParts,fitsMessage,Control.onMessage). -
When the core refuses the quote of an answer with
invalidQuoteorchatItemNotFound, as for a deleted prompt, Claude posts the answer without the quote. It does the same when the core refuses the message with the quote as too large, withlargeMsg. Claude also posts these replies without the quote in the same cases (Session.post,isRefusedQuote):Session N is not running.The file of this message was not received: ERROR- the reply to a one-line
/text of a moderator, member or author - the opening message of a turn
-
When the core refuses an answer or a terminal prompt with
feature not allowed NAME, Claude posts a text in its place, and the turn goes on (Session.turn,answer,postRefusal,notAllowedForUser). NAME is, for example,SimpleX linksfor a SimpleX link while that preference is off. A prompt ofUseris also refused while the preference is on only for roles above that ofUser. The texts are:- for an answer,
Claude's answer was not posted: NAME are off in the group of this session; its owners can turn them on in the group's preferences., quoting the turn's prompt as the answer would, with the end line on its next line and priority 1. When the answer's first part would fill the turn's opening message, this text fills it in place of a post, or⏹️ Stoppeddoes, without the end line, when that update fails too; - for a terminal prompt,
User's prompt was not posted: NAME are not allowed for User in the group of this session; its owners can allow them in the group's preferences.
- for an answer,
-
The hook cuts a prompt or an answer over 250,000 characters at that length and appends
…, so that the request fits within the socket's limit of 1 MiB (maxText,cut). -
A card of a tool use that started after the hook stays pending, because the hook's start time
atis earlier than the card's creation (turn,Session.endPermissions). -
The Stop hook sends the model of its answer and the usage of its turn (
answerReads,transcriptReadMs,transcriptTailBytes,usageTailBytes,syntheticModel,turn,answerRecord,findInTranscript,readTail,lastAnswer,turnUsage,usageOf,tokenCount):- The model is the
message.modelof Claude's last entry in the transcript, an entry of typeassistantwithoutisSidechain. It is taken once the text of that entry is equal to the answer. - Only the end of the transcript is read, 1 MiB plus twice the answer's size in bytes. The hook reads it up to 20 times, 100 ms apart, as Claude Code writes the transcript every 100 ms.
- No model and no usage are sent for the model
<synthetic>, for an answer without text, for an emptytranscript_pathor an unreadable transcript, and when the answer's entry is not written within the reads. - The usage runs from the turn's first entry, the first user entry with the hook's
prompt_idthat is not a tool result, to the answer. When the tail of the answer's read lacks that entry, the hook reads the last 4, 16 and 64 MiB, until one has it. It sums the output tokens of the distinct responses of the main conversation after that entry, and takes the context tokens of the answer's response. No usage is sent withoutprompt_id, for an answer withoutmessage.usageortimestamp, and when the entry is not in the last 64 MiB.
- The model is the
-
PostModelSwitch sends
{id, pid, at, model, switched: true}, witheffortwhen the hook's input has it (turn). When the model differs from the shown one, Claude posts!- Model changed to MODEL!, silent, and the hub writes the model tosession.jsonand updates the short description (Session.turn). -
A known effort level that changes, from the Stop hook, a tool hook or the status line command, gets
!- Effort changed to LEVEL!, silent, before the other posts of its request. Once the status line command reports, only its level counts (flow 38). The first model and the first effort level of a session get no line. -
An answer's model equal to the shown model without a final
[1m]keeps the shown model, as the transcript names the 1M context variant without that suffix, so the first answer after a start withX[1m]changes no description. -
The hub takes a model or an effort level only from a request whose
atis not older than theatof the value it took last. It keeps the two times apart, one for the model and one for the effort level. The model of a/titlecomes with theatof its SessionStart hook, so a hook that started during the wait of a held title keeps its model (flow 27). A request withoutatcounts as the current time. So when a Stop request that waited for its transcript entry arrives after a later PostModelSwitch request, the model of the switch stays (Session.newer). -
For a Stop request with a changed model or effort, the hub posts the answer before it updates the short description. So the prompt of a request handled meanwhile is posted after the answer. The description is updated also when a post fails (
Session.turn). -
A turn hook starts the service when none runs. It repeats a turn refused with 409 up to 15 times, 1 s apart, which is longer than the 10 s wait of a held title. It prints
{}and logs errors on its stderr (turn). Claude Code gives a hook withouttimeout600 s, more than the 60 s of a prompt's reads, the 2 minutes of a compaction's reads of flow 35 and the 15 s of repeats.
Source: the UserPromptSubmit, Stop and PostModelSwitch entries of hooks, Session.turn, turnQuote, answer, postRefusal, post, textParts, User.post.
22. A tool use approved in the session group
sequenceDiagram
participant CC as Claude Code
participant S as Session process
participant D as Service
participant N as Session N
participant O as Owner
CC->>S: notifications/claude/channel/permission_request {request_id, tool_name, description, input_preview}
CC->>CC: the terminal dialog stays open
S->>D: POST /permission {id, requestId, toolName, description, inputPreview}
D->>N: permission
N->>O: card in #35;G: I want to use `Bash`: `DESCRIPTION`, preview, /'approve N', /'approve N all' or /'reject N'
O->>N: /approve N
N->>N: performing
N->>D: onLine {permission: {requestId, behavior: allow}}
D->>S: the line on /attach
S->>CC: notifications/claude/channel/permission {request_id, behavior: allow}
N->>N: done, removed
N->>O: card edited: ... Approved by Alice.
Notes:
- On
/reject N, the session pushesdeny, and the card ends withRejected by NAME.(Session.permission). - The first answer, in the terminal or in the group, applies. The last line of a card that is still pending becomes
Ended.at an answer, or at a prompt that is not mid-turn, whose hook started after the card was created, and when the last attachment of the session ends. A prompt that Claude Code adds to the running turn ends no card (Session.turn,endPermissions,Service.onAttach,cardText). - The input preview is cut to fit the card (
Control.refusal,fittedLines). - The card is posted in mode
requestsalso for a session in modehost(Session.permission). /approve N allalso approves the tool for the rest of the session, see flow 34.
Source: the notification handler of startSession, ServiceLink.permission, the POST /permission route of Service.routes, Session.permission, requestLines.
23. Mode host for a session
sequenceDiagram
participant S as Session process
participant D as Service
participant N as Session N
participant O as Owner
S->>D: POST /session {config: {approve: host}}
D->>N: requestMode(host): requested = host
alt the group has no approver
O->>N: joins #35;G as an admin or owner, or gets one of these roles: membership event, Control.onEvent, announceRights, askMode
end
N->>O: card in #35;G: I want to run in mode host ... /'approve N' or /'reject N'
O->>N: /approve N
N->>N: perform: setMode(host), mode host in the custom data of #35;G
N->>O: card edited: I run in mode host ... Approved by Alice.
S->>D: POST /session {config: {approve: requests}}
D->>N: requestMode(requests): a pending mode card ends with Ended.#59; at once, mode requests in the custom data of #35;G
Notes:
- At most one
modecard is pending at a time. After a card is rejected or expires, the request is forgotten until the next/session(Session.askMode). - When a card is rejected, the hub sets
hostDeclinedinsession.json. While it is set, no card is posted for a/sessionrequest ofhost, also after a service restart. It is cleared at a/sessionwithrequests(the constructor ofSession,Session.requestMode,askMode,declineHost). - When the session opens, the approved mode is read from the custom data of
#G, and isrequestswhen none is stored. No mode is stored insession.json(the constructor ofSession,Session.setMode). - An idle session is closed also while a
modecard is pending (Session.busy). - The session process marks the action tools for Claude Code's confirmation by the option read at its own start, before the owner decides (
startSession).
Source: Session.requestMode, askMode, setMode, declineHost, store, Hub.onEvent, AgentTools.perform.
24. /give
sequenceDiagram
participant O as Owner
participant K as Control of session 1
participant T as AgentTools of session 1
participant C as Core _hub
O->>K: /give @4 2 in the group of session 1
K->>T: agentChat @4: a chat of session 1
K->>K: session 2 has an ID
K->>T: giveChat @4 ID2
T->>C: apiSetContactCustomData @4 {simplexMcpOwner: {session: ID2}}
K->>K: pending actions of @4 with a card rejected by Alice
K->>O: Gave bot X (@4) to session 2.
Source: Control.give, AgentTools.giveChat, Hub.sessionId.
25. reset-owners
sequenceDiagram
participant P as Person
participant R as reset-owners
participant D as Service
participant M as MainGroup
participant N as Sessions
participant O as Owner
P->>R: npx -y @simplex-chat/mcp@VERSION reset-owners in a terminal
R->>D: POST /reset-owners
D->>M: replace, also while owners exist
M->>O: the Main group deleted for all its members
M->>M: a new Main group with a link
Note over M,N: the session groups and the roles of their members stay as they are
D-->>R: {link}
alt on a terminal
R-->>P: "Claude Control" was replaced. Join the new one in the SimpleX app. The link works once:, QR code, link
else without a terminal, as by Claude's tools
R-->>P: "Claude Control" was replaced. Run npx -y @simplex-chat/mcp@VERSION link in a terminal to see the link to the new one.
end
Notes:
- VERSION is the plugin's version, so that the command runs the service's version (
linkCommand,resetCommand). reset-ownersreplaces the group at once, also while owners exist, without their approval. On a terminal, it prints the new link with a QR code. Without a terminal, it names thelinkcommand instead, so the link is never in Claude's context (resetOwnersText,resetOwners,Hub.resetOwners).- The members who joined the session groups from the old Main group stay there with their roles and the rights of those roles (
Session.approves).
Source: MainGroup.replace.
26. Idle close, idle stop and a newer version
sequenceDiagram
participant S as Session process
participant D as Service
participant N as Session N
participant S2 as Session process of a newer plugin
S->>D: the /attach stream ends with Claude Code
D->>N: onLine = undefined, endPermissions, endLive: steps, opening messages and texts ended
D->>D: idle timer, 10 min
D->>N: no call, no action in memory: entry closed, open false
D->>D: no entry: stop timer, 10 min
D->>D: stop: actions cancelled, cards edited, cores closed, lock released
S2->>D: GET /status: version lower than its own
S2->>D: POST /stop
S2->>D: spawn a service of its version
Notes:
- The service cancels the stop timer when it creates an entry for a call or an attachment (
Service.entry). - A service of a higher version is kept. When the service speaks another protocol version, clients fail with
Restart Claude Code to update the SimpleX plugin.(ServiceClient.ensureService).
Source: Service.shutdown, onAttach, scheduleIdle, scheduleStop, Hub.stop.
27. /clear, --continue and /resume in one session
Claude Code keeps the session server's CLAUDE_CODE_SESSION_ID from its spawn. After /clear and /resume, it gives the hooks a new session_id. With --continue, it may spawn the server with a startup ID other than the resumed one. The hooks send CLAUDE_PID, and the session server sends its parent process. Both are the same Claude Code process.
sequenceDiagram
participant CC as Claude Code, process P
participant S as Session process
participant HK as Hooks
participant D as Service
participant N as Session of A
Note over CC,N: /clear in session A, the server attached as A
CC->>HK: SessionStart {session_id: B, source: clear}, CLAUDE_PID P
HK->>D: POST /title {id: B, pid: P}
D->>D: B unknown#59; entry A has pid P and is attached: alias B to A, in A's session.json
D->>N: rename, model
HK->>D: POST /turn {id: B, pid: P, answer}
D->>N: turn, posted in A's group
Note over CC,N: claude --continue: the server spawned with startup ID X, the resumed session R
CC->>S: CLAUDE_CODE_SESSION_ID X
S->>D: POST /session {id: X, pid: P}
D->>D: X unknown, no folder: wait up to 10 s for a /title of P
CC->>HK: SessionStart {session_id: R, source: resume}, CLAUDE_PID P
HK->>D: POST /title {id: R, pid: P}
D->>D: the session of R opened, the title of P recorded
D->>D: the wait of X ends: alias X to R
D-->>S: {number of R}
S->>D: POST /attach {id: X}: the entry of R
Note over CC,N: /resume R2 in session A, R2 with its own session.json
CC->>HK: SessionStart {session_id: R2, source: resume}, CLAUDE_PID P
HK->>D: POST /title {id: R2, pid: P}
D->>D: R2 has session.json#59; entry A has pid P and is attached: A, without an alias
HK->>D: POST /turn {id: R2, pid: P, answer}
D->>N: turn, posted in A's group
Note over CC,N: later, claude --resume R2 in process Q
S->>D: POST /session {id: R2, pid: Q}
D-->>S: {number of R2}: its own group and chats
Note over CC,N: the title of a new ID F before the server of P registers, as with --fork-session or /clear during a re-attach
HK->>D: POST /title {id: F, pid: P}
D->>D: F unknown, no session of P: title of P = F#59; the title is held
D-->>HK: the reply
S->>D: POST /session {id: A, pid: P}
D->>D: A has session.json: A#59; the held title resumes: entry A has pid P: alias F to A
D->>N: rename, model
Notes:
- The service maps a process to the session of its session server while the server is attached, and for 10 s after it detached. It maps a process to the session of its title for 10 s. So a new Claude Code process with a reused PID later starts its own session (
Service.processSession). - The service gives an alias only to an ID without
session.json. A hook of an ID withsession.jsongoes to the session attached from its process, without an alias, or else to its own session. A session server with such an ID registers its own session (Service.resolve). - The service answers a title of a new ID from a process without a known session at once, and holds the title. It applies the title when the session server of that process registers, or after 10 s without one. In the second case, the service opens a session of its own for the title's ID. So after
/clearduring the re-attach of a session server after a service start, and after--fork-sessionin either order, the new ID is joined to the session that the server registers (Service.onSession,onTitle,markUnattended,refuseUnattended,applyTitle,processEvent). - When a session is created for an ID, the existing aliases of that ID are written to its first
session.json(Service.openAgent). - Turn hooks of an ID whose title is held get 409, and repeat the turn as in flow 21 (
turnAttempts). - A second title of a process whose title is held is held too. So after two
/clearwithin the wait, both new IDs are joined to the session that the server registers. At a stop, the service saves the held title requests inROOT/titles.json, each with itsat, and at its next start it takes them as new titles (Service.start,shutdown,onTitle). - Aliases are read from
session.jsonat the service's start, so the service routes later hooks and calls with B or X to the same session (the constructor ofService,Service.alias). - Without
CLAUDE_PID, before Claude Code 2.1.214, a new session server waits the 10 s and then registers its own ID.
Source: sessionStart, turn, claudePid, startSession, Service.onSession to alias.
28. A member joins the Main group and a session's group, and a person is added to it
sequenceDiagram
participant A as Owner Alice
participant B as Bob
participant G as Carol
participant C as Core _hub
participant M as MainGroup
participant N as Session N
A->>B: a group link of #35;M, or an invitation of a contact
B->>C: joins #35;M
C->>M: connectedToGroupMember, or joinedGroupMember by the hub's link
M->>C: apiListMembers #35;M: Bob a current member
M->>B: Bob joined. They can join the group of any Claude Code session here, prompt Claude and approve its actions.
B->>M: /join N in #35;M
M->>N: Hub.join: role admin, or owner for an owner of #35;M
N->>C: apiAddMemberViaGroup #35;G via #35;M, role admin
M->>B: Sent you an invitation to "N · NAME".
B->>C: joins #35;G
C->>N: joinedGroupMember: Control.onEvent, announceRights, askMode
N->>B: Bob is an admin and can send prompts to Claude and the group's commands, and approve tool use. You can change role to observer to stop it: /'observer #35;G ID'
A->>G: a group link of #35;G with role member, or an invitation of a contact with a role
G->>C: joins #35;G
C->>N: connectedToGroupMember: Control.onEvent, announceRights, askMode
N->>B: Carol is a member and can send prompts to Claude ... You can change role to observer to stop it: /'observer #35;G ID'
G->>C: a message in #35;G, /pending, /!ls
C->>N: newChatItems: Session.onMessage, a prompt of Carol
N->>G: to /pending: Only admins and owners of this group can send / commands.
N->>G: to /!ls: Only admins and owners of this group can send / commands.
A->>C: Carol's role set to admin in the app
C->>N: memberRole: Control.onEvent, announceRights, askMode
N->>A: Carol is an admin and can send prompts to Claude and the group's commands, and approve tool use. You can change role to observer to stop it: /'observer #35;G ID'
A->>N: /observer #35;G ID of Carol
N->>C: apiSetMembersRole #35;G [ID] observer, apiListMembers #35;G
N->>A: Carol is an observer and can't send messages.
Note over G,C: Carol's app refuses to send as an observer
Note over A,N: Bob leaves #35;M, is removed from it, or gets another role there
C->>M: leftMember, deletedMember or memberRole in #35;M
M->>C: apiListMembers #35;M#59; the session groups stay as they are
Notes:
-
A member's rights depend on the member's role in the session group, not on the way the member joined or on the member's role in the Main group. Admins and owners approve and send the group's
/commands. The session groups stay as they are at changes in the Main group (Session.invite,approves,MainGroup.handleEvent). -
With
/join N, a member of the Main group gets an invitation as an admin, and an owner of the Main group as an owner (Hub.join). -
When a member of the group changes a member's role, the core raises
memberRole, and Claude posts the new rights. For a role change by Claude, as with/observer, the core raises no event, and Claude states the observer's rights in its reply to/observer(Session.announceRights,Control.setObserver,rightsText). -
/observer #G IDis accepted from a sender whose role is admin or owner and not below the member's role, as SimpleX requires for a role change. Only a current member's role changes (Control.setObserver,memberCurrentOrPending):- For a member with the status
pending_approvalorpending_review, Claude repliesNAME's role can't be changed. No member ID in this group.is the reply for a member who is neither current nor pending, such as an invited member who has not joined.
After the role change, the members are read again. So the standing approvals that the new observer gave are not counted while that member is not an admin or owner. They stay in the chat's custom data and are counted again when the member becomes one again (
Control.standingApprover). - For a member with the status
-
Claude finds the joiner of the Main group's post among the refreshed members, because in
connectedToGroupMemberthe member's status is the one before the connection. The post is made only for a human joiner (MainGroup.handleEvent). -
Claude posts nothing when
Userjoins a session group or when its role changes (Session.announceRights,isUser). -
One post is made for each join. For each connection, the core raises one of two events:
joinedGroupMemberfor a member who joined through the hub, by its invitation or link;connectedToGroupMemberfor a member whom another member added.
The end-to-end test counts one post for each join in both groups (test/e2e/service.test.ts).
-
A person added to the group directly has the rights of the role that the adding member set, as a member from the Main group has the rights of its role (
Session.prompt,approves). -
Claude answers
/join Nfrom a member of the group of session N withYou are a member of "N · NAME".(Hub.join). -
At a reset of the owners, the session groups and their members stay as they are (flow 25).
Source: MainGroup.command, handleEvent, Session.invite, announceRights, Hub.join, onEvent, Control.setObserver, canSend, rightsText.
29. reply
sequenceDiagram
participant CC as Claude Code
participant T as AgentTools
participant N as Session N
participant C as Core _hub
participant A as Owner Alice
CC->>T: reply {file, text}
T->>T: the file checked, and its message with the caption and the preview by fitsMessage
T-->>CC: too long: text: too long for a message with this TYPE#59; shorten it.
T->>C: apiSendMessages #35;G with the file, its caption and its preview
alt the group's preference for files and media allows the files of Claude's role
C-->>T: the sent item
T-->>CC: {item}
else it does not
C-->>T: error: feature not allowed Files and media
T-->>CC: Files and media are off in the group of this session#59; its owners can turn them on in the group's preferences.
end
A->>C: the group's preferences changed in the app
N->>C: a later profile update of #35;G, for the model or the name: apiGetChat #35;G count 0
N->>C: apiUpdateGroupProfile #35;G, the current profile with Claude's fields changed
Notes:
replycreates no action and posts no card, in both modes. It is not an action tool, so Claude Code does not ask before it either (AgentTools.reply,sendFile,replyTool).- The core checks the preference at the send, by the sender's role. Only owners change the preference.
- At each profile update of
#G, Claude sends the whole profile. It starts each update from the group's current profile in the chat database, and changes only the name, the short description and the commands. So the owners' preferences are kept (Control.load,rename,describe,updateProfile,updateGroupProfile,changeGroupProfile).
Source: AgentTools.reply, sendFile, call, the replyChat of the Session constructor, updateGroupProfile, changeGroupProfile.
30. A run that is not interactive
sequenceDiagram
participant CC as Claude Code, claude -p
participant HK as Hooks
participant S as Session process
participant D as Service
Note over CC,D: claude -p or the Agent SDK: CLAUDE_CODE_ENTRYPOINT sdk-cli, sdk-ts or sdk-py for the hooks and the server
CC->>HK: SessionStart, UserPromptSubmit, Stop
HK-->>CC: {}, without a request
CC->>S: tools/call
S-->>CC: This Claude Code run is not interactive, so it has no SimpleX group ...
Note over CC,D: claude -p from a command of a VS Code session: entrypoint claude-vscode#59; the hooks get ATTENDED 0 and CLAUDE_PID P, the server ATTENDED 1 and the parent process P
CC->>HK: SessionStart
HK->>D: ensureService, POST /title {id, pid: P, project, config, unattended: true}
D->>D: marks of 10 s ago and older removed#59; P marked#59; a /session of P waiting for its title ends its wait
HK-->>CC: {}
S->>D: POST /session {id, pid: P}, before or after the mark
D-->>S: 403
CC->>S: tools/call
S-->>CC: This Claude Code run is not interactive, so it has no SimpleX group ...
CC->>HK: UserPromptSubmit, Stop
HK-->>CC: {}, without a request
Notes:
- Claude Code sets
CLAUDE_CODE_ENTRYPOINTfor its hooks and its MCP servers. The value issdk-cliforclaude -p, andclifor an interactive session. The Agent SDK setssdk-tsorsdk-py. Claude Code keeps an entrypoint already in the environment, exceptcli. So aclaude -prun started by a command of a VS Code or desktop-app session keepsclaude-vscodeorclaude-desktop. - For its hooks, Claude Code sets
CLAUDE_CODE_SESSION_ATTENDEDto1or0, and to0for a run nobody attends. Its MCP servers get the variable only from the environment of the command that started Claude Code. In the run recorded with Claude Code 2.1.319 inclaude-p-runs.jsonl, the hooks got0and aCLAUDE_PIDequal to the server's parent process. The server got the parent session's1andCLAUDE_PID. - The service checks the mark before and after the wait of
/sessionfor the title of its process. So the session server is refused whether its/sessionarrives before or after the hook's mark. A mark is valid for 10 s, and after that it is removed at the next mark (Service.onSession,markUnattended,refuseUnattended). - A refused server answers every call with that text, relays no permission request and does not register again (
ServiceLink.connect,start,permission,call,open). - A hook without
CLAUDE_PIDsends no mark. A failed mark is logged asSimpleX MCP session start(markUnattended).
Source: unattendedEntrypoints, interactiveEntrypoint, interactive, sessionStart, turn, Service.onTitle, markUnattended, refuseUnattended, startSession.
31. A prompt of Claude Code
sequenceDiagram
participant CC as Claude Code
participant HK as UserPromptSubmit hook
participant T as Transcript
participant D as Service
participant N as Session N
participant O as Owner
Note over CC,O: at a turn's start
CC->>HK: {prompt_id of the new turn, prompt: a task notification}
CC->>T: the prompt's entry, origin task-notification
HK->>T: the entry with prompt_id whose text is the prompt
HK->>D: POST /turn {prompt, typed: false, note}
D->>N: end tool-use cards created before at#59; turns += (at, null), unless at is below answeredAt
N->>O: Claude: ✅ Background command "Build" completed (exit code 0)
Note over CC,O: during the turn
CC->>HK: {prompt_id of the running turn, prompt: a task notification}
CC->>T: a queued_command attachment with the prompt and its origin
HK->>T: the attachment after the entry with prompt_id
HK->>D: POST /turn {prompt, typed: false, note, midTurn: true}
D->>N: cards stay pending, and a turn record needs a matched pushed prompt
N->>O: Claude: ❌ Background command "Lint" failed with exit code 1
CC->>D: Stop hook: POST /turn {answer}
N->>O: Claude: the answer, without a quote, ending with !- Done in DURATION!, important
Notes:
- The note is posted before the answer of its turn, in the order in which the hooks' requests arrive. The UserPromptSubmit hook of a turn starts before its Stop hook (
Session.turn). - A mid-turn prompt ends no tool-use card. A prompt adds a turn record only when its hook started no earlier than the hook of the last answer handled (
answeredAt), and a mid-turn prompt only when it also matched a pushed prompt, an owner's prompt from the group. So the answer quotes the turn's prompt, or an owner's prompt added to the turn (Session.turn,turnQuote). - A person's prompt typed during a turn runs its hook at once. Its record is written later, as a
queued_commandattachment when Claude Code adds it to the running turn, or as the entry of the next turn.Userposts it as typed and mid-turn (promptRecord).
Source: promptKind, promptRecord to peerName, firstLine to shortened, Session.turn.
32. The steps of a turn
sequenceDiagram
participant CC as Claude Code
participant HK as Tool hooks, async
participant D as Service
participant N as Session N
participant C as Core _hub
participant O as Owner
CC->>HK: PreToolUse {tool_use_id, tool_name: Bash, tool_input: {command, description}, cwd}
HK->>D: POST /turn {id, pid, at, effort, step: {id, text: "💻 Run the tests"}}
D->>N: turn, the step's id not finished
N->>C: apiSendMessages #35;G [{text, priority: -1}], live
N->>N: steps += (id, at, text, the promise of the item's ID)
C->>O: Claude: 💻 Run the tests, live, silent
CC->>HK: PostToolUse {tool_use_id, duration_ms: 2018}
HK->>D: POST /turn {step: {id, text: "!- 💻 Run the tests 2.0 s!", end: true}}
D->>N: turn, steps -= id
N->>C: apiUpdateChatItem #35;G item, the final text, live off
C->>O: the line updated, without an edited mark
CC->>D: Stop hook: POST /turn {answer}
N->>N: endSteps(at), each step started before at and still without an end
N->>C: apiUpdateChatItem #35;G item, the step's own text, live off
N->>C: apiSendMessages #35;G the answer's parts, the last ending with "!- Done in DURATION!" with priority 1, the others with priority -1, unless a text of Claude streamed it (flow 37)
Notes:
- The tool hooks send a step for each tool use of the main conversation, with the text of API 4.8, and nothing for a tool use of a subagent or of this plugin, or without
tool_use_idortool_name(turn,stepOf,stepText,displayPath,duration). The hook processes load only the hook's modules: the CLI imports the server, the service and the session server when it runs them (main). - The hooks run in parallel processes, so the end of a step can arrive before its start: in a recorded
claude -prun, the two hooks offalsestarted 58 ms apart. The hub posts an end without a known step as a silent message and keeps its ID among the finished IDs. For the start that arrives later, the hub finds the ID there, removes it and posts nothing (Session.step). - Claude Code runs no end hook for a tool use refused at approval. At an answer or a prompt that is not mid-turn, the hub updates each line still live whose hook started before that request's hook, with its own text and live off, and keeps its ID among the finished IDs; at the last detach and at the hub's stop, it updates every line still live. The hub then posts nothing for the step's later end. A prompt added to the running turn leaves the lines live (
Session.turn,endSteps,Hub.stop,Service.onAttach). - The hub keeps the IDs of the last 100 finished steps, the oldest dropped first (
maxFinished,Session.remember). - SimpleX allows edits of a message for 24 hours, and a step can wait longer, as for an approval. So 23 hours after the send of its start, by the wall clock, the hub updates a line still live with its own text and live off, without keeping its ID among the finished IDs; the step's later end is posted as a new silent line. For a line that fills the turn's opening message, that send is the opening message's. Timers run on the monotonic clock, which stops while the computer sleeps, so the hub checks the ages every minute while a step, an opening message or a text is live, and before each step. A computer that sleeps through the whole hour from 23 to 24 hours after a start leaves that line live (
liveLineMs,stepCheckMs,Session.step,endStep,expireLive,watchLive). - A start that a group preference refuses is replaced by
Claude's note was not posted:and the preference's text, once, and the hub posts nothing at its end. A start that fails for another reason is logged, and the hub posts nothing at its end. A failed update of a line is logged, and the hub posts nothing more for that step (Session.startLine,endStep). - The hub keeps every started update of a line in one promise, so its stop waits for the updates that the end of the steps at the last detach started before the core closes (
Session.finalizing,endSteps,endStep). - The steps and the finished IDs are kept in memory. When the service stops during a step, the hub's stop updates its line with its own text; after a crash, the line stays live. The step's end reaches the next service and is posted as a new silent line (
Hub.stop). - The tool hooks send
effortas the other turn hooks do; the hub takes it by the hook's start time, as in flow 21. - A core without message priority ignores
priority, and an app without silent messages alerts for each line when it is posted. An update of a live message sends no SMP notification. - The hub sends a step's line after the text work queued before the step's request, so the line follows the texts whose batches arrived first. A step's line that is the turn's first post fills the turn's opening message (flow 37).
Source: turn, stepOf, stepText, displayPath, duration, Session.turn, endPermissions, endSteps, answer, step, startLine, endStep, expireLive, remember, Service.onAttach.
33. A reaction in the session group
sequenceDiagram
participant O as Member
participant C as Core _hub
participant N as Session N
participant D as Service
participant S as Session process
participant CC as Claude Code
O->>C: 👍 to a message in #35;G
C->>N: chatItemReaction: Session.onReaction
alt removed, from an observer, a relay or User, or to an item that is not a message
N->>N: nothing
else not one of the apps' eight emoji, replied before for this member and message, or to the reply below
N->>N: nothing
else not one of the apps' eight emoji
N->>N: refusedReactions += (member, message)
N->>N: delivery = delivery then the reply, after the earlier messages of the session
N->>O: reply to the reacted message: This reaction is not supported.
else one of the apps' eight emoji
N->>N: replyTo = toReplyTo of the reacted item, with its file name for an empty text
N->>N: delivery = delivery then prompt: after the earlier messages of the session
opt no attachment, in the first 30 s after the hub opened
N->>N: wait for an attachment until then
end
alt no attachment now
N->>O: reply to the reacted message: Session N is not running.
else attached
N->>N: text = quote line of replyTo, a line break and 👍
N->>N: pushed += (text, the reacted item), at most 20
N->>D: onLine {prompt: {text, from, item, replyTo: {item, from?}}}, item the reacted message's ID
D->>S: the line on /attach
S->>CC: notifications/claude/channel {content, meta: {from, item, reply_to, reply_to_from?}}
end
end
CC->>D: UserPromptSubmit hook: POST /turn {prompt}, the channel tag matched
N->>O: Claude: the opening message, quoting the reacted message
CC->>D: Stop hook: POST /turn {answer}
N->>O: Claude: the answer in the opening message, ending with the end line
Notes:
- A reaction with one of the apps' eight emoji, of a member whose role sends, other than
User, is a prompt. The core accepts the reactions of observers, and the hub ignores them. A reaction in the Main group reaches no session (Session.onReaction,prompt,Hub.onEvent,canSend). - A reaction is never a command or an approval. A 👍 to a tool-use card leaves the card pending, and reaches Claude as a prompt.
- The apps send and show eight emoji: 👍 👎 😀 😂 😢 ❤ 🚀 ✅. Any other reaction, such as
❤️with U+FE0F, a newer emoji, a text or another type, reaches no session, and Claude repliesThis reaction is not supported.to the reacted message. The reply is posted once for each member and reacted message while the service runs, also when the member removes the reaction and adds it again, and never for a reaction to this reply (reactionEmoji,unsupportedReaction,Session.refusedReactions,onReaction,refuseReaction). - The reacted message is quoted by the rule of a reply's quote, with the item's file name for an empty text, such as
> video: ride.mp4, and Claude's answer without its end line. Its file is not received (Session.onReaction,deliver,withoutEndLine,toReplyTo,replyText,quoteLine,trimmed). - The opening message of the turn, which the answer fills, quotes the reacted message, Claude's own messages included. An answer posted at Stop as a new message quotes it too (
Session.openTurn,postAnswer,quoteOf). - Each of this plugin's channel tags in a turn's prompt matches one pushed prompt. So two equal reactions to one message are quoted in their own turns (
Session.pushedIn). - Owners turn reactions off with the group's preference "Message reactions", and the core then emits no
chatItemReaction.
Source: Session.onReaction, prompt, refuseReaction, deliver, openTurn, answer, Hub.onEvent, channelNotification.
34. A tool approved for the rest of a session
sequenceDiagram
participant CC as Claude Code
participant S as Session process
participant D as Service
participant N as Session N
participant O as Owner
CC->>S: notifications/claude/channel/permission_request {request_id, tool_name: Bash, description, input_preview}
S->>D: POST /permission
D->>N: permission, Bash not approved
N->>O: card: I want to use Bash, /'approve 5', /'approve 5 all' or /'reject 5'
O->>N: /approve 5 all
N->>N: toolApprovals: Bash by Alice, logged
N->>D: onLine {tools: [{tool: Bash, approvedBy: Alice}]}
D->>S: the line on /attach, kept as the list of that attachment
N->>D: onLine {permission: {requestId, behavior: allow}}
D->>S: the line on /attach
S->>CC: notifications/claude/channel/permission allow
N->>O: card edited: Approved by Alice.
N->>O: reply: Approved Bash for the rest of this session by Alice. /'revoke Bash'
CC->>S: PreToolUse hook of type mcp_tool: tools/call pre_tool_use {tool: Bash}
S-->>CC: allow
CC->>CC: the next Bash use runs without a prompt, unless Claude Code's own rules ask
A use that Claude Code asks for by its own rules:
sequenceDiagram
participant CC as Claude Code
participant S as Session process
participant D as Service
participant N as Session N
participant O as Owner
CC->>S: PreToolUse hook: tools/call pre_tool_use {tool: Bash}
S-->>CC: allow
CC->>CC: the command writes to .bashrc, a protected path: the permission flow
CC->>S: notifications/claude/channel/permission_request {request_id, tool_name: Bash, ...}
S->>D: POST /permission
D->>N: permission, Bash approved
N->>O: card with the line: Bash is approved for this session, and Claude Code still asks for this use. /'approve 6' or /'reject 6'
Notes:
- Claude Code re-checks a call that a PreToolUse hook allows. A deny rule refuses it, and an ask rule, a safety check such as a write to a protected path, plan mode or the auto mode classifier sends it through the permission flow, which relays the prompt as a card. With Claude Code before 2.1.299, a hook's
allowalso ran writes in plan mode. - One tap approves its own card only. Other pending cards of the tool stay pending.
- An approval counts while its approver is an admin or owner of the group. After a membership event, the hub sends the approved tools before the rights post; after
/observer,Controlsends them after it reads the members again. /revoke TOOLremoves an approval, and the session gets the new list./listshows the approved tools after the chats.- The approvals belong to the Claude Code process of the session. A session server answers from the list of its current attachment only. When it drops the attachment after a failed call and attaches again, the hub sends it the approved tools, which it keeps. The approvals are dropped when
/sessioncomes from another process and when the session closes. The service tells processes apart by their ID and their start time, read on Linux and macOS; a/sessionwhose start time is unknown counts as another process. While two processes have the session attached, only the attachments of the process of the last/sessionget the approved tools; the others get{tools: []}. The approvals also end when the session's group is lost, found at an event or at a load, and the session server gets{tools: []}. - The approvals are kept in memory, so a service restart drops them.
- The terminal shows nothing at the approval, and Claude Code's
/permissionsdoesn't list it. - While the plugin's MCP server is not connected, Claude Code reports
MCP server 'plugin:simplex:simplex' not connectedas a non-blocking PreToolUse hook error at each tool use, and the tool use goes on.
Source: Control.ownerCommand, approveTool, revokeTool, approvedTools, endToolApprovals, load, lose, requestLines, commandsLine, ownerRequest, Session.permission, onLine, sendTools, endToolApprovals, Hub.onEvent, Service.onSession, onAttach, scheduleIdle, processStart, startSession, ServiceLink.open, ServiceLink.approvedBy, hookOutput, hooks/hooks.json.
35. A summary of the session's context
sequenceDiagram
participant CC as Claude Code
participant HK as PostCompact hook
participant SS as SessionStart hook
participant T as Transcript
participant D as Service
participant N as Session N
participant O as Owner
CC->>CC: the context is full, or idle, or /compact: Claude Code summarises the conversation
CC->>SS: SessionStart {source: compact, model}
SS->>D: POST /title without model
CC->>HK: PostCompact {trigger, compact_summary}, agent_id for a subagent since 2.1.323
CC->>T: compact_boundary {timestamp, compactMetadata}, at once, or with the next request's records during a turn
HK->>T: the tail of 4 MiB, every second, up to 120 times
HK->>D: POST /turn {note}
N->>O: Claude: ⚙️ Context summarised automatically: 968K → 35K tokens
Notes:
- Claude Code runs the PostCompact hooks after each compaction of the session's conversation and of its subagents' conversations, with
triggerautoormanual. Since Claude Code 2.1.323 a subagent's input hasagent_id, and the hook sends nothing for it (eventFields,compactionNote). - The boundary is the last entry of type
systemand subtypecompact_boundarywithoutisSidechain, whosetimestampis no earlier than 60 s before the hook started and no later than 5 s after it. Claude Code creates it before it runs the PostCompact hooks. It writes the boundary of a compaction during a turn to the transcript with the records of the next request, a few seconds later, and the boundary of/compactand of an idle session at once. A subagent's boundary is written to the subagent's own transcript, so before 2.1.323 the hook reads for 2 minutes and sends nothing for a subagent's compaction. The upper bound keeps such a hook from taking the boundary of a compaction of the session's conversation that ends during its reads. A tail is decoded only when its bytes contain"compact_boundary"(recentBoundary,boundaryMarker,compactionAge,compactionSkew). - The note is
⚙️ Context summarised, thenon requestfortriggermanualandautomaticallyotherwise, then: PRE → POST tokensfrompreTokensandpostTokensof the boundary'scompactMetadata, in the compact notation ofIntl.NumberFormat. Claude posts it silent and without a quote, as the notes of flow 31. Without a note the hook sends no request (compactionNote,tokenCount,Session.turn). - After a compaction Claude Code runs the SessionStart hooks with
source: compactand the model of the compacted conversation, which is a subagent's model for a subagent's compaction. The SessionStart hook sends/titlewithout the model then, so the group's description keeps the session's model (sessionStart).
Source: sessionStart, turn, eventFields, compactionNote, recentBoundary, findInTranscript, readTail, the PostCompact entry of hooks.
36. The list of sessions
sequenceDiagram
participant CC as Claude Code
participant R as Claude Code's record
participant S as Session process
participant D as Service
participant N as Session N
participant M as MainGroup
participant C as Core _hub
participant O as Owner
S->>D: POST /session {id, pid, project, config, record: CONFIG/sessions/PID.json}
D->>N: record
CC->>R: status busy
D->>N: every 2 s: readRecord, the session attached
N->>R: read status
D->>M: showList: 🟠 N · NAME: working, then the not running line
M->>C: no list yet, an owner in the group: apiSendMessages #35;M, priority -1
M->>C: apiSetGroupCustomData #35;M {simplexMcpMain: true, simplexMcpList: {item, at}}
C->>O: the list
CC->>R: status waiting, a permission dialog
CC->>S: permission_request
S->>D: POST /permission
D->>M: showList: 🔵 N · NAME: waiting for you, 1 approval
M->>C: apiUpdateChatItem #35;M item
C->>O: the list edited, no alert
CC->>R: status idle
D->>M: showList: 🟢 N · NAME: idle
M->>C: apiUpdateChatItem #35;M item
Note over D,M: the list 23 hours old, or its edit refused
M->>C: apiSendMessages #35;M the new list, priority -1, and its item saved
M->>C: apiDeleteChatItems #35;M the old item, broadcast
Notes:
- The session process sends the absolute path of Claude Code's record of its parent process,
CLAUDE_CONFIG_DIRor~/.claude, thensessions/PID.json, and the service keeps it in the session (startSession,Service.onSession). - Claude Code writes
statusin its record at each change of its state:busywhile a query runs or delegated work is active,waitingwhile a dialog or another request waits for the person,idleotherwise, andshellin place ofidlewhile a background Bash task runs. It writes the file in place, so a read can find it half written; the hub then keeps the last status. The hub opens the record without blocking and reads only a regular file, and a render waits at most 1 s for a read; a slower read keeps the last status (Session.readRecord,recordStatus). - A tool-use card counts while the status is
waitingor unknown. When someone answers the dialog in the terminal, the status leaveswaiting, and the card, which stays until the turn ends, no longer counts (Session.stateLine). - When the session process detaches, the session's permissions end and the session moves into the last line. At the service's stop, the hub renders the list once more, with every session there, before it waits for the cancelled cards (
Hub.stop). - The text fits one message: the last line keeps the newest names that fit and counts the others (
Hub.sessionsText). - The first list waits for an owner, so it follows the greeting. The item and its time are kept in the Main group's custom data, so a new service edits the same list. A reset of the owners creates a new Main group, which gets its own list once an owner joins (
MainGroup.showList,postList,replace). - SimpleX allows edits of a message for 24 hours and deletions for everyone for 30 hours. The hub replaces a list 23 hours old, by the wall clock, at its next render, and deletes the old one; a refused deletion is logged (
MainGroup.replaceList). - An edit sends no SMP notification, and the apps alert for an edit only when it creates the item. The list's posts carry
priority: -1; an app without silent messages alerts for them.
Source: Hub.showSessions, Hub.sessionsText, Session.readRecord, Session.stateLine, MainGroup.showList.
37. The texts of a turn
sequenceDiagram
participant O as Owner
participant C as Core _hub
participant N as Session N
participant D as Service
participant HK as Turn hooks, async
participant DH as Display hook, sync
participant CC as Claude Code
O->>C: a prompt in #35;G
Note over O,CC: flow 20 delivers it to Claude Code
CC->>HK: UserPromptSubmit
HK->>D: POST /turn {id, pid, at: 0, prompt}
D->>N: turn: the steps and texts started before 0 ended, the opening messages without an end bounded at 0
N->>C: apiSendMessages #35;G [{text: "", priority: -1}], live, quoting the prompt
C->>O: the opening message, from Claude, with typing dots
CC->>DH: MessageDisplay {message_id: m1, index: 0, final: false, delta: "I'll read the hook first.\n"}
DH->>D: POST /turn {id, pid, at: 5, text: {message: m1, index: 0, final: false, delta}}
D->>N: turn: addBatch queued
D-->>DH: 200, without waiting for the posts
DH-->>CC: {}, the terminal shows the line
N->>C: apiUpdateChatItem #35;G the opening message, the line, live
CC->>DH: MessageDisplay {message_id: m1, index: 1, final: false, delta: "Then the tests.\n"}
N->>N: a timer for the update, 3 s after the last send
CC->>HK: PreToolUse
HK->>D: POST /turn {at: 6, step}
N->>C: apiSendMessages #35;G [{text: "📖 Read src/hook.ts", priority: -1}], live, after the queued text work
CC->>DH: MessageDisplay {message_id: m1, index: 2, final: true, delta: ""}
N->>N: the timer cleared, m1 complete, a timer to end it 10 s later
N->>C: apiUpdateChatItem #35;G the opening message, the whole text of m1, live
CC->>DH: MessageDisplay {message_id: m2, index: 0, final: true, delta: the answer}
N->>C: apiUpdateChatItem #35;G the opening message, the whole text of m1, live off
N->>C: apiSendMessages #35;G [{text: the answer, priority: -1}], live
N->>N: m2 complete, a timer to end it 10 s later
CC->>HK: Stop {last_assistant_message}
HK->>D: POST /turn {at: 11, answer}
N->>N: claim: m2, the newest text started after 0 and before 11, starts the answer
N->>C: /_update item #35;G m2's message, the answer and "!- Done in 11 s!", live off, priority 1
C->>O: the answer ending with the end line in small print, without an edited mark
Notes:
- Claude Code runs the display hook for each batch of Claude's text in the main conversation: whole lines, at most every 100 ms, and a last batch with
final: true, which may end within a line. In the terminal, Claude Code shows each batch only after the hook returns. The hook waits at most 1 s for the service, starts none and makes no retry, and Claude Code gives it 2 s. Inclaude -pand Agent SDK runs, the hook runs once per message with the whole text, and the service answers 409, because such runs have no session (display,postToService). Session.turnqueues a batch and returns, so the service answers before the posts. One queue holds the text work and the step starts, so the texts and the steps' lines are posted in the order their requests arrive (Session.text,queueLive,step).- The hub appends a text's batches in index order, and posts the text from its first part that is not blank, live and silent. The turn's first post fills the opening message (flow 21). The hub updates a live text at most once per 3 s. At its final batch, it updates the text at once with its whole text, still live. It finalizes the text, live off, 10 s later, before the next step or the first batch of the next text, or at Stop with the end line when the text is the answer's message. So the answer's message ends without an edited mark. A text whose first batch's hook started before the latest answer's hook is dropped, and so are the later batches of an ended text (
textEndMs,Session.addBatch,completeText,endComplete,showText,step). - Each part of a text is measured as a part of an answer without a quote. When a text outgrows one message, the hub finalizes its message with the part that fits, and continues the rest in a new live message (
Session.showText,textParts). - At Stop, the hub first claims the answer, and then ends the live texts whose first batch's hook started before the Stop hook. The claimed text is the newest one, live or among the last 20 ended that have a message or were refused, whose first batch's hook started after the turn's start and before the Stop hook, when its text, trimmed, starts the trimmed answer. The rest of the answer after the text's finished parts, with the end line, then completes that text's message. A text that ended before Stop gets the end line in an edit, with an edited mark. Without such a text, the hub posts the answer with the end line as in flow 21 (
Session.endTexts,claim,endText,endPart,answer,withLine). - At a prompt that starts a turn, the hub finalizes the live texts whose first batch's hook started before the prompt's hook with their text. At the last detach and at the hub's stop, it finalizes every live text. It also finalizes a live text 23 hours after the send of its message by the wall clock, as after an interruption with Esc and no prompt for a day; for a text in the opening message, that send is the opening message's (
Session.turn,endLive,expireLive). - When the core refuses a text's post or update with
feature not allowed NAME, Claude postsClaude's text was not posted: NAME are off in the group of this session; its owners can turn them on in the group's preferences.once for that text. When the refused post would fill the turn's opening message, this text fills it in place of a post. The text's message, when one was posted, keeps the text accepted last. The text ends at once, also when it outgrows a message, the hub drops its later batches, and an update scheduled before its end is skipped. At Stop, the claim finds such a text as for any other text, and then posts nothing more of the answer, so the group gets one refusal (Session.updateText,startLine,refuseText,claim). - The texts and the opening messages are kept in the service's memory. After a service restart during a text, its message stays live, its later batches show nothing, and the answer is posted at Stop.
Source: hooks.json, display, postToService, Session.turn, text, addBatch, completeText, endComplete, showText, updateText, endText, endTexts, claim, answer.
38. The status line command
sequenceDiagram
participant S as Service
participant F as ROOT/status-line.js
participant CC as Claude Code
participant SL as Status line command
participant N as Session N
participant C as Core _hub
participant O as Owner
S->>F: at each start: import of its own dist/status-line.js, through status-line.js.tmp
Note over CC: statusLine: node "${SIMPLEX_MCP_HOME:-$HOME/.simplex-mcp}/status-line.js"
CC->>SL: the input on stdin, after a response, a change of the effort level or the reset of a window
SL->>SL: available memory, and statfs of ROOT or its nearest existing parent
SL->>CC: Opus 5.5 · effort high · 67% context · 5 h: 34% · week: 61% · RAM 12 GB free · disk 7.3 GB free
SL->>S: POST /turn {id, pid, at, effort, limits, statusLine: true}, waiting at most 1 s, without the memory and disk
S->>N: turn
N->>N: statusLineReports = true, and limits kept when at is not older than that of the limits kept
opt a known effort level changed
N->>C: apiSendMessages #35;G [{text: "!- Effort changed to high!", priority: -1}]
C->>O: the line, silent
end
Note over N: the next end line has " · 5 h: 34% · week: 61%"
Notes:
- Claude Code passes the plan's usage only to the status line command of the person's settings, which a plugin can't set, and it refuses
${CLAUDE_PLUGIN_ROOT}in a command that belongs to no plugin. The shell expands${SIMPLEX_MCP_HOME:-$HOME/.simplex-mcp}to the data folder of the machine or container, and the service of each version writesstatus-line.jsthere at its start, so one setting serves every container and every version (writeStatusLine,Service.start,productionDeps). - The command loads only Node modules,
paths.tsandservice-request.ts. It prints its line first, sends nothing without an effort level and a window, starts no service and makes no retry (statusLine,runStatusLine,postToService). - The line ends with the machine's available memory and the free disk of the data folder's volume, each followed by ❗️ when low: memory below 5% of the total, which a container's limit caps, or disk below 5 GB. The command does not send them: the service reads its own for the end line (flow 21) (
machineState,machineParts). - The hub keeps the limits in memory. A window whose
resetsAthas passed is left out of the end line, as Claude Code leaves it out of the input. Without the setting, the end line has no plan's usage, and an effort change shows at the next tool step or the end of the next turn (Session.turn,endLine,limitParts). - The hooks send the level of the turn, which is
xhighafterultrathinkand can be a skill's or the prompt's own level, while the command sends the session's level. After the first request of the command, the hub takes the effort level only from the command, so the level of one turn posts no line (Session.turn). - Claude Code runs
status-line.jsalso when no service could start in the data folder, so that folder must be writable only by the user.
Source: statusLine, limitParts, runStatusLine, writeStatusLine, Session.turn, endLine.