diff --git a/.claude/skills/sdk/notes/2026-11-23-ai-3516.md b/.claude/skills/sdk/notes/2026-11-23-ai-3516.md
new file mode 100644
index 0000000000..0dd62b7ad4
--- /dev/null
+++ b/.claude/skills/sdk/notes/2026-11-23-ai-3516.md
@@ -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.
diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml
index 9f916f17fa..6688429a24 100644
--- a/acceleration/api/openapi.yaml
+++ b/acceleration/api/openapi.yaml
@@ -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:
@@ -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:
diff --git a/acceleration/internal/api/config_patch.go b/acceleration/internal/api/config_patch.go
index 8f1468d0a1..1b4c611d63 100644
--- a/acceleration/internal/api/config_patch.go
+++ b/acceleration/internal/api/config_patch.go
@@ -3,6 +3,7 @@ package api
import (
"context"
"net/http"
+ "time"
"github.com/danielgtaylor/huma/v2"
@@ -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 {
@@ -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
@@ -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)
diff --git a/acceleration/internal/api/configs.go b/acceleration/internal/api/configs.go
index 43f9c233a8..dac0637136 100644
--- a/acceleration/internal/api/configs.go
+++ b/acceleration/internal/api/configs.go
@@ -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
@@ -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)
@@ -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.
@@ -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 {
@@ -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):
diff --git a/acceleration/internal/api/configs_test.go b/acceleration/internal/api/configs_test.go
index ab565f4b90..d6042c988e 100644
--- a/acceleration/internal/api/configs_test.go
+++ b/acceleration/internal/api/configs_test.go
@@ -9,6 +9,7 @@ import (
"net/http"
"slices"
"strings"
+ "sync"
"testing"
"time"
@@ -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.
diff --git a/acceleration/internal/api/guests.go b/acceleration/internal/api/guests.go
index ee09d8372f..e8eee626a6 100644
--- a/acceleration/internal/api/guests.go
+++ b/acceleration/internal/api/guests.go
@@ -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 {
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.
@@ -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
}
@@ -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"),
diff --git a/acceleration/internal/api/guests_test.go b/acceleration/internal/api/guests_test.go
index 198e703743..3d955c3784 100644
--- a/acceleration/internal/api/guests_test.go
+++ b/acceleration/internal/api/guests_test.go
@@ -398,6 +398,39 @@ func (s *GuestsSuite) TestTheSameClaimArrivingTwiceIsNotAConflict() {
s.Equal(0, again.SessionsMoved, "the conversations moved the first time")
}
+// A claim that stopped once the guest was marked, before the account joined the channels of
+// the conversations it moved, was answered as done when sent again, and the account never
+// could read them. The store's half is all the first claim got through.
+func (s *GuestsSuite) TestAClaimThatStoppedAfterMovingTheRowsJoinsTheChannelsWhenSentAgain() {
+ guest, account := s.recordGuest(), s.data.createUser()
+ talked := s.talked(guest)
+ _, err := s.store.ClaimGuest(context.Background(), s.customerID(), guest, account.userID)
+ s.Require().NoError(err)
+ s.Require().NotContains(s.chat.Members(s.transcriptOf(talked)), account.userID)
+
+ s.claim(guest, account.userID)
+
+ s.Contains(s.chat.Members(s.transcriptOf(talked)), account.userID, "the account reads what the guest said")
+}
+
+// A claim sent again once every step of it ran did them all again: a backend that claims at
+// every sign-in put the account back into the channel of a conversation it had left, with two
+// Stream calls for each of the account's conversations every time.
+func (s *GuestsSuite) TestAFinishedClaimSentAgainLeavesTheChannelsAsTheyAre() {
+ guest, account := s.recordGuest(), s.data.createUser()
+ talked := s.talked(guest)
+ s.claim(guest, account.userID)
+ channel := s.transcriptOf(talked)
+ s.Require().Contains(s.chat.Members(channel), account.userID)
+ _, err := s.chat.Client.Chat().UpdateChannel(context.Background(), chatlog.ChannelType, channel,
+ &getstream.UpdateChannelRequest{RemoveMembers: []string{account.userID}})
+ s.Require().NoError(err)
+
+ s.claim(guest, account.userID)
+
+ s.NotContains(s.chat.Members(channel), account.userID, "the claim had nothing left to do")
+}
+
func (s *GuestsSuite) TestAGuestSomebodyElseClaimedIsAConflict() {
guest := s.recordGuest()
s.claim(guest, s.utils.uuid())
diff --git a/acceleration/internal/api/sync.go b/acceleration/internal/api/sync.go
index 312de69428..879769f003 100644
--- a/acceleration/internal/api/sync.go
+++ b/acceleration/internal/api/sync.go
@@ -7,6 +7,7 @@ import (
"fmt"
"net/http"
"strings"
+ "time"
"github.com/danielgtaylor/huma/v2"
@@ -196,6 +197,11 @@ func (s *Server) registerSync(api huma.API) {
// The hash is a fingerprint of that directory. A second call with the same hash does
// nothing, so a process that syncs on startup is cheap when nothing has changed.
func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syncAgentResponse, error) {
+ return onTheConfigAsItIs(func() (*syncAgentResponse, error) { return s.trySyncAgent(ctx, request) })
+}
+
+// trySyncAgent is one try of syncAgent, on the config as it reads it.
+func (s *Server) trySyncAgent(ctx context.Context, request *syncAgentRequest) (*syncAgentResponse, error) {
customerID, ok := CustomerFrom(ctx)
if !ok {
return nil, errMissingCustomer
@@ -413,10 +419,14 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn
config.UIInstructions = value(body.UiInstructions)
config.Skills = named
config.KnowledgeNamespace = namespace
- config.SyncHash = hash
+ // The hash is written last, after the skills and simulations: written here, a sync whose
+ // skills then failed was found unchanged when sent again, and never wrote them.
+ config.SyncHash = ""
if found {
- if err := s.store.AgentConfigs.Update(ctx, &config); err != nil {
+ // Only over existing, which may have come from the cache: every setting the directory
+ // does not declare is 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)
}
} else {
@@ -442,6 +452,15 @@ func (s *Server) syncAgent(ctx context.Context, request *syncAgentRequest) (*syn
return nil, err
}
}
+ // Only over the config as this sync left it: one saved since no longer holds what the
+ // directory says, and is written again by the next sync of it.
+ marked := config
+ marked.SyncHash = hash
+ if err := s.store.AgentConfigs.Save(ctx, &marked, config.UpdatedAt, time.Time{}); err == nil {
+ config = marked
+ } else if !errors.Is(err, store.ErrStaleAgentConfig) {
+ return nil, err
+ }
// Recorded last, after the skills the directory brought with it, because what it marks
// is the moment the whole directory and the whole stored agent agreed. An entry written
// before the skills would leave each of them looking like an edit made since the sync,
diff --git a/acceleration/internal/api/sync_test.go b/acceleration/internal/api/sync_test.go
index 33e724e8ed..ff11061813 100644
--- a/acceleration/internal/api/sync_test.go
+++ b/acceleration/internal/api/sync_test.go
@@ -8,16 +8,39 @@ import (
"fmt"
"net/http"
"strings"
+ "sync/atomic"
"testing"
+ "github.com/uptrace/bun"
+
"github.com/GetStream/Vision-Agents/acceleration/internal/connectors/providers"
"github.com/GetStream/Vision-Agents/acceleration/internal/store"
)
type SyncSuite struct {
RouterSuite
+ // between runs a test's step in the middle of a sync, before a query of its choosing.
+ between *beforeQuery
+}
+
+// beforeQuery runs a test's step once, just before the first query that holds its marker, as
+// another writer's save landing in the middle of a request.
+type beforeQuery struct{ step atomic.Pointer[queryStep] }
+
+type queryStep struct {
+ marker string
+ run func()
}
+func (b *beforeQuery) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context {
+ if step := b.step.Load(); step != nil && strings.Contains(event.Query, step.marker) && b.step.CompareAndSwap(step, nil) {
+ step.run()
+ }
+ return ctx
+}
+
+func (*beforeQuery) AfterQuery(context.Context, *bun.QueryEvent) {}
+
func TestSyncSuite(t *testing.T) {
runSuite(t, new(SyncSuite))
}
@@ -28,6 +51,8 @@ func (s *SyncSuite) SetupSuite() {
s.speechToSpeech = true
s.RouterSuite.SetupSuite()
s.Require().NoError(s.store.ConnectorDefinitions.Seed(context.Background(), providers.FS))
+ s.between = &beforeQuery{}
+ s.store.GlobalDB().AddQueryHook(s.between)
}
// SetupTest gives every test an app of its own, because a sync is named by what the agent
@@ -341,6 +366,90 @@ func (s *SyncSuite) TestASyncWhosePageCannotBeStoredIsAnInternalError() {
s.NotContains(string(body), "deadline")
}
+// The hash was stored with the config, before the skills: a sync whose skills then failed was
+// found unchanged when sent again, and its skills were never written.
+func (s *SyncSuite) TestASyncWhoseSkillsFailedOnceWritesThemWhenSentAgain() {
+ declaration := map[string]any{"name": "support", "hash": "v1", "skills": []map[string]string{
+ {"config_id": "", "name": "refund", "description": "work out a refund", "instructions": "Read the policy."},
+ }}
+ s.failQueries(`INSERT INTO "skills"`)
+ status, _ := s.serverClient.call(http.MethodPost, "/v1/agents/sync", declaration)
+ s.Require().Equal(http.StatusInternalServerError, status)
+ s.failing.value.Store(nil)
+
+ again := s.sync(declaration)
+
+ s.False(again.Unchanged, "the first sync did not finish, so this one has work to do")
+ s.Equal("Read the policy.", s.skillNamed(again.Config.Id, "refund").Instructions)
+ s.Equal("v1", value(again.Config.SyncHash))
+}
+
+// A sync wrote every setting from the copy of the config it read, which can come from the
+// cache, so a model saved since that the directory does not declare went back to what the copy
+// held. The update below goes past the store, as a save the cache has not heard of yet.
+func (s *SyncSuite) TestASyncKeepsAModelSavedSinceItReadTheConfigThatItsDirectoryDoesNotDeclare() {
+ declaration := map[string]any{"name": "support", "hash": "v1", "instructions": "Be brief.", "llm": "llm-flow"}
+ synced := s.sync(declaration)
+ s.Require().True(s.sync(declaration).Unchanged, "read, and so cached, by name")
+ _, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)).
+ Set("llm = ?", "llm-thinking").Set("updated_at = now()").
+ Where("id = ?", synced.Config.Id).Exec(context.Background())
+ s.Require().NoError(err)
+
+ result := s.sync(map[string]any{"name": "support", "hash": "v2", "instructions": "Be briefer."})
+
+ s.Equal("Be briefer.", value(result.Config.Instructions))
+ s.Equal("llm-thinking", value(result.Config.Llm), "the directory says nothing of the model")
+}
+
+// A sync whose copy of the config, read through the cache, missed a dashboard save kept the
+// dashboard's wording of a setting its directory declares, and still wrote its hash: every later
+// sync of the directory found nothing changed. The save goes past the store, as one the cache has
+// not heard of yet.
+func (s *SyncSuite) TestASyncWritesWhatItsDirectoryDeclaresOverASaveItsCachedCopyMissed() {
+ declaration := map[string]any{"name": "support", "hash": "v1", "instructions": "Be brief."}
+ synced := s.sync(declaration)
+ s.Require().True(s.sync(declaration).Unchanged, "read, and so cached, by name")
+ _, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)).
+ Set("instructions = ?", "Dashboard wording.").Set("sync_hash = ''").Set("updated_at = now()").
+ Where("id = ?", synced.Config.Id).Exec(context.Background())
+ s.Require().NoError(err)
+
+ result := s.sync(map[string]any{"name": "support", "hash": "v2", "instructions": "Be brief."})
+
+ s.Equal("Be brief.", value(result.Config.Instructions))
+ s.Equal("v2", value(result.Config.SyncHash))
+ s.Equal("Be brief.", value(s.configsNamed("support")[0].Instructions))
+}
+
+// The hash said the config held the directory although a save landed between the sync's write
+// of the config and of its hash, so every later sync of the directory found nothing changed and
+// never wrote it again. The save goes past the store, as one the cache has not heard of yet.
+func (s *SyncSuite) TestASyncLeavesItsHashOffAConfigSavedWhileItWroteItsSkills() {
+ declaration := map[string]any{"name": "support", "hash": "v1", "instructions": "Be brief.",
+ "skills": []map[string]string{
+ {"config_id": "", "name": "refund", "description": "work out a refund", "instructions": "Read the policy."},
+ }}
+ saved := make(chan error, 1)
+ s.between.step.Store(&queryStep{marker: `INSERT INTO "skills"`, run: func() {
+ _, err := s.store.GlobalDB().NewUpdate().Model((*store.AgentConfig)(nil)).
+ Set("instructions = ?", "Dashboard wording.").Set("sync_hash = ''").Set("updated_at = now()").
+ Where("customer_id = ?", s.customerID()).Where("name = ?", "support").Exec(context.Background())
+ saved <- err
+ }})
+ s.T().Cleanup(func() { s.between.step.Store(nil) })
+
+ s.sync(declaration)
+ s.Require().Len(saved, 1, "the save landed in the middle of the sync")
+ s.Require().NoError(<-saved)
+ s.Empty(value(s.configsNamed("support")[0].SyncHash), "the config no longer holds the directory")
+
+ again := s.sync(declaration)
+
+ s.False(again.Unchanged)
+ s.Equal("Be brief.", value(again.Config.Instructions))
+}
+
func (s *SyncSuite) TestASyncDeclaringAPageThatIsNotAFetchablePageIsRefusedInItsWords() {
status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/sync", map[string]any{
"name": "librarian", "hash": "v1",
diff --git a/acceleration/internal/store/agent_config.go b/acceleration/internal/store/agent_config.go
index 9d5a2550cb..305afd6568 100644
--- a/acceleration/internal/store/agent_config.go
+++ b/acceleration/internal/store/agent_config.go
@@ -372,6 +372,15 @@ func (r *AgentConfigs) Insert(ctx context.Context, config *AgentConfig) error {
return nil
}
+// ErrAgentConfigChanged says a save was refused because the config is not the one saved at
+// the updated_at its caller made the change from (Save's unmodifiedSince).
+var ErrAgentConfigChanged = errors.New("store: save agent config: saved since the caller's updated_at")
+
+// ErrStaleAgentConfig says a save was refused because it was made from a copy of the config,
+// read through the cache or not, that another save has replaced since. Nothing was written,
+// and the cached copies of the config are forgotten, so a read now returns it as it is.
+var ErrStaleAgentConfig = errors.New("store: save agent config: saved since the copy was read")
+
// Update replaces a config a customer holds. Every field is written, so an update is what the
// config now is rather than what changed about it. A connection it binds as fixed is locked as
// Insert locks it, and has to be live unless the stored config binds it already: a forced
@@ -381,6 +390,26 @@ func (r *AgentConfigs) Insert(ctx context.Context, config *AgentConfig) error {
// The config is forgotten under its id and under both the name it had and the one it has, since
// a rename leaves whoever asked for the old name holding a config that no longer answers to it.
func (r *AgentConfigs) Update(ctx context.Context, config *AgentConfig) error {
+ return r.save(ctx, config, time.Time{}, time.Time{})
+}
+
+// Save is Update for a change made to a copy of the config, the one stored at read: it is
+// written only over that config. When another save has replaced it since, nothing is written
+// and ErrStaleAgentConfig says so, so a change checked against one config is never written
+// over another one nobody checked it against. The caller reads the config again and makes its
+// change on that. With unmodifiedSince set, the config must also be the one saved then, or the
+// save is refused with ErrAgentConfigChanged.
+//
+// Both are compared with the row's updated_at for equality, at the column's microseconds. A
+// later-than comparison would let through a save whose replica's clock is behind.
+func (r *AgentConfigs) Save(ctx context.Context, config *AgentConfig, read, unmodifiedSince time.Time) error {
+ return r.save(ctx, config, read, unmodifiedSince)
+}
+
+// save is Update when read is zero and Save otherwise. The row is locked first and what it binds
+// after, the order every write of a stored config takes them in, so no two writes wait on each
+// other in a cycle: neither a connection delete nor Insert locks a stored config's row.
+func (r *AgentConfigs) save(ctx context.Context, config *AgentConfig, read, unmodifiedSince time.Time) error {
if config.ID == "" {
return stack.Wrap(&ValidationError{Model: "agent config", Field: "id", Reason: "is required"})
}
@@ -391,8 +420,27 @@ func (r *AgentConfigs) Update(ctx context.Context, config *AgentConfig) error {
config.UpdatedAt = time.Now().UTC()
- var wasName string
+ var stored AgentConfig
err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error {
+ err := tx.NewSelect().Model(&stored).Column("name", "connectors", "tags", "updated_at").
+ Where("id = ?", config.ID).
+ Where("customer_id = ?", config.CustomerID).
+ Where("deleted_at IS NULL").
+ For("UPDATE").
+ Scan(ctx)
+ if errors.Is(err, sql.ErrNoRows) {
+ return unknownAgentConfig(config.ID)
+ }
+ if err != nil {
+ return fmt.Errorf("store: update agent config: %w", err)
+ }
+ if !unmodifiedSince.IsZero() && !stored.UpdatedAt.Equal(unmodifiedSince.Truncate(time.Microsecond)) {
+ return ErrAgentConfigChanged
+ }
+ if !read.IsZero() && !stored.UpdatedAt.Equal(read.Truncate(time.Microsecond)) {
+ return ErrStaleAgentConfig
+ }
+
missing, err := lockBoundConnections(ctx, tx, config)
if err != nil {
return err
@@ -401,17 +449,6 @@ func (r *AgentConfigs) Update(ctx context.Context, config *AgentConfig) error {
if err != nil {
return err
}
- var stored AgentConfig
- if len(missing) > 0 || len(undefined) > 0 || bindsAnyFixed(config.Connectors) {
- err := tx.NewSelect().Model(&stored).Column("connectors", "tags").
- Where("id = ?", config.ID).
- Where("customer_id = ?", config.CustomerID).
- Where("deleted_at IS NULL").
- Scan(ctx)
- if err != nil && !errors.Is(err, sql.ErrNoRows) {
- return fmt.Errorf("store: update agent config: %w", err)
- }
- }
if err := refuseUnbindable(missing, stored.Connectors); err != nil {
return err
}
@@ -421,43 +458,31 @@ func (r *AgentConfigs) Update(ctx context.Context, config *AgentConfig) error {
if err := refuseSecondChannelAgent(ctx, tx, config, stored.Connectors, stored.TestCopy()); err != nil {
return err
}
- // The name the row had is read in the same statement, locked, so the one forgotten is
- // the one a concurrent rename did not already replace.
- was := tx.NewSelect().Model((*AgentConfig)(nil)).Column("name").
- Where("id = ?", config.ID).
- Where("customer_id = ?", config.CustomerID).
- Where("deleted_at IS NULL").
- For("UPDATE")
- err = tx.NewUpdate().Model(config).
- With("was", was).
- TableExpr("was").
+ _, err = tx.NewUpdate().Model(config).
Column(configColumns...).
Where("ac.id = ?", config.ID).
Where("ac.customer_id = ?", config.CustomerID).
- Returning("was.name").
- Scan(ctx, &wasName)
+ Exec(ctx)
switch constraint(err) {
case "agent_configs_name_idx":
return ErrNameTaken
case "agent_configs_role_idx":
return ErrRoleTaken
}
- if errors.Is(err, sql.ErrNoRows) {
- return unknownAgentConfig(config.ID)
- }
if err != nil {
return fmt.Errorf("store: update agent config: %w", err)
}
return nil
}, func() []string {
- // Named once the write answered: a commit that fails can still have landed.
- if wasName == "" {
+ // Named once the locked read found the row: a commit that fails can still have landed,
+ // and a save refused as stale leaves the copy it was made from to be read again.
+ if stored.Name == "" {
return nil
}
return []string{
agentConfigKey(config.CustomerID, config.ID),
agentConfigNameKey(config.CustomerID, config.Name),
- agentConfigNameKey(config.CustomerID, wasName),
+ agentConfigNameKey(config.CustomerID, stored.Name),
}
})
if err != nil {
@@ -686,8 +711,9 @@ func (r *AgentConfigs) where(ctx context.Context, customerID, column, value stri
// FOR KEY SHARE, not FOR SHARE: it conflicts with the delete's FOR UPDATE and not with the
// FOR NO KEY UPDATE a plain UPDATE of a non-key column takes (table 13.3,
// https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS), so a config
-// save does not hold up a credential save. The connection is locked before the config row,
-// as in the delete, so the two never wait on each other in a cycle.
+// save does not hold up a credential save. A config write locks its own row before the
+// connection, and the delete locks no config row, so the two never wait on each other in a
+// cycle.
func lockBoundConnections(ctx context.Context, tx bun.Tx, config *AgentConfig) ([]string, error) {
var bound []string
for _, binding := range config.Connectors {
@@ -724,11 +750,6 @@ func refuseUnbindable(missing []string, kept []ConnectorBinding) error {
return nil
}
-// bindsAnyFixed reports whether a binding has a fixed connection.
-func bindsAnyFixed(bindings []ConnectorBinding) bool {
- return slices.ContainsFunc(bindings, func(binding ConnectorBinding) bool { return binding.Connection.Type == "fixed" })
-}
-
// boundConnectors are the connector ids bindings name.
func boundConnectors(bindings []ConnectorBinding) []string {
ids := make([]string, 0, len(bindings))
diff --git a/acceleration/internal/store/agent_config_test.go b/acceleration/internal/store/agent_config_test.go
index dc15b89a10..72fce25360 100644
--- a/acceleration/internal/store/agent_config_test.go
+++ b/acceleration/internal/store/agent_config_test.go
@@ -80,6 +80,61 @@ func (s *StoreSuite) TestAnUpdateKeepsABindingAForcedDeleteLeftBehind() {
s.Equal([]ConnectorBinding{fixed(connection.ID)}, read.Connectors)
}
+// A save wrote every column from the copy it was made from, so a column another save changed
+// since that copy was read went back to what the copy held, and the change was written over a
+// config nobody had checked it against.
+func (s *StoreSuite) TestASaveMadeFromACopyAnotherSaveReplacedWritesNothing() {
+ read := s.boundConfig("acme-app")
+ other := read
+ other.Greeting = "Hello."
+ s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, &other))
+
+ mine := read
+ mine.Instructions = "be brief"
+ s.Require().ErrorIs(s.store.AgentConfigs.Save(s.ctx, &mine, read.UpdatedAt, time.Time{}), ErrStaleAgentConfig)
+
+ stored, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", read.ID)
+ s.Require().NoError(err)
+ s.Equal("Hello.", stored.Greeting, "the other save's greeting is kept")
+ s.Empty(stored.Instructions, "nothing of the stale copy is written")
+}
+
+// A save asked to refuse a config saved after the version its caller made the change from must
+// not write over that save, even when its own copy is the config as stored.
+func (s *StoreSuite) TestASaveFromACopyOlderThanTheConfigIsRefusedWhenAskedTo() {
+ read := s.boundConfig("acme-app")
+ other := read
+ other.Instructions = "be brief"
+ s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, &other))
+
+ mine := other
+ mine.Instructions = "be loud"
+ s.Require().ErrorIs(s.store.AgentConfigs.Save(s.ctx, &mine, other.UpdatedAt, read.UpdatedAt), ErrAgentConfigChanged)
+
+ stored, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", read.ID)
+ s.Require().NoError(err)
+ s.Equal("be brief", stored.Instructions)
+}
+
+// A replica whose clock is behind writes an updated_at earlier than the one before it, and a
+// later-than comparison let a save made from that one through, over the save it did not see.
+func (s *StoreSuite) TestASaveIsRefusedOverASaveWhoseClockWasBehind() {
+ read := s.boundConfig("acme-app")
+ earlier := read.UpdatedAt.Add(-time.Hour).Truncate(time.Microsecond)
+ _, err := s.store.GlobalDB().NewUpdate().Model((*AgentConfig)(nil)).
+ Set("instructions = ?", "be brief").Set("updated_at = ?", earlier).
+ Where("id = ?", read.ID).Exec(s.ctx)
+ s.Require().NoError(err)
+
+ mine := read
+ mine.Instructions = "be loud"
+ s.Require().ErrorIs(s.store.AgentConfigs.Save(s.ctx, &mine, earlier, read.UpdatedAt), ErrAgentConfigChanged)
+
+ var stored AgentConfig
+ s.Require().NoError(s.store.GlobalDB().NewSelect().Model(&stored).Where("id = ?", read.ID).Scan(s.ctx))
+ s.Equal("be brief", stored.Instructions)
+}
+
func (s *StoreSuite) TestAConfigWithoutBindingsStoresAnEmptyList() {
created := s.boundConfig("acme-app")
@@ -282,8 +337,12 @@ func (s *StoreSuite) TestAgentConfigQueryBudgets() {
s.Require().NoError(err)
}))
config.Instructions = "be brief"
- s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, &config)) }),
- "begin, the update and commit: a config that binds nothing locks no connection")
+ s.Equal(4, s.countQueries(func() { s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, &config)) }),
+ "begin, the locked read, the update and commit: a config that binds nothing locks no connection")
+ read := config.UpdatedAt
+ config.Greeting = "Hello."
+ s.Equal(4, s.countQueries(func() { s.Require().NoError(s.store.AgentConfigs.Save(s.ctx, &config, read, read)) }),
+ "the same as an update: the copy is held against the row the locked read returns")
if s.store.cache != nil {
for range 2 {
_, err := s.store.AgentConfigs.Get(s.ctx, "acme-app", config.ID)
diff --git a/acceleration/internal/store/channel_owner.go b/acceleration/internal/store/channel_owner.go
index 114d110c96..3c63284dd6 100644
--- a/acceleration/internal/store/channel_owner.go
+++ b/acceleration/internal/store/channel_owner.go
@@ -123,8 +123,9 @@ func refuseSecondChannelAgent(ctx context.Context, tx bun.Tx, config *AgentConfi
// lockChannelOwner takes the lock a channel connection's owner is decided under
// (refuseSecondChannelAgent) when the live connection id is a channel connection, and returns
-// its connector and whether it is one. A write that also locks the config's row takes this
-// lock first, as UpdateAgentConfig does, or the two would wait on each other in a cycle.
+// its connector and whether it is one. A write of a stored config locks the config's row
+// before this lock (AgentConfigs.save), and Insert locks no stored row, so two writes never
+// wait on each other in a cycle.
func lockChannelOwner(ctx context.Context, tx bun.Tx, customerID, id string) (string, bool, error) {
var connection ConnectorConnection
err := tx.NewSelect().Model(&connection).Column("id", "connector_id", "definition_revision").
diff --git a/acceleration/internal/store/models.go b/acceleration/internal/store/models.go
index 7ab6c02db3..eb24a2bca6 100644
--- a/acceleration/internal/store/models.go
+++ b/acceleration/internal/store/models.go
@@ -485,6 +485,9 @@ type User struct {
// person's conversations onto another's account.
ClaimedBy string `bun:"claimed_by,nullzero"`
ClaimedAt *time.Time `bun:"claimed_at"`
+ // ClaimFinishedAt is when every step of ClaimedBy's claim ran (FinishGuestClaim), nil
+ // while a claim that set ClaimedBy has not got that far.
+ ClaimFinishedAt *time.Time `bun:"claim_finished_at"`
// RefreshSecretHash is the SHA-256 of the refresh secret this guest was last handed
// (GuestSecretHash), nil for one handed none. Never sent anywhere: it is the credential
// that lets a guest whose token expired come back as themselves.
diff --git a/acceleration/internal/store/session_test.go b/acceleration/internal/store/session_test.go
index 06c7b7623b..363821a794 100644
--- a/acceleration/internal/store/session_test.go
+++ b/acceleration/internal/store/session_test.go
@@ -1103,6 +1103,25 @@ func (s *StoreSuite) TestClaimingAGuestMovesTheirScheduledTasks() {
}
}
+// A claim marked finished for anybody but the account that claimed the guest would have the
+// guest's own claim skip the steps it still owes, sent again.
+func (s *StoreSuite) TestAGuestClaimIsFinishedOnlyForTheAccountThatClaimedIt() {
+ s.Require().NoError(s.store.RecordGuest(s.ctx, &User{ID: "guest-1", CustomerID: "acme", Name: "Guest"}))
+ s.Require().NoError(s.store.FinishGuestClaim(s.ctx, "acme", "guest-1", "account-1"))
+ _, err := s.store.ClaimGuest(s.ctx, "acme", "guest-1", "account-1")
+ s.Require().NoError(err)
+ s.Require().NoError(s.store.FinishGuestClaim(s.ctx, "acme", "guest-1", "mallory"))
+ guest, err := s.store.Guest(s.ctx, "acme", "guest-1")
+ s.Require().NoError(err)
+ s.Require().Nil(guest.ClaimFinishedAt, "finished before the claim, or by another account")
+
+ s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.FinishGuestClaim(s.ctx, "acme", "guest-1", "account-1")) }))
+
+ guest, err = s.store.Guest(s.ctx, "acme", "guest-1")
+ s.Require().NoError(err)
+ s.NotNil(guest.ClaimFinishedAt)
+}
+
// sessionIDs is the ids of the sessions, in the order they were found.
func sessionIDs(sessions []AgentSession) []string {
found := make([]string, 0, len(sessions))
diff --git a/acceleration/internal/store/sessions.go b/acceleration/internal/store/sessions.go
index cd8d9259bf..e14480fceb 100644
--- a/acceleration/internal/store/sessions.go
+++ b/acceleration/internal/store/sessions.go
@@ -143,8 +143,9 @@ func (s *Store) Guest(ctx context.Context, customerID, id string) (User, error)
// somebody else. A task left on the guest follows up for nobody who can still see it.
//
// With shards, the guest and the tasks are in the shared database and the sessions in every
-// shard, and no transaction spans them. The guest is claimed with its tasks first, and a claim
-// by the same user again moves whatever sessions a failed one left behind.
+// shard, and no transaction spans them. The guest is claimed with its tasks first. A claim by
+// the same user again moves whatever sessions a failed one left behind, with shards or without,
+// so a caller with steps after this one can finish them on a retry.
func (s *Store) ClaimGuest(ctx context.Context, customerID, guestID, userID string) (int64, error) {
if customerID == "" || guestID == "" || userID == "" {
return 0, stack.Wrap(errors.New("store: a customer, a guest and a user id are required"))
@@ -186,7 +187,7 @@ func (s *Store) ClaimGuest(ctx context.Context, customerID, guestID, userID stri
if !s.Sharded() && len(s.peers) == 0 {
var moved int64
err := s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
- if err := claimGuest(ctx, tx, customerID, guestID, userID, now, false); err != nil {
+ if err := claimGuest(ctx, tx, customerID, guestID, userID, now); err != nil {
return err
}
if err := moveTasks(ctx, tx); err != nil {
@@ -209,7 +210,7 @@ func (s *Store) ClaimGuest(ctx context.Context, customerID, guestID, userID stri
}
err := s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
- if err := claimGuest(ctx, tx, customerID, guestID, userID, now, true); err != nil {
+ if err := claimGuest(ctx, tx, customerID, guestID, userID, now); err != nil {
return err
}
return moveTasks(ctx, tx)
@@ -224,9 +225,9 @@ func (s *Store) ClaimGuest(ctx context.Context, customerID, guestID, userID stri
return moved, nil
}
-// claimGuest marks a guest claimed by userID. sameUserAgain lets a claim userID already made
-// stand rather than fail, for a caller that has more to finish after it.
-func claimGuest(ctx context.Context, db bun.IDB, customerID, guestID, userID string, now time.Time, sameUserAgain bool) error {
+// claimGuest marks a guest claimed by userID. A claim userID already made stands rather than
+// fails, for a caller that has more to finish after it.
+func claimGuest(ctx context.Context, db bun.IDB, customerID, guestID, userID string, now time.Time) error {
claimed, err := db.NewUpdate().Model((*User)(nil)).
Set("claimed_by = ?", userID).
Set("claimed_at = ?", now).
@@ -261,12 +262,32 @@ func claimGuest(ctx context.Context, db bun.IDB, customerID, guestID, userID str
if err != nil {
return fmt.Errorf("claim guest: %w", err)
}
- if sameUserAgain && existing.ClaimedBy == userID {
+ if existing.ClaimedBy == userID {
return nil
}
return stack.Wrap(fmt.Errorf("%w: %s was already claimed by %s", ErrGuestClaimed, guestID, existing.ClaimedBy))
}
+// FinishGuestClaim records that every step of userID's claim of a guest ran, so the same claim
+// sent again has nothing left to do. A guest userID has not claimed is left as it is.
+func (s *Store) FinishGuestClaim(ctx context.Context, customerID, guestID, userID string) error {
+ if customerID == "" || guestID == "" || userID == "" {
+ return stack.Wrap(errors.New("store: a customer, a guest and a user id are required"))
+ }
+ _, err := s.global.NewUpdate().Model((*User)(nil)).
+ Set("claim_finished_at = ?", time.Now().UTC()).
+ Where("id = ?", guestID).
+ Where("customer_id = ?", customerID).
+ Where("kind = ?", UserKindGuest).
+ Where("claimed_by = ?", userID).
+ Where("claim_finished_at IS NULL").
+ Exec(ctx)
+ if err != nil {
+ return stack.Wrap(fmt.Errorf("store: finish guest claim: %w", err))
+ }
+ return nil
+}
+
// ErrGuestClaimed is a guest another user has already claimed.
var ErrGuestClaimed = errors.New("store: guest claimed")
diff --git a/acceleration/migrations/global/20270201000700_guest_claim_finished.sql b/acceleration/migrations/global/20270201000700_guest_claim_finished.sql
new file mode 100644
index 0000000000..8797381959
--- /dev/null
+++ b/acceleration/migrations/global/20270201000700_guest_claim_finished.sql
@@ -0,0 +1,10 @@
+-- +goose Up
+SET LOCAL lock_timeout = '5s';
+
+-- When every step of a guest's claim ran: its sessions moved and the account joined their
+-- channels. NULL while a claim that set claimed_by has not got that far, so the same claim sent
+-- again runs its steps again; once set, the same claim sent again has nothing left to do.
+ALTER TABLE users ADD COLUMN IF NOT EXISTS claim_finished_at timestamptz;
+
+-- +goose Down
+ALTER TABLE users DROP COLUMN IF EXISTS claim_finished_at;
diff --git a/acceleration/schema/global.sql b/acceleration/schema/global.sql
index 53b9684181..7c14bdfb80 100644
--- a/acceleration/schema/global.sql
+++ b/acceleration/schema/global.sql
@@ -1347,6 +1347,7 @@ TABLE user_phones
CREATE UNIQUE INDEX user_phones_phone ON public.user_phones USING btree (customer_id, stream_app_pk, phone)
TABLE users
+ claim_finished_at timestamp with time zone
claimed_at timestamp with time zone
claimed_by text
created_at timestamp with time zone NOT NULL DEFAULT now()
diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/claim_guest_user.py b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/claim_guest_user.py
index 84e35f3166..b1c2770af8 100644
--- a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/claim_guest_user.py
+++ b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/claim_guest_user.py
@@ -110,7 +110,8 @@ def sync_detailed(
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.
Args:
body (ClaimGuestRequest):
@@ -149,7 +150,8 @@ def sync(
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.
Args:
body (ClaimGuestRequest):
@@ -183,7 +185,8 @@ async def asyncio_detailed(
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.
Args:
body (ClaimGuestRequest):
@@ -220,7 +223,8 @@ async def asyncio(
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.
Args:
body (ClaimGuestRequest):
diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/agent_config_patch.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/agent_config_patch.py
index 6d6e9f05c9..77223ba5f9 100644
--- a/plugins/stream/vision_agents/plugins/stream/_generated/models/agent_config_patch.py
+++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/agent_config_patch.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import datetime
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, cast
@@ -137,6 +138,10 @@ class AgentConfigPatch:
agents (list[ChildAgent] | Unset): Replaces the list whole. An empty list removes it.
image (str | Unset): An empty string removes it, and the agent stops being offered generate_image.
ui_instructions (str | Unset): What teaches the agent's model to answer with UI. An empty string removes them.
+ updated_at (datetime.datetime | Unset): 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.
"""
calls: AgentCalls | Unset = UNSET
@@ -180,6 +185,7 @@ class AgentConfigPatch:
agents: list[ChildAgent] | Unset = UNSET
image: str | Unset = UNSET
ui_instructions: str | Unset = UNSET
+ updated_at: datetime.datetime | Unset = UNSET
def to_dict(self) -> dict[str, Any]:
from ..models.agent_config_patch_plugins_item_type_1 import (
@@ -347,6 +353,10 @@ def to_dict(self) -> dict[str, Any]:
ui_instructions = self.ui_instructions
+ updated_at: str | Unset = UNSET
+ if not isinstance(self.updated_at, Unset):
+ updated_at = self.updated_at.isoformat()
+
field_dict: dict[str, Any] = {}
field_dict.update({})
@@ -432,6 +442,8 @@ def to_dict(self) -> dict[str, Any]:
field_dict["image"] = image
if ui_instructions is not UNSET:
field_dict["ui_instructions"] = ui_instructions
+ if updated_at is not UNSET:
+ field_dict["updated_at"] = updated_at
return field_dict
@@ -694,6 +706,13 @@ def _parse_plugins_item(
ui_instructions = d.pop("ui_instructions", UNSET)
+ _updated_at = d.pop("updated_at", UNSET)
+ updated_at: datetime.datetime | Unset
+ if isinstance(_updated_at, Unset):
+ updated_at = UNSET
+ else:
+ updated_at = datetime.datetime.fromisoformat(_updated_at)
+
agent_config_patch = cls(
calls=calls,
channels=channels,
@@ -736,6 +755,7 @@ def _parse_plugins_item(
agents=agents,
image=image,
ui_instructions=ui_instructions,
+ updated_at=updated_at,
)
return agent_config_patch
diff --git a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs
index 7cd3aa78ef..1b84fb7883 100644
--- a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs
+++ b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs
@@ -1243,6 +1243,12 @@ public partial class AgentConfigPatch
[System.Text.Json.Serialization.JsonPropertyName("ui_instructions")]
public string? UiInstructions { get; set; } = default!;
+ ///
+ /// 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.
+ ///
+ [System.Text.Json.Serialization.JsonPropertyName("updated_at")]
+ public System.DateTimeOffset? UpdatedAt { get; set; } = default!;
+
[System.Text.Json.Serialization.JsonPropertyName("video")]
public SessionVideo? Video { get; set; } = default!;
diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go
index 38b779e035..2f1f498a87 100644
--- a/sdks/go/acceleration/generated.go
+++ b/sdks/go/acceleration/generated.go
@@ -4028,8 +4028,11 @@ type AgentConfigPatch struct {
Tts *string `json:"tts,omitempty"`
// UiInstructions What teaches the agent's model to answer with UI. An empty string removes them.
- UiInstructions *string `json:"ui_instructions,omitempty"`
- Video *SessionVideo `json:"video,omitempty"`
+ UiInstructions *string `json:"ui_instructions,omitempty"`
+
+ // UpdatedAt 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.
+ UpdatedAt *time.Time `json:"updated_at,omitempty"`
+ Video *SessionVideo `json:"video,omitempty"`
// VisibleTools Tools whose steps end users see on a persistent conversation's replies, as tool names or path.Match patterns such as athena_*. Only a step's name, status and timing are shown, never its arguments or result. A shown tool whose result is exactly {"status":"answered","citations":[...]} also adds those citations to the reply's sources. An empty list shows search and web_search.
VisibleTools *[]string `json:"visible_tools,omitempty"`
@@ -14316,7 +14319,7 @@ type ClientInterface interface {
//
// 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.
//
// Takes any type of body and a specified content type.
//
@@ -14327,7 +14330,7 @@ type ClientInterface interface {
//
// 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.
//
// Takes a body of the `application/json` content type.
//
@@ -18742,7 +18745,7 @@ func (c *Client) CreateGuestUser(ctx context.Context, body CreateGuestUserJSONRe
//
// 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.
//
// Takes any type of body and a specified content type.
//
@@ -18763,7 +18766,7 @@ func (c *Client) ClaimGuestUserWithBody(ctx context.Context, contentType string,
//
// 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.
//
// Takes a body of the `application/json` content type.
//
@@ -37629,7 +37632,7 @@ type ClientWithResponsesInterface interface {
//
// 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.
//
// Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s).
//
@@ -37640,7 +37643,7 @@ type ClientWithResponsesInterface interface {
//
// 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.
//
// Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s).
//
@@ -69575,7 +69578,7 @@ func (c *ClientWithResponses) CreateGuestUserWithResponse(ctx context.Context, b
//
// 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.
//
// Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s).
//
@@ -69592,7 +69595,7 @@ func (c *ClientWithResponses) ClaimGuestUserWithBodyWithResponse(ctx context.Con
//
// 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.
//
// Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s).
//
diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts
index be8e37731d..bc7eecf0a9 100644
--- a/sdks/js/src/generated/api.ts
+++ b/sdks/js/src/generated/api.ts
@@ -1464,7 +1464,7 @@ export type paths = {
* Move a guest's conversations onto the account they turned out to be
* @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.
*/
readonly post: operations["claimGuestUser"];
readonly delete?: never;
@@ -5061,6 +5061,11 @@ export type components = {
readonly tts?: string;
/** @description What teaches the agent's model to answer with UI. An empty string removes them. */
readonly ui_instructions?: string;
+ /**
+ * Format: date-time
+ * @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.
+ */
+ readonly updated_at?: string;
readonly video?: components["schemas"]["SessionVideo"];
/** @description Tools whose steps end users see on a persistent conversation's replies, as tool names or path.Match patterns such as athena_*. Only a step's name, status and timing are shown, never its arguments or result. A shown tool whose result is exactly {"status":"answered","citations":[...]} also adds those citations to the reply's sources. An empty list shows search and web_search. */
readonly visible_tools?: readonly string[];
diff --git a/sdks/php/src/Generated/AgentConfigPatch.php b/sdks/php/src/Generated/AgentConfigPatch.php
index 5a44077ce2..a6f5731f7b 100644
--- a/sdks/php/src/Generated/AgentConfigPatch.php
+++ b/sdks/php/src/Generated/AgentConfigPatch.php
@@ -86,6 +86,8 @@ public function __construct(
public ?string $image = null,
// What teaches the agent's model to answer with UI. An empty string removes them.
public ?string $uiInstructions = null,
+ // The updated_at of the config this change was made from. Sent, the change is refused with a 409 conflict whe...
+ public ?\DateTimeImmutable $updatedAt = null,
) {
}
@@ -136,6 +138,7 @@ public static function fromArray(array $data): self
agents: array_key_exists('agents', $data) && $data['agents'] !== null ? array_map(ChildAgent::fromArray(...), Json::objects($data, 'agents')) : null,
image: array_key_exists('image', $data) && $data['image'] !== null ? Json::string($data, 'image') : null,
uiInstructions: array_key_exists('ui_instructions', $data) && $data['ui_instructions'] !== null ? Json::string($data, 'ui_instructions') : null,
+ updatedAt: array_key_exists('updated_at', $data) && $data['updated_at'] !== null ? Json::date($data, 'updated_at') : null,
);
}
@@ -270,6 +273,9 @@ public function toArray(): array
if ($this->uiInstructions !== null) {
$out['ui_instructions'] = $this->uiInstructions;
}
+ if ($this->updatedAt !== null) {
+ $out['updated_at'] = Json::dateValue($this->updatedAt);
+ }
return $out;
}
}
diff --git a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb
index dfd46670ad..2496d3a998 100644
--- a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb
+++ b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb
@@ -1920,7 +1920,7 @@ module Generated
required: %w[created_at id mode name region updated_at].freeze, open: false
}.freeze,
"AgentConfigPatch" => {
- properties: %w[agents calls channels chat_channels connectors dispatch episode_cards floor_control greeting guardrail harness image instructions keyterms knowledge_namespace llm llm_fallbacks mcp_servers mode name plugin_events plugins region resume_history review role sandbox sandbox_options scheduling search skills sts stt subagent tags tools tts ui_instructions video visible_tools voice].freeze,
+ properties: %w[agents calls channels chat_channels connectors dispatch episode_cards floor_control greeting guardrail harness image instructions keyterms knowledge_namespace llm llm_fallbacks mcp_servers mode name plugin_events plugins region resume_history review role sandbox sandbox_options scheduling search skills sts stt subagent tags tools tts ui_instructions updated_at video visible_tools voice].freeze,
required: [].freeze, open: false
}.freeze,
"AgentConfigRequest" => {
diff --git a/sdks/rust/src/types.rs b/sdks/rust/src/types.rs
index 14e11a415d..b90d80196e 100644
--- a/sdks/rust/src/types.rs
+++ b/sdks/rust/src/types.rs
@@ -819,6 +819,9 @@ pub struct AgentConfigPatch {
///What teaches the agent's model to answer with UI. An empty string removes them.
#[serde(skip_serializing_if = "::std::option::Option::is_none")]
pub ui_instructions: ::std::option::Option<::std::string::String>,
+ ///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.
+ #[serde(skip_serializing_if = "::std::option::Option::is_none")]
+ pub updated_at: ::std::option::Option<::std::string::String>,
#[serde(skip_serializing_if = "::std::option::Option::is_none")]
pub video: ::std::option::Option,
///Tools whose steps end users see on a persistent conversation's replies, as tool names or path.Match patterns such as athena_*. Only a step's name, status and timing are shown, never its arguments or result. A shown tool whose result is exactly {"status":"answered","citations":[...]} also adds those citations to the reply's sources. An empty list shows search and web_search.