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 disabled, 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 tool calls, and sends one permission request to the client. 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.Agent,acp.AgentLoader, andacp.AgentExperimental, checked by compile-time assertions [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 and form and url elicitation, and returnsProtocolVersion: acp.ProtocolVersionNumber,AgentCapabilities.LoadSession: false, andSessionCapabilitieswithListandDeleteset to{}[main.go:Initialize]NewSessionreturns a new session ID of the formsess_<hex>and records the request'sCwd[main.go:NewSession]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 and returnsacp.StopReasonEndTurn, oracp.StopReasonCancelledwhen the turn context ends [main.go:Prompt]Cancelcancels the running turn of a session [main.go:Cancel]AuthenticateandLoadSessionreturn empty responses and a nil error [main.go:Authenticate, main.go:LoadSession]SetSessionModereturns an empty response and a nil error [main.go:SetSessionMode]UnstableDidOpenDocument,UnstableDidChangeDocument,UnstableDidCloseDocument,UnstableDidFocusDocument,UnstableDidSaveDocument,UnstableAcceptNes, andUnstableRejectNesreturn nil and do nothing [main.go:UnstableDidOpenDocument, main.go:UnstableAcceptNes]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,UnstableForkSession,UnstableStartNes,UnstableSuggestNes,UnstableCloseNes,UnstableListProviders,UnstableSetProvider,UnstableDisableProvider[main.go:ResumeSession, main.go:CloseSession, main.go:UnstableForkSession] 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, undera.mu.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, takes the earlier turn's cancel func froms.cancel, and stores its own in one critical section, and then calls the earlier func. 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]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_orelic_) 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(read/project/README.md) andcall_2(edit/project/config.json). 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(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]
NewSessionadds an entry to the sessions map undera.mu[main.go:NewSession]DeleteSessionremoves an entry from the sessions map undera.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.