// Package acp serves editor requests over the Agent Client Protocol. package acp import ( "bufio" "context" "crypto/rand" "encoding/base64" "encoding/json" "errors" "fmt" "io" "slices" "sync" "time" "albedo/cli/internal/app" "albedo/cli/internal/daemon" "albedo/cli/internal/daemon/protocol" ) type Backend interface { Catalog(context.Context) (app.ACPSettings, error) Refresh(context.Context, string, app.ACPSettings) (app.ACPSettings, error) Settings(context.Context, string) (app.ACPSettings, error) SetModel(context.Context, string, string) error SetEffort(context.Context, string, string) error SetContextWindow(context.Context, string, *int) error SetCompactionStrategy(context.Context, string, *string) error Compact(context.Context, string) (daemon.CompactionResult, error) Delete(context.Context, string) error List(context.Context, *string, *string) (protocol.SessionPage, error) History(context.Context, string, daemon.ACPHistoryCursor, int64) ([]daemon.StreamEvent, daemon.ACPHistoryCursor, error) Cancel(context.Context, string, string) (protocol.InputCancellation, error) New(context.Context, string, []protocol.ACPMCPServer) (protocol.ACPAttachment, error) Resume(context.Context, string, string, []protocol.ACPMCPServer) (protocol.ACPAttachment, error) Prepare(string, []json.RawMessage, string) (*daemon.OperationHandle, error) Submit(context.Context, *daemon.OperationHandle) error Renew(context.Context, string) error Release(context.Context, string) error Observer(string, protocol.Cursor) *daemon.ChatClient } type Connector func(context.Context, string) (Backend, error) func AppConnector(service *app.Service) Connector { return func(ctx context.Context, token string) (Backend, error) { return service.ConnectACP(ctx, token) } } type adapter struct { backend Backend diagnostics io.Writer ctx context.Context cancel context.CancelFunc writer *writer connect Connector sessions map[string]*session attachmentTails map[string]chan struct{} recoveringPrompts map[string]*request watch streamFunc token string workers sync.WaitGroup setupMu sync.Mutex mu sync.Mutex v2 bool used bool initialized bool // owned by the stdio reader capabilities clientCapabilities } func Run(ctx context.Context, input io.Reader, output, diagnostics io.Writer, version string, connect Connector) error { ctx, cancel := context.WithCancel(ctx) defer cancel() token := make([]byte, 32) if _, err := rand.Read(token); err != nil { return err } adapter := &adapter{ctx: ctx, cancel: cancel, writer: newWriter(output), connect: connect, token: base64.RawURLEncoding.EncodeToString(token), sessions: map[string]*session{}, diagnostics: diagnostics} go adapter.writer.run(ctx) lines := make(chan []byte) readDone := make(chan error, 1) go func() { scanner := bufio.NewScanner(input) scanner.Buffer(make([]byte, 4096), 100*1024*1024) for scanner.Scan() { line := slices.Clone(scanner.Bytes()) select { case lines <- line: case <-ctx.Done(): return } } readDone <- scanner.Err() }() defer adapter.release() for { select { case <-ctx.Done(): if failure := adapter.writer.failure(); failure != nil { return failure } return ctx.Err() case <-adapter.writer.done: if err := adapter.writer.failure(); err != nil { return err } return ctx.Err() case err := <-readDone: if err != nil { return err } barrier := adapter.writer.flush() select { case <-barrier: case <-adapter.writer.done: return adapter.writer.failure() case <-ctx.Done(): return ctx.Err() } return nil case line := <-lines: message, failure := parse(line) if failure != nil { if failure.Code == -32602 && message.ID == nil { continue } adapter.respond(message.ID, nil, failure) continue } adapter.handle(message, version) } } } type requestRoute struct { run func(*adapter, request) worker bool ordered bool } var requestRoutes = map[method]requestRoute{ methodAuthenticate: {run: refuseAuthentication}, methodList: {run: (*adapter).list, worker: true}, methodNew: {run: (*adapter).setup, worker: true}, methodResume: {run: (*adapter).setup, worker: true, ordered: true}, methodLoad: {run: (*adapter).setup, worker: true, ordered: true}, methodConfig: {run: (*adapter).setConfigOption, worker: true, ordered: true}, methodClose: {run: (*adapter).closeSession, worker: true, ordered: true}, methodDelete: {run: (*adapter).deleteSession, worker: true, ordered: true}, methodPrompt: {run: (*adapter).prompt}, } func refuseAuthentication(a *adapter, message request) { a.respond(message.ID, nil, invalidParams("No authentication methods are available")) } func (a *adapter) handle(message request, version string) { switch { case message.Method == "": return case message.Method == methodInitialize && message.ID != nil: a.initialize(message, version) case !a.initialized: if message.ID != nil { a.respond(message.ID, nil, problem(-32600, "not_initialized", "Initialize the connection first")) } case message.Method == methodCancel && message.ID == nil: a.cancelNotification(message) case message.ID == nil: return default: a.used = true route, known := requestRoutes[message.Method] if !known || a.v2 && (message.Method == methodLoad || message.Method == methodAuthenticate) { a.respond(message.ID, nil, unknownMethod()) return } switch { case route.worker && route.ordered: // Reserve the session's place here, on the reader, so two ordered // requests keep arrival order instead of racing their workers. run := a.reserve(message, route.run) a.workers.Go(run) case route.worker: a.workers.Go(func() { route.run(a, message) }) default: route.run(a, message) } } } func (a *adapter) initialize(message request, version string) { var params struct { ProtocolVersion *int `json:"protocolVersion"` } if json.Unmarshal(message.Params, ¶ms) != nil || params.ProtocolVersion == nil || *params.ProtocolVersion < 0 || *params.ProtocolVersion > 65535 { a.respond(message.ID, nil, invalidParams("protocolVersion must be an integer between 0 and 65535")) return } if a.used && (a.v2 || *params.ProtocolVersion >= 2) { a.respond(message.ID, nil, problem(-32600, "already_initialized", "Connection already in use")) return } if *params.ProtocolVersion == 0 { p := problem(-32022, "unsupported_version", "Unsupported protocol version") p.Data["requested"] = 0 p.Data["supported"] = []int{1, 2} a.respond(message.ID, nil, p) return } a.mu.Lock() if !a.used { a.v2 = *params.ProtocolVersion >= 2 } a.initialized = true a.capabilities = decodeClientCapabilities(message.Params) a.mu.Unlock() if message.ID != nil { if a.v2 { a.respond(message.ID, initializeV2(version), nil) } else { a.respond(message.ID, initialize(version), nil) } } } func (a *adapter) response(id json.RawMessage, result any, failure error) map[string]any { if id == nil { id = json.RawMessage("null") } message := map[string]any{"jsonrpc": "2.0", "id": id} if failure == nil { message["result"] = result return message } var rpc *rpcError if !errors.As(failure, &rpc) { rpc = internalError(failure.Error()) if api, ok := errors.AsType[*daemon.APIError](failure); ok { rpc = daemonProblem(api) } if mismatch, ok := errors.AsType[*daemon.CompatibilityError](failure); ok { rpc = problem(-32603, "daemon_incompatible", mismatch.Error()+" Use matching Albedo builds for the daemon and editor, then relaunch the ACP adapter.") } if mismatch, ok := errors.AsType[*daemon.APIMismatchError](failure); ok { rpc = problem(-32603, "daemon_incompatible", fmt.Sprintf("Daemon API %.12s differs from editor adapter API %.12s. Use matching Albedo builds, then relaunch the ACP adapter.", mismatch.Daemon, mismatch.Client)) } } message["error"] = rpc return message } func missingSession(err error) bool { api, ok := errors.AsType[*daemon.APIError](err) return ok && (api.Code == "session_not_found" || api.Code == "not_found") } func daemonProblem(api *daemon.APIError) *rpcError { switch api.Code { case "provider_missing", "provider_unconfigured": rpc := problem(-32000, "provider_missing", "No model provider is configured.") rpc.Data["instruction"] = "Run `albedo login` in a terminal, then try again." return rpc case "session_not_found", "not_found": return problem(-32002, "session_not_found", api.Message) case "daemon_incompatible": return problem(-32603, api.Code, api.Message) } if api.StatusCode >= 500 { return problem(-32603, api.Code, api.Message) } return problem(-32602, api.Code, api.Message) } func (a *adapter) respond(id json.RawMessage, result any, failure error) { if _, err := a.writer.enqueue(a.response(id, result, failure), false); err != nil { a.cancel() } } type newSessionResult struct { Options any `json:"configOptions"` SessionID string `json:"sessionId,omitempty"` } func (a *adapter) setup(message request) { var replay bool if a.v2 { var failure error replay, failure = v2Setup(message) if failure != nil { a.respond(message.ID, nil, failure) return } } params, refusal := parseSetup(message) if refusal != nil { a.respond(message.ID, nil, refusal) return } servers, refusal := a.decodeMCPServers(params.mcpServers) if refusal != nil { a.respond(message.ID, nil, refusal) return } if err := a.connectBackend(); err != nil { a.respond(message.ID, nil, err) return } catalog, err := a.backend.Catalog(a.ctx) if err != nil { a.respond(message.ID, nil, err) return } var attachment protocol.ACPAttachment var prior *session if message.Method == methodNew { attachment, err = a.backend.New(a.ctx, params.cwd, servers) } else { prior = a.pausePrior(params.sessionID) attachment, err = a.backend.Resume(a.ctx, params.sessionID, params.cwd, servers) if missingSession(err) { err = noSession(params.sessionID) } if err != nil && prior != nil { prior.resumeObservation() } } if err != nil { a.respond(message.ID, nil, err) return } settings, err := a.backend.Refresh(a.ctx, attachment.SessionID, catalog) if err != nil { setupFailed(a.backend, prior, attachment.SessionID) a.respond(message.ID, nil, err) return } a.stopPrior(attachment.SessionID) current := newSession(a, attachment) current.cwd, current.servers = params.cwd, servers current.settings = settings a.reportSettings(attachment.SessionID, settings) current.v2 = a.v2 current.replayV2 = replay if current.v2 && !replay { current.keyHistoryCutoff = current.historyCutoff } if current.v2 { for _, id := range current.inherited { current.rememberInput(id) } } loading := message.Method == methodLoad || a.v2 && message.Method == methodResume if loading { current.pauseObservation() for id := range current.boundaries { current.withheld[id] = true } } a.mu.Lock() current.compactionEnabled = a.capabilities.compaction current.planUpdates = a.v2 || a.capabilities.plan a.sessions[attachment.SessionID] = current if loading { current.start() a.mu.Unlock() if err := current.load(message); err != nil { a.discard(current) a.respond(message.ID, nil, err) } return } result := newSessionResult{Options: current.wireOptions(configOptions(current.settings))} if message.Method == methodNew { result.SessionID = attachment.SessionID } a.respond(message.ID, result, nil) current.start() a.mu.Unlock() } func setupFailed(backend Backend, prior *session, id string) { if prior != nil { prior.resumeObservation() return } ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() _ = backend.Release(ctx, id) } func (a *adapter) discard(current *session) { current.stop() a.mu.Lock() if a.sessions[current.id] == current { delete(a.sessions, current.id) } a.mu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() _ = a.backend.Release(ctx, current.id) } func (a *adapter) prompt(message request) { var params struct { SessionID string `json:"sessionId"` Prompt []json.RawMessage `json:"prompt"` } if err := decodeParams(message.Params, ¶ms); err != nil { a.respond(message.ID, nil, invalidParams(err.Error())) return } blocks, err := translatePrompt(params.Prompt) if err != nil { a.respond(message.ID, nil, invalidParams(err.Error())) return } // Ordinary prompts and cancellation stay on the reader. Only a prompt // waiting for reattachment needs a worker and an ordered setup slot. a.mu.Lock() current := a.sessions[params.SessionID] switch { case current == nil: a.mu.Unlock() a.respond(message.ID, nil, noSession(params.SessionID)) return case a.recoveringPrompts[params.SessionID] != nil: a.mu.Unlock() a.respond(message.ID, nil, refuseBusy("A prompt is waiting for reconnection")) return case current.prompt(message, blocks): a.mu.Unlock() return } if a.recoveringPrompts == nil { a.recoveringPrompts = make(map[string]*request) } a.recoveringPrompts[params.SessionID] = &message a.mu.Unlock() a.workers.Go(a.reserve(message, func(a *adapter, _ request) { a.mu.Lock() pending := a.recoveringPrompts[params.SessionID] == &message a.mu.Unlock() if !pending { return } current, err := a.forInput(params.SessionID) a.mu.Lock() defer a.mu.Unlock() if a.recoveringPrompts[params.SessionID] != &message { return // cancelled before admission } delete(a.recoveringPrompts, params.SessionID) if err != nil { a.respond(message.ID, nil, err) } else if !current.prompt(message, blocks) { a.respond(message.ID, nil, uncertain("The session disconnected again; retry this prompt")) } })) } func (a *adapter) cancelNotification(message request) { var params struct { SessionID string `json:"sessionId"` } if decodeParams(message.Params, ¶ms) != nil { return } a.mu.Lock() defer a.mu.Unlock() if pending := a.recoveringPrompts[params.SessionID]; pending != nil { delete(a.recoveringPrompts, params.SessionID) a.respond(pending.ID, promptCancelled(), nil) } if current := a.sessions[params.SessionID]; current != nil { current.cancelPrompt() } } func (a *adapter) closeSession(message request) { id, failure := a.sessionParam(message) if failure != nil { a.respond(message.ID, nil, failure) return } if !fullSessionID(id) { a.respond(message.ID, struct{}{}, nil) return } ctx, cancel := context.WithTimeout(a.ctx, 3*time.Second) defer cancel() if current := a.attached(id); current != nil { if err := current.cancelForClose(ctx); err != nil { a.respond(message.ID, nil, err) return } } a.detach(id) if err := a.backend.Release(ctx, id); err != nil && !missingSession(err) { a.respond(message.ID, nil, err) return } a.respond(message.ID, struct{}{}, nil) } func (a *adapter) deleteSession(message request) { id, failure := a.sessionParam(message) if failure != nil { a.respond(message.ID, nil, failure) return } // Delete first: a refused or partial delete must leave the editor's session // usable, so detaching is the last thing a successful delete does. if !fullSessionID(id) { a.respond(message.ID, struct{}{}, nil) return } if a.v2 { if s := a.attached(id); s != nil { ctx, cancel := context.WithTimeout(a.ctx, 3*time.Second) defer cancel() if err := s.cancelForClose(ctx); err != nil { a.respond(message.ID, nil, err) return } } } if err := a.backend.Delete(a.ctx, id); err != nil && !missingSession(err) { a.respond(message.ID, nil, err) return } a.detach(id) a.respond(message.ID, struct{}{}, nil) } func (a *adapter) sessionParam(message request) (string, error) { var params struct { SessionID string `json:"sessionId"` } if decodeParams(message.Params, ¶ms) != nil || params.SessionID == "" { return "", invalidParams("A full session ID is required") } if fullSessionID(params.SessionID) { if err := a.connectBackend(); err != nil { return "", err } } return params.SessionID, nil } func (a *adapter) detach(id string) { a.mu.Lock() current := a.sessions[id] delete(a.sessions, id) a.mu.Unlock() if current == nil { return } current.mu.Lock() current.fail("The editor closed this session") current.stop() current.mu.Unlock() } func (a *adapter) release() { a.cancel() a.workers.Wait() a.mu.Lock() defer a.mu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() for id, current := range a.sessions { current.stop() _ = a.backend.Release(ctx, id) } } func (a *adapter) reserve(message request, run func(*adapter, request)) func() { var params struct { SessionID string `json:"sessionId"` } _ = json.Unmarshal(message.Params, ¶ms) a.mu.Lock() if a.attachmentTails == nil { a.attachmentTails = map[string]chan struct{}{} } prior := a.attachmentTails[params.SessionID] done := make(chan struct{}) a.attachmentTails[params.SessionID] = done a.mu.Unlock() return func() { if prior != nil { <-prior } defer func() { a.mu.Lock() if a.attachmentTails[params.SessionID] == done { delete(a.attachmentTails, params.SessionID) } close(done) a.mu.Unlock() }() run(a, message) } } func (a *adapter) connectBackend() error { a.setupMu.Lock() defer a.setupMu.Unlock() if a.backend != nil { return nil } backend, err := a.connect(a.ctx, a.token) if err != nil { return err } a.backend = backend return nil } // reportSettings says why a selector may be shorter than expected: a provider // catalogue that could not be read, or a model with no reasoning levels. func (a *adapter) reportSettings(id string, settings app.ACPSettings) { for _, note := range settings.Notes { a.note("session %s: %s", id, note) } if settings.Model != "" && len(settings.EffortLevels()) == 0 { a.note("session %s: model %s reports no reasoning levels", id, settings.Model) } } func (a *adapter) note(format string, args ...any) { if a.diagnostics == nil { return } fmt.Fprintf(a.diagnostics, "acp: "+format+"\n", args...) } func (a *adapter) attached(id string) *session { a.mu.Lock() defer a.mu.Unlock() return a.sessions[id] } func (a *adapter) stopPrior(id string) { a.mu.Lock() prior := a.sessions[id] delete(a.sessions, id) a.mu.Unlock() if prior != nil { prior.mu.Lock() prior.fail("Attachment resumed by this connection") prior.stop() prior.mu.Unlock() } } func (a *adapter) pausePrior(id string) *session { prior := a.attached(id) if prior != nil { prior.pauseObservation() } return prior }