Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .claude/skills/sdk/notes/2026-11-23-ai-3516.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`AgentConfigPatch` has a new optional field, `updated_at` (a date-time): the `updated_at` of the config a patch was made from (AI-3516). Sent, `PATCH /v1/agents/configs/{id}` refuses the patch with a 409 `conflict` when the config was saved after it; left out, nothing changes for the caller, and the router now makes the patch on the row as it stands, so two patches at once to different fields both land. Go has it through the regenerated `acceleration.AgentConfigPatch.UpdatedAt` (`sdks/go/acceleration/generated.go`), Python through the regenerated `AgentConfigPatch.updated_at` and JavaScript through the regenerated `Schemas["AgentConfigPatch"]`. Other SDKs need to update: .NET, Ruby, Rust and PHP add the field to their `AgentConfigPatch` model when they regenerate, serialised as RFC 3339 and left out when unset. Swift, Kotlin and Dart have no patch operation, which is server-side only. No SDK sends it on its own: a helper that patches a config (`UpdateConfig` in Go, `updateConfig` in JavaScript) passes it through only when its caller set it.
6 changes: 5 additions & 1 deletion acceleration/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,10 @@ components:
ui_instructions:
description: What teaches the agent's model to answer with UI. An empty string removes them.
type: string
updated_at:
description: 'The updated_at of the config this change was made from. Sent, the change is refused with a 409 conflict when the config was saved after it, so an edit made from an old copy does not write over a newer one: read the config again and make the change on that. Left out, the change is made on the config as it now is, and every field it does not send keeps what is stored.'
format: date-time
type: string
video:
$ref: '#/components/schemas/SessionVideo'
visible_tools:
Expand Down Expand Up @@ -17197,7 +17201,7 @@ paths:
description: |-
For somebody who talked to an agent and then signed up. Their sessions are rewritten to the real user and the guest is marked claimed, in one transaction: a guest marked claimed whose sessions still say the guest owns them is a person who signed up and lost their history, and sessions moved without the guest being marked is a guest that can be claimed again, by somebody else.
Server-side only, and the one operation here that most needs to be. Only the customer's own backend knows that a given guest is a given account -- it is the thing that just authenticated them. A page allowed to ask this could claim anybody's conversations by guessing a guest id, which is the whole attack.
A guest already claimed is refused rather than moved again.
A guest another account already claimed is refused. The same claim sent again finishes whatever the first left undone, and moves nothing twice.
operationId: claimGuestUser
requestBody:
content:
Expand Down
11 changes: 10 additions & 1 deletion acceleration/internal/api/config_patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api
import (
"context"
"net/http"
"time"

"github.com/danielgtaylor/huma/v2"

Expand Down Expand Up @@ -54,6 +55,7 @@ type AgentConfigPatch struct {
EndOfTurn any `json:"end_of_turn,omitempty" hidden:"true"` // refused: floor_control's max_wait_ms replaced it
Tags *map[string]string `json:"tags,omitempty"`
Video *SessionVideo `json:"video,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty" doc:"The updated_at of the config this change was made from. Sent, the change is refused with a 409 conflict when the config was saved after it, so an edit made from an old copy does not write over a newer one: read the config again and make the change on that. Left out, the change is made on the config as it now is, and every field it does not send keeps what is stored."`
}

func (*AgentConfigPatch) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema {
Expand Down Expand Up @@ -134,6 +136,11 @@ func (s *Server) registerConfigPatch(api huma.API) {

// patchAgentConfig writes what a caller changed onto a stored config.
func (s *Server) patchAgentConfig(ctx context.Context, request *patchAgentConfigRequest) (*agentConfigResponse, error) {
return onTheConfigAsItIs(func() (*agentConfigResponse, error) { return s.tryPatchAgentConfig(ctx, request) })
}

// tryPatchAgentConfig is one try of patchAgentConfig, on the config as it reads it.
func (s *Server) tryPatchAgentConfig(ctx context.Context, request *patchAgentConfigRequest) (*agentConfigResponse, error) {
customerID, ok := CustomerFrom(ctx)
if !ok {
return nil, errMissingCustomer
Expand Down Expand Up @@ -309,7 +316,9 @@ func (s *Server) patchAgentConfig(ctx context.Context, request *patchAgentConfig
return nil, invalidRequest(message)
}

if err := s.store.AgentConfigs.Update(ctx, &config); err != nil {
// Only over original, which may have come from the cache: every field this patch does not
// send is what another save since then wrote.
if err := s.store.AgentConfigs.Save(ctx, &config, original.UpdatedAt, value(patch.UpdatedAt)); err != nil {
return nil, storeFailure(err, errAgentNameTaken)
}
stored := agentConfigOf(config)
Expand Down
43 changes: 41 additions & 2 deletions acceleration/internal/api/configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,11 @@ func (s *Server) getAgentConfig(ctx context.Context, request *getAgentConfigRequ

// updateAgentConfig replaces a config with what it now is.
func (s *Server) updateAgentConfig(ctx context.Context, request *updateAgentConfigRequest) (*updateAgentConfigResponse, error) {
return onTheConfigAsItIs(func() (*updateAgentConfigResponse, error) { return s.tryUpdateAgentConfig(ctx, request) })
}

// tryUpdateAgentConfig is one try of updateAgentConfig, on the config as it reads it.
func (s *Server) tryUpdateAgentConfig(ctx context.Context, request *updateAgentConfigRequest) (*updateAgentConfigResponse, error) {
customerID, ok := CustomerFrom(ctx)
if !ok {
return nil, errMissingCustomer
Expand Down Expand Up @@ -377,7 +382,9 @@ func (s *Server) updateAgentConfig(ctx context.Context, request *updateAgentConf
} else if !ok {
return nil, invalidRequest(message)
}
if err := s.store.AgentConfigs.Update(ctx, &config); err != nil {
// Only over existing, which may have come from the cache: the fields kept from it above are
// what another save since then wrote.
if err := s.store.AgentConfigs.Save(ctx, &config, existing.UpdatedAt, time.Time{}); err != nil {
return nil, storeFailure(err, errAgentNameTaken)
}
stored := agentConfigOf(config)
Expand Down Expand Up @@ -604,6 +611,35 @@ var (
}
)

// errAgentConfigChanged is a patch made from a copy of the config older than the config: it
// sent updated_at, and the config was saved after it.
var errAgentConfigChanged = conflict("the agent config was saved after updated_at: read it again and make the change on that")

// errAgentConfigBusy is a save of an agent config that other saves replaced the config under on
// every try: sent again, it is made on the config as it then is.
var errAgentConfigBusy = conflict("the agent config was saved by others while this save was made: send it again")

// configSaveTries is how many times a save of an agent config is made in all while other saves
// keep replacing the config it was made from. A try is lost only to a save that landed while it
// ran, so this many saves of one config at once all land.
const configSaveTries = 5

// onTheConfigAsItIs runs save, which reads an agent config, makes a change to it, checks the
// result and stores it, again when another save replaced the config in between
// (store.ErrStaleAgentConfig). The change is then made and checked again on the config as it
// now is, rather than written over a config nobody checked it against.
func onTheConfigAsItIs[T any](save func() (T, error)) (T, error) {
for try := 1; ; try++ {
saved, err := save()
if !errors.Is(err, store.ErrStaleAgentConfig) {
return saved, err
}
if try == configSaveTries {
return saved, errAgentConfigBusy
}
}
}

// errAgentRoleTaken is a save that would give a second live agent config of the customer a
// role another one holds. The one there is, agent_moderator, is what the chat worker finds the
// app's moderator by, so two would leave it guessing.
Expand Down Expand Up @@ -649,7 +685,8 @@ func channelConnectionTaken(taken *store.ChannelConnectionTakenError) APIError {
// choosing another name. A record, a connection or a custom connector that is not there, such
// as one deleted after the request was checked, is the invalid request it has always been
// answered with. A channel connection another live agent config binds is a 409 naming that
// config. Anything else is the database failing rather than the
// config, and an agent config saved after the copy a patch was made from is a 409 too.
// Anything else is the database failing rather than the
// caller, so err goes back as it is, to be answered as a 500 and recorded with its stack.
func storeFailure(err error, taken APIError) error {
if owned, ok := errors.AsType[*store.ChannelConnectionTakenError](err); ok {
Expand All @@ -660,6 +697,8 @@ func storeFailure(err error, taken APIError) error {
return taken
case errors.Is(err, store.ErrRoleTaken):
return errAgentRoleTaken
case errors.Is(err, store.ErrAgentConfigChanged):
return errAgentConfigChanged
case errors.Is(err, store.ErrNoAgentConfig), errors.Is(err, store.ErrNoSkill),
errors.Is(err, store.ErrNoRouterConfig), errors.Is(err, store.ErrNoVoice),
errors.Is(err, store.ErrNoConnectorConnection), errors.Is(err, store.ErrNoConnectorDefinition):
Expand Down
135 changes: 135 additions & 0 deletions acceleration/internal/api/configs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"slices"
"strings"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -130,6 +131,140 @@ func (s *ConfigsSuite) TestPatchingAnEmptyGreetingRemovesIt() {
s.Nil(patched.Greeting)
}

// A patch wrote every column from the copy it read, so of patches at once to different fields
// the last to write put back what the others had changed.
func (s *ConfigsSuite) TestPatchesAtOnceToDifferentFieldsAllSurvive() {
created := s.createConfig(map[string]any{"name": "support"})
for round := range 10 {
patches := []map[string]any{
{"instructions": fmt.Sprintf("Be brief, %d.", round)},
{"ui_instructions": fmt.Sprintf("Answer with a card, %d.", round)},
{"greeting": map[string]any{"text": fmt.Sprintf("Hello, %d.", round)}},
{"keyterms": []string{fmt.Sprintf("Vision Agents %d", round)}},
}
statuses := make(chan int, len(patches))
var wg sync.WaitGroup
for _, patch := range patches {
wg.Go(func() {
statuses <- s.serverClient.do(http.MethodPatch, "/v1/agents/configs/"+created.Id, patch, nil)
})
}
wg.Wait()
close(statuses)
for status := range statuses {
s.Require().Equal(http.StatusOK, status)
}

var read AgentConfig
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read))
s.Equal(fmt.Sprintf("Be brief, %d.", round), value(read.Instructions), "round %d", round)
s.Equal(fmt.Sprintf("Answer with a card, %d.", round), value(read.UiInstructions), "round %d", round)
s.Require().NotNil(read.Greeting, "round %d", round)
s.Equal(fmt.Sprintf("Hello, %d.", round), read.Greeting.Text, "round %d", round)
s.Equal([]string{fmt.Sprintf("Vision Agents %d", round)}, value(read.Keyterms), "round %d", round)
}
}

// A patch sending the updated_at of the copy it was made from must not write over a save made
// after that copy was read.
func (s *ConfigsSuite) TestAPatchMadeFromACopyOlderThanTheConfigIsRefused() {
created := s.createConfig(map[string]any{"name": "support", "instructions": "Be brief."})
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPatch, "/v1/agents/configs/"+created.Id,
map[string]any{"instructions": "Be briefer."}, nil))

status, body := s.serverClient.call(http.MethodPatch, "/v1/agents/configs/"+created.Id,
map[string]any{"instructions": "Be loud.", "updated_at": created.UpdatedAt})

s.Equal(http.StatusConflict, status)
s.Contains(string(body), `"code":"conflict"`)
var read AgentConfig
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read))
s.Equal("Be briefer.", value(read.Instructions))
}

// The control: a client sending back the updated_at it was last given, by a read or by its own
// save, made its change on the config as it is, and is not refused. The two are not as precise
// as each other, a read's being the database's.
func (s *ConfigsSuite) TestAPatchSendingTheUpdatedAtItWasLastGivenIsWritten() {
created := s.createConfig(map[string]any{"name": "support"})
var read AgentConfig
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read))

var patched AgentConfig
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPatch, "/v1/agents/configs/"+created.Id,
map[string]any{"instructions": "Be brief.", "updated_at": read.UpdatedAt}, &patched))
var again AgentConfig
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPatch, "/v1/agents/configs/"+created.Id,
map[string]any{"instructions": "Be briefer.", "updated_at": patched.UpdatedAt}, &again))

s.Equal("Be briefer.", value(again.Instructions))
}

// A patch was checked against its copy of the config, read through the cache, and written onto
// a row another save had made a text agent of since: a text agent was stored with a subagent,
// which none may have. The save goes past the store, as one the cache has not heard of yet.
func (s *ConfigsSuite) TestAPatchIsCheckedAgainstTheConfigAsASaveItsCachedCopyMissedLeftIt() {
created := s.createConfig(map[string]any{"name": "support"})
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, nil),
"read, and so cached, by id")
_, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)).
Set("mode = ?", store.AgentModeText).Set("updated_at = now()").
Where("id = ?", created.Id).Exec(context.Background())
s.Require().NoError(err)

status, failure := s.serverClient.failure(http.MethodPatch, "/v1/agents/configs/"+created.Id,
map[string]any{"subagent": "llm-thinking"})

s.Equal(http.StatusBadRequest, status)
s.Contains(failure, "subagent")
var read AgentConfig
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read))
s.Equal(AgentModeText, read.Mode)
s.Nil(read.Subagent)
}

// A patch that sent the value its cached copy held kept what another save had written there
// since, and answered 200 with that: the field it sent was never written. The save goes past
// the store, as one the cache has not heard of yet.
func (s *ConfigsSuite) TestAPatchWritesAFieldItSendsThatItsCachedCopyAlreadyHeld() {
created := s.createConfig(map[string]any{"name": "support", "instructions": "Be brief."})
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, nil),
"read, and so cached, by id")
_, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)).
Set("instructions = ?", "Be loud.").Set("updated_at = now()").
Where("id = ?", created.Id).Exec(context.Background())
s.Require().NoError(err)

var patched AgentConfig
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPatch, "/v1/agents/configs/"+created.Id,
map[string]any{"instructions": "Be brief."}, &patched))

s.Equal("Be brief.", value(patched.Instructions))
var read AgentConfig
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read))
s.Equal("Be brief.", value(read.Instructions))
}

// The same through a replacement, which writes the whole config it is sent.
func (s *ConfigsSuite) TestAnUpdateWritesAFieldItSendsThatItsCachedCopyAlreadyHeld() {
created := s.createConfig(map[string]any{"name": "support", "instructions": "Be brief."})
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, nil),
"read, and so cached, by id")
_, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)).
Set("instructions = ?", "Be loud.").Set("updated_at = now()").
Where("id = ?", created.Id).Exec(context.Background())
s.Require().NoError(err)

var updated AgentConfig
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPut, "/v1/agents/configs/"+created.Id,
map[string]any{"name": "support", "instructions": "Be brief."}, &updated))

s.Equal("Be brief.", value(updated.Instructions))
var read AgentConfig
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/configs/"+created.Id, nil, &read))
s.Equal("Be brief.", value(read.Instructions))
}

func (s *ConfigsSuite) TestAnImageTargetIsStoredOnCreateAndOnEveryUpdate() {
// An update writes a named list of columns; a field missing from it is kept on create and
// silently dropped by every save after.
Expand Down
22 changes: 15 additions & 7 deletions acceleration/internal/api/guests.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,14 +304,17 @@ func (s *Server) claimGuestUser(ctx context.Context, request *claimGuestUserRequ
if err != nil {
return nil, unknownOr(err, store.ErrNotAGuest, notFound("no such guest"))
}
if guest.ClaimedBy != "" {
// A second claim naming the same account is the same claim arriving twice, which is
// not a conflict: a retried request must not read as somebody else's.
if guest.ClaimedBy == userID {
return &claimGuestUserResponse{Body: ClaimGuestResult{GuestId: guestID, UserId: userID, SessionsMoved: 0}}, nil
}
// A second claim naming the same account is the same claim arriving twice, which is not a
// conflict: a retried request must not read as somebody else's.
if guest.ClaimedBy != "" && guest.ClaimedBy != userID {
Comment thread
martinmitrevski marked this conversation as resolved.
Resolved
return nil, conflict("that guest was already claimed")
}
// Once every step below ran, the same claim has nothing left to do. Until then it runs them
// all again, since the first may have stopped after marking the guest, before the sessions
// in a shard moved or the account joined their channels.
if guest.ClaimFinishedAt != nil {
return &claimGuestUserResponse{Body: ClaimGuestResult{GuestId: guestID, UserId: userID, SessionsMoved: 0}}, nil
}

moved, err := s.store.ClaimGuest(ctx, customerID, guestID, userID)
// Another claim won since the guest was read.
Expand All @@ -335,6 +338,10 @@ func (s *Server) claimGuestUser(ctx context.Context, request *claimGuestUserRequ
s.logger.Error("claimed a guest but could not add the account to their channels",
"guest", guestID, "user", userID, "error", err)
}
// Last, so a claim that stopped before here is finished by the same claim sent again.
if err := s.store.FinishGuestClaim(ctx, customerID, guestID, userID); err != nil {
return nil, err
}

return &claimGuestUserResponse{Body: ClaimGuestResult{GuestId: guestID, UserId: userID, SessionsMoved: int(moved)}}, nil
}
Expand Down Expand Up @@ -456,7 +463,8 @@ func (s *Server) registerGuests(api huma.API) {
"own backend knows that a given guest is a given account -- it is the thing that just " +
"authenticated them. A page allowed to ask this could claim anybody's conversations by " +
"guessing a guest id, which is the whole attack.\n" +
"A guest already claimed is refused rather than moved again.",
"A guest another account already claimed is refused. The same claim sent again finishes " +
"whatever the first left undone, and moves nothing twice.",
Responses: map[string]*huma.Response{
"200": {Description: "The conversations were moved"},
"409": errorResponse("That guest was already claimed"),
Expand Down
Loading
Loading