package acp import ( "crypto/sha256" "encoding/json" "fmt" "path/filepath" "unicode/utf8" ) func initializeV2(version string) any { marker := struct{}{} return map[string]any{ "protocolVersion": 2, "info": initialize(version).AgentInfo, "capabilities": map[string]any{"session": map[string]any{ "prompt": map[string]any{"image": marker, "embeddedContext": marker}, "mcp": map[string]any{"stdio": marker, "http": marker}, "delete": marker, }}, } } func v2Setup(message request) (bool, error) { var p struct { ReplayFrom *struct{ Type string } AdditionalDirectories []string SystemPrompt json.RawMessage } if err := json.Unmarshal(message.Params, &p); err != nil { return false, invalidParams(err.Error()) } for _, dir := range p.AdditionalDirectories { if !filepath.IsAbs(dir) { return false, invalidParams("Additional directories must be absolute") } } if len(p.SystemPrompt) > 0 && string(p.SystemPrompt) != "null" { return false, invalidParams("System prompt overrides are unavailable") } if p.ReplayFrom != nil && p.ReplayFrom.Type != "start" { return false, invalidParams("Unsupported replay cursor") } return p.ReplayFrom != nil, nil } type v2Option struct { ID settingID `json:"configId"` Name string `json:"name"` Type string `json:"type"` Current string `json:"currentValue"` Category settingCategory `json:"category"` Choices []choice `json:"options"` } func (s *session) wireOptions(opts []option) any { if !s.v2 { return opts } out := make([]v2Option, 0, len(opts)) for _, o := range opts { out = append(out, v2Option{ID: o.ID, Name: o.Name, Type: o.Type, Current: o.Current, Choices: o.Choices, Category: o.Category}) } return out } func (s *session) configResult(opts []option) any { return map[string]any{"configOptions": s.wireOptions(opts)} } func (s *session) v2State(state, reason string) { u := map[string]any{"sessionUpdate": "state_update", "state": state} if reason != "" { u["stopReason"] = reason } s.update(u) } // The timestamp prefix remains a fresh UUIDv7. Its random field identifies the // client's key within the session, including after the adapter replays history. func keySuffix(session, key string) string { h := sha256.Sum256([]byte(session + "\x00" + key)) h[0] = h[0]&15 | 0x70 h[2] = h[2]&63 | 0x80 return fmt.Sprintf("%x-%x-%x", h[:2], h[2:4], h[4:10]) } func (s *session) rememberInput(id string) { if len(id) != 36 { return } if s.acceptedKeys == nil { s.acceptedKeys = make(map[string]string) } s.acceptedKeys[id[14:]] = id } func (s *session) v2Prompt(message request, blocks []json.RawMessage) { if refusal := s.promptRefusal(); refusal != nil { s.adapter.respond(message.ID, nil, refusal) return } var p struct { IdempotencyKey json.RawMessage Prompt []json.RawMessage } if err := json.Unmarshal(message.Params, &p); err != nil { s.adapter.respond(message.ID, nil, invalidParams(err.Error())) return } key := "" if p.IdempotencyKey != nil && string(p.IdempotencyKey) != "null" { if json.Unmarshal(p.IdempotencyKey, &key) != nil || len(key) == 0 || utf8.RuneCountInString(key) > 255 { s.adapter.respond(message.ID, nil, invalidParams("idempotencyKey must contain 1 to 255 characters")) return } key = keySuffix(s.id, key) if id, ok := s.acceptedKeys[key]; ok { s.adapter.respond(message.ID, map[string]string{"messageId": id}, nil) return } for _, a := range append([]*activity{s.active}, s.held...) { if a != nil && a.key == key { a.retries = append(a.retries, message.ID) return } } } a := &activity{request: message, blocks: blocks, key: key, original: p.Prompt} if s.active != nil || s.blocked() { s.held = append(s.held, a) return } s.active = a s.admit(a) } func (s *session) v2Accepted(a *activity) { if a.acknowledged { return } a.acknowledged = true id := a.handle.ID() if a.key != "" { s.rememberInput(id) } s.update(map[string]any{"sessionUpdate": "user_message", "messageId": id, "content": a.original}) s.adapter.respond(a.request.ID, map[string]string{"messageId": id}, nil) for _, r := range a.retries { s.adapter.respond(r, map[string]string{"messageId": id}, nil) } a.retries = nil s.v2State("running", "") } // Only a keyed request after a resume without replay needs this scan. Keep // the stdio reader free to dispatch cancellation and other sessions' work. func (s *session) restoreInputKeys(a *activity, cutoff int64) { ids, err := s.client.ACPInputIDs(s.ctx, cutoff) s.mu.Lock() defer s.mu.Unlock() if s.active != a || a.phase != activityPending || s.ctx.Err() != nil { return } if err != nil { s.finishPending(a, nil, err) return } for _, id := range ids { s.rememberInput(id) } s.keyHistoryCutoff = 0 if a.cancelRequested { s.finishPending(a, nil, problem(-32800, "cancelled", "Prompt cancelled before insertion")) return } s.prepareInput(a) } // A retained duplicate or a failed lookup completes the request without a turn. func (s *session) finishPending(a *activity, result any, failure error) { a.phase = activityFinishing for _, id := range a.retries { s.adapter.respond(id, result, failure) } s.writeFinal(a, s.adapter.response(a.request.ID, result, failure)) } func (s *session) cancelHeld() { s.rejectHeld(problem(-32800, "cancelled", "Prompt cancelled before insertion")) } func (s *session) rejectHeld(err error) { for _, a := range s.held { s.adapter.respond(a.request.ID, nil, err) for _, id := range a.retries { s.adapter.respond(id, nil, err) } } s.held = nil } func (s *session) nextHeld() { if len(s.held) == 0 || s.active != nil || s.blocked() || s.observation != observing { return } a := s.held[0] s.held[0] = nil s.held = s.held[1:] s.active = a s.admit(a) } func (s *session) v2Tool(u toolCall) toolCall { u.Kind = updateToolStatus absolute := func(path string) string { if filepath.IsAbs(path) { return path } return filepath.Join(s.cwd, path) } for i, location := range u.Locations { u.Locations[i].Path = absolute(location.Path) } for i, block := range u.Content { diff, ok := block.(diffBlock) if !ok { continue } operation := "modify" if diff.OldText == nil { operation = "add" } change := map[string]string{"operation": operation, "path": absolute(diff.Path), "fileType": "text"} u.Content[i] = map[string]any{"type": "diff", "changes": []map[string]string{change}} } return u }