README
¶
example/agent
Overview
example/agent is a package main demo ACP agent built on github.com/coder/acp-go-sdk. It keeps sessions in a mutex-guarded map and answers Initialize with the SDK protocol version, LoadSession enabled, and the session/list and session/delete capabilities. It lists and deletes the sessions in that map. Each Prompt runs a scripted turn: it streams text, reports two named tool calls, and sends one permission request to the client. A client that advertises notices gets the demo disclaimer as a notice. The prompt /compact compacts the session instead. A client that advertises form elicitation is asked for the database host of the edit first, and a client that advertises url elicitation is asked to review an allowed edit. It uses no AI model. main connects the agent over stdio, or over the stdio of a child process when you pass a command line, and blocks until the peer disconnects.
Interface
- No exported top-level symbols. All top-level identifiers are unexported:
agentSession,exampleAgent,newExampleAgent,defaultHost,randomID,pause,main[main.go:exampleAgent] exampleAgentsatisfiesacp.Agentand the optional interfacesacp.AgentLoaderandacp.AgentUnstableMessageMcp, checked by compile-time assertions. It implements no other optional interface, so the SDK answers every other agent method, such assession/fork, with-32601[main.go:exampleAgent]- CLI: no flags are parsed. With no arguments, the agent speaks ACP on its own stdin and stdout. With arguments,
os.Args[1]is the client program andos.Args[2:]are its arguments [main.go:main] - Environment variables: this file reads none. With arguments,
exec.CommandContextlooks up the client program throughPATHwhen its name has no path separator, and the child inherits the full environment [main.go:main] Initializerecords whether the client accepts boolean config options, form and url elicitation, notices, and compaction updates, and returnsProtocolVersion: acp.ProtocolVersionNumber,AgentCapabilities.LoadSession: true, andSessionCapabilitieswithList,DeleteandSystemPromptset to{}, so it takes a system prompt inappendmode only [main.go:Initialize]NewSessionreturns a new session ID of the formsess_<hex>and records the request'sCwdand the text of itsSystemPrompt. A system prompt in another mode thanappend, with no content, or with a block that is not text getsacp.NewInvalidParamsand no session. Each scripted turn of a session with a system prompt sendsFollowing your system prompt: <text>after the disclaimer [main.go:NewSession, systemPromptText, simulateTurn]ListSessionsreturns one page, with noNextCursor, of every session in the map, or only those whoseCwdequals the request'sCwdwhen it is set, in creation order. Each entry hasSessionIdandCwd[main.go:ListSessions]DeleteSessionremoves the session from the map and returns an empty response and a nil error, also for an unknown session ID [main.go:DeleteSession]Promptruns the scripted turn, or the compaction when the prompt is the single text block/compact, and returnsacp.StopReasonEndTurn, oracp.StopReasonCancelledwhen the turn context ends [main.go:Prompt]Cancelcancels the running turn of a session [main.go:Cancel]Authenticatereturns an empty response and a nil error [main.go:Authenticate]LoadSessionreplays the session's history assession/updatenotifications before it returns: each prompt's blocks asuser_message_chunkupdates, and every update that the agent sent for the session but notices, which are live events, in order. It returns the session's config options. ASystemPromptreplaces the session's prompt, with the rules ofNewSession; without one the session keeps its prompt. An unknown session ID gets-32002(resource not found) with thesessionIdindata, and aCwdother than the session's getsacp.NewInvalidParams. Sessions live in memory, so only a session of this process loads [main.go:LoadSession, main.go:sessionUpdate]SetSessionModereturns an empty response and a nil error [main.go:SetSessionMode]UnstableMessageMcpreturns nil and does nothing: the agent sends nomcp/messagerequest, so no client notification belongs to one [main.go:UnstableMessageMcp]SetSessionConfigOptionsets themodelselect todemo-fastordemo-deep, or theweb_searchboolean for a client that accepts booleans, and returns every option. Any other id or value returnsacp.NewInvalidParams[main.go:SetSessionConfigOption]- These methods return
acp.NewMethodNotFound:ResumeSession,CloseSession,Logout[main.go:ResumeSession, main.go:CloseSession, main.go:Logout] SetAgentConnectionstores the*acp.AgentSideConnectionthat the turn uses to send updates.maincalls it afteracp.NewAgentSideConnection[main.go:SetAgentConnection, main.go:main]
Invariants
Promptreturns the errorsession <id> not foundwhen the session ID is not in the sessions map, so a prompt afterDeleteSessionfails [main.go:Prompt, main.go:DeleteSession]DeleteSessioncalls the session's cancel func, when it is set, under the session'ssendMuanda.mu, so it waits for a running replay, and no update of the session follows it.Promptchecks its context undera.muafter the last step of a turn, so a turn that a delete reaches before that check ends withStopReasonCancelled, and a delete after it finds no cancel func [main.go:DeleteSession, main.go:Prompt]Promptlooks up the session, then in one critical section undersendMuanda.muchecks that the session still exists and that its context is not done, takes the earlier turn's cancel func froms.cancel, stores its own, and adds the prompt tohistory. Then it calls the earlier func. The SDK cancels the context of a prompt that arrived before the session's newest one, so a late prompt returnsStopReasonCancelledat once: it neither cancels the newer turn nor lands after it in the history. A concurrentDeleteSessioneither runs first, soPromptfails withsession <id> not found, or finds the new func and cancels the turn. The SDK also cancels the earlier prompt of a session when a later one registers [main.go:Prompt, main.go:DeleteSession] [../../agent.go:registerPrompt]Promptmaps any turn error that occurs after the turn context ends toStopReasonCancelledwith a nil error [main.go:Prompt]Promptstores the current turn's cancel func ins.cancelbefore the turn runs, and clears it only after a successful turn, and only when no laterPrompthas replaced it (s.turnstill holds its number). On the error and cancelled paths,s.cancelstill holds the current turn's func [main.go:Prompt]- Every session update of a turn goes through
sessionUpdate, which holds the session'ssendMuwhile it sends the update and appends it tohistory.Promptappends the user's blocks undersendMutoo, so an update of an earlier, overlapping turn lands before or after the whole prompt.LoadSessionapplies a new system prompt only after the replay succeeds.LoadSessionholdssendMuwhile it replays, so a replay never misses or repeats an update of a running turn. Lock order:sendMu, thena.mu. No code takessendMuwhile it holdsa.mu, and no request to the client runs undersendMu[main.go:sessionUpdate, main.go:LoadSession] Cancelreturns nil for unknown sessions and calls the cancel func only when it is set. It readss.cancelafter it releasesa.mu[main.go:Cancel]a.muguards the sessions map andnextSeqinNewSession,ListSessions,DeleteSession,Cancel, andPrompt, and guardss.cancelands.turninPrompt[main.go:NewSession, main.go:ListSessions, main.go:DeleteSession, main.go:Cancel, main.go:Prompt]- A
Cancelledpermission outcome ends the turn with a nil error, soPromptreturnsStopReasonEndTurn[main.go:simulateTurn] - A permission outcome with no
Selectedoption returns the errorunexpected permission outcome[main.go:simulateTurn] - A selected option other than
alloworrejectreturns the errorunexpected permission option: <id>[main.go:simulateTurn] randomIDreturns its prefix (sess_,elic_orcmp_) plus 24 hex characters, or the prefix plusUnixNanoifcrypto/randfails [main.go:randomID]pausereturnsctx.Err()when the context ends before the timer fires [main.go:pause]
Side Effects
- Without arguments, the ACP connection uses
os.Stdinandos.Stdout[main.go:main] - With arguments,
mainstarts the client withexec.CommandContext, pipes its stdin and stdout to the connection, and sets its stderr toos.Stderr. Errors fromStdinPipeandStdoutPipeare discarded [main.go:main] - If the client fails to start,
mainwritesfailed to start client: <err>to stderr and callsos.Exit(1)[main.go:main] - After the peer disconnects,
mainkills the child process if one was started [main.go:main] signal.NotifyContextcancels the main context onos.Interrupt. The call also listsos.Kill, but no process can catch SIGKILL, so a kill ends the agent at once and no cleanup runs [main.go:main]mainsets the connection logger toslog.Default()[main.go:main]mainblocks on<-asc.Done()until the peer disconnects [main.go:main]- A turn that is not cancelled sends
SessionUpdatenotifications with hard-coded text and tool callscall_1(nameread_file, read/project/README.md) andcall_2(namewrite_file, edit/project/config.json). Tool call ids are unique within a session: the session's next turn usescall_3andcall_4, and so on [main.go:toolCallIDs]. Its first update is the disclaimer: aninfonotice titledACP Go Example Agent — demo onlyfor a client that advertisessession.notices, else an agent message. A cancelled turn returns at its nextSessionUpdate,pause, orRequestPermissioncall, so it can end before either tool call. No file is read or written [main.go:simulateTurn, main.go:pause] - A turn that is not cancelled sends one
RequestPermissionrequest forcall_2(namewrite_file, path/project/config.json, the same as the tool call) with optionsallowandreject, and waits for the client response [main.go:simulateTurn] - Before that request, when the client advertises form elicitation, the turn sends
CreateElicitationin form mode, tied to the session andcall_2, for one required stringhost(defaultnew-host). An accepted non-empty host goes into the request'srawInput.content; a decline, a cancel or an empty host keepsnew-host[main.go:askHost] - After an allowed edit, when the client advertises url elicitation, the turn sends
CreateElicitationin url mode with a newelic_<hex>id, and sendsCompleteElicitationwith that id once the client accepts [main.go:askReview] - A turn that is not cancelled sleeps between steps: one 250 ms step and several 1 s steps [main.go:simulateTurn, main.go:pause]
/compactsends, for a client that advertisessession.compaction, acompaction_updatewith a newcmp_<hex>id and statusin_progress, onecompaction_summary_chunkwith the textCompacted <n> earlier prompt(s) of this demo session., and acompaction_updatewith statuscompleted, 250 ms apart. Any other client gets that text as one agent message [main.go:compact]NewSessionadds an entry to the sessions map undera.mu[main.go:NewSession]DeleteSessionremoves an entry from the sessions map under the session'ssendMuanda.mu[main.go:DeleteSession]Promptstores acontext.CancelFuncin the session undera.mu[main.go:Prompt]randomIDreads 12 bytes fromcrypto/rand[main.go:randomID]
Verification
- Run:
go vet ./example/agentandgo test ./example/agent. The tests drivesession/new,session/list,session/delete, andsession/promptthrough an SDK client connection over pipes [main_test.go]
Documentation
¶
There is no documentation for this package.