From 605d74bb6d8f20067ad65bb24735a2590daec3bd Mon Sep 17 00:00:00 2001 From: thesyncim Date: Tue, 24 Nov 2026 23:44:10 +0000 Subject: [PATCH] fix(session): a device's new session leaves a worker's tools to the worker --- acceleration/api/openapi.yaml | 2 +- acceleration/internal/api/money.go | 2 + acceleration/internal/api/session_create.go | 2 +- .../internal/api/session_worker_tools_test.go | 233 ++++++++++++++++++ acceleration/internal/session/hosted_tools.go | 98 ++++++-- .../internal/session/hosted_tools_test.go | 27 +- acceleration/internal/session/manager.go | 22 +- .../internal/session/tool_policy_test.go | 4 +- sdks/js/src/generated/api.ts | 2 +- 9 files changed, 349 insertions(+), 43 deletions(-) create mode 100644 acceleration/internal/api/session_worker_tools_test.go diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index 910a884944..606a9b0a21 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -19055,7 +19055,7 @@ paths: application/json: schema: $ref: '#/components/schemas/ErrorResponse' - description: A session with that id already exists, or the call placed for this phone session ended without an answer (call_unanswered) + description: A session with that id already exists, a tool an end user's device declared is one a worker hosts for the session's agent, or the call placed for this phone session ended without an answer (call_unanswered) "500": $ref: '#/components/responses/InternalError' "503": diff --git a/acceleration/internal/api/money.go b/acceleration/internal/api/money.go index 045b72ec9a..a0d741d3c0 100644 --- a/acceleration/internal/api/money.go +++ b/acceleration/internal/api/money.go @@ -112,6 +112,8 @@ func refusedRequest(err error) error { switch { case errors.Is(err, session.ErrToolNotConfigured): return toolNotConfigured(err) + case errors.Is(err, session.ErrToolTaken): + return conflict(err.Error()) case errors.Is(err, session.ErrNoMemory): return errNoMemory case errors.Is(err, session.ErrNotConfigured): diff --git a/acceleration/internal/api/session_create.go b/acceleration/internal/api/session_create.go index f1d1abf017..3bbeb1dfaa 100644 --- a/acceleration/internal/api/session_create.go +++ b/acceleration/internal/api/session_create.go @@ -428,7 +428,7 @@ func (s *Server) registerSessionCreate(api huma.API) { DefaultStatus: http.StatusCreated, Responses: map[string]*huma.Response{ "201": {Description: "The agent is in the call"}, - "409": errorResponse("A session with that id already exists, or the call placed for this phone session ended without an answer (call_unanswered)"), + "409": errorResponse("A session with that id already exists, a tool an end user's device declared is one a worker hosts for the session's agent, or the call placed for this phone session ended without an answer (call_unanswered)"), }, Errors: []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound}, }, s.createSession) diff --git a/acceleration/internal/api/session_worker_tools_test.go b/acceleration/internal/api/session_worker_tools_test.go new file mode 100644 index 0000000000..a1d53ecb1a --- /dev/null +++ b/acceleration/internal/api/session_worker_tools_test.go @@ -0,0 +1,233 @@ +//go:build integration + +package api + +import ( + "context" + "encoding/json" + "net/http" + "time" + + "github.com/gorilla/websocket" + + "github.com/GetStream/Vision-Agents/acceleration/internal/auth" + "github.com/GetStream/Vision-Agents/acceleration/internal/dispatch" + "github.com/GetStream/Vision-Agents/acceleration/internal/session" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" +) + +// shareLocation is a tool a device runs. +const shareLocation = "share_location" + +func (s *SessionToolsSuite) TestADevicesNewSessionDoesNotDeclareAToolItsAgentsWorkerHosts() { + config := s.ordersAgent() + s.hostsLookupOrder(config.Name) + + for _, device := range []*testClient{s.client, s.guestClient, s.anonymousClient} { + s.Run(string(device.kind), func() { + s.assertWorkersTool(device, map[string]any{"config_id": config.ID, "tools": s.toolsNamed(shareLocation, lookupOrder)}) + }) + } +} + +func (s *SessionToolsSuite) TestADevicesNewSessionDoesNotDeclareAToolHostedForEveryAgent() { + config := s.ordersAgent() + s.hostsLookupOrder(dispatch.EveryAgent) + + s.assertWorkersTool(s.client, map[string]any{"config_id": config.ID, "tools": s.toolsNamed(lookupOrder)}) +} + +func (s *SessionToolsSuite) TestARefusedSessionOpensNoConversation() { + config := s.ordersAgent() + s.hostsLookupOrder(config.Name) + id := "session-" + s.utils.uuid() + + s.Require().Equal(http.StatusConflict, s.client.do(http.MethodPost, "/v1/agents/sessions", + CreateSessionRequest{Id: &id, ConfigId: &config.ID, Tools: s.toolsNamed(lookupOrder)}, nil)) + + _, kept := s.chat.Channel(id) + s.False(kept, "a refused session keeps no conversation") + opened := s.client.createSession(CreateSessionRequest{Id: &id, ConfigId: &config.ID}) + s.Equal(id, opened.Id, "the id is still free") + _, kept = s.chat.Channel(id) + s.True(kept, "the session's conversation is kept under its id") +} + +// A conversation carried on by its id says the agent it is kept under only once it is open. +func (s *SessionToolsSuite) TestADevicesNewSessionOnAConversationDoesNotDeclareAToolItsAgentsWorkerHosts() { + device := s.data.createUser() + agent := "agent-" + s.utils.uuid() + request := textSession(nil) + request.AgentId = &agent + opened := s.serverClient.actingFor(device).createSession(request) + device.stopSession(opened.Id) + s.hostsLookupOrder(agent) + + carried := CreateSessionRequest{LegacyConversationId: opened.ConversationId, Tools: s.toolsNamed(lookupOrder)} + s.Equal(http.StatusConflict, device.do(http.MethodPost, "/v1/agents/sessions", carried, nil)) + + carried.Tools = s.toolsNamed(shareLocation) + sources := s.toolSourcesAs(s.serverClient.actingFor(device), device.createSession(carried).Id) + s.Equal("session", sources[shareLocation]) + s.Equal("worker", sources[lookupOrder]) +} + +func (s *SessionToolsSuite) TestADevicesOwnToolsAreOfferedBesideItsWorkers() { + config := s.ordersAgent() + s.hostsLookupOrder(config.Name) + + opened := s.client.createSession(CreateSessionRequest{ConfigId: &config.ID, Tools: s.toolsNamed(shareLocation)}) + + sources := s.toolSourcesAs(s.serverClient.actingFor(s.client), opened.Id) + s.Equal("session", sources[shareLocation]) + s.Equal("worker", sources[lookupOrder]) +} + +func (s *SessionToolsSuite) TestADeviceDeclaresAToolNoWorkerHosts() { + config := s.ordersAgent() + + opened := s.client.createSession(CreateSessionRequest{ConfigId: &config.ID, Tools: s.toolsNamed(lookupOrder)}) + s.hostsLookupOrder(config.Name) + + s.Equal("session", s.toolSourcesAs(s.serverClient.actingFor(s.client), opened.Id)[lookupOrder], + "a worker that connects later leaves the session's tools as they are") +} + +func (s *SessionToolsSuite) TestADeviceDeclaresAToolItsWorkerHostsForAnotherAgent() { + config := s.ordersAgent() + s.hostsLookupOrder("agent-" + s.utils.uuid()) + + opened := s.client.createSession(CreateSessionRequest{ConfigId: &config.ID, Tools: s.toolsNamed(lookupOrder)}) + + s.Equal("session", s.toolSourcesAs(s.serverClient.actingFor(s.client), opened.Id)[lookupOrder]) +} + +func (s *SessionToolsSuite) TestABackendsSessionKeepsItsOwnToolOverItsWorkers() { + config := s.ordersAgent() + s.hostsLookupOrder(config.Name) + + opened := s.serverClient.createSession(CreateSessionRequest{ConfigId: &config.ID, Tools: s.toolsNamed(lookupOrder)}) + + s.Equal("session", s.toolSources(opened.Id)[lookupOrder]) +} + +func (s *SessionToolsSuite) TestADevicesConversationIsCarriedOnWithTheToolAWorkerHostsNow() { + config := s.ordersAgent() + device := s.data.createUser() + opened := device.createSession(CreateSessionRequest{ConfigId: &config.ID, Tools: s.toolsNamed(shareLocation, lookupOrder)}) + s.hostsLookupOrder(config.Name) + + s.endHere(opened.Id) + s.Require().Equal(http.StatusOK, + device.do(http.MethodPost, "/v1/agents/sessions/"+opened.Id+"/resume", ResumeSessionRequest{}, nil)) + s.assertTakenOver(device, opened.Id) + + s.endHere(opened.Id) + s.Require().Equal(http.StatusOK, device.do(http.MethodPost, "/v1/agents/sessions/"+opened.Id+"/resume", + ResumeSessionRequest{Tools: s.toolsNamed(shareLocation, lookupOrder)}, nil)) + s.assertTakenOver(device, opened.Id) +} + +func (s *SessionToolsSuite) TestADevicesForkHasTheToolAWorkerHostsNow() { + config := s.ordersAgent() + device := s.data.createUser() + opened := device.createSession(CreateSessionRequest{ConfigId: &config.ID, Tools: s.toolsNamed(shareLocation, lookupOrder)}) + s.hostsLookupOrder(config.Name) + + var forked Session + s.Require().Equal(http.StatusCreated, device.do(http.MethodPost, "/v1/agents/sessions/"+opened.Id+"/fork", + ForkSessionRequest{Messages: pointerTo(false)}, &forked)) + + s.assertTakenOver(device, forked.Id) + parent, held := s.manager.Get(opened.Id, session.Owner{CustomerID: s.customerID(), Kind: auth.KindServer}) + s.Require().True(held) + var declared []string + for _, tool := range parent.Spec().Tools { + declared = append(declared, tool.Name) + } + s.Equal([]string{shareLocation, lookupOrder}, declared, "the running parent keeps its tools") +} + +// A worker's call in a conversation carried on is the worker's to run, and is not shown as the +// tool the device declared. +func (s *SessionToolsSuite) TestACallInADevicesConversationCarriedOnIsTheWorkersToRun() { + config := s.ordersAgent() + device := s.data.createUser() + tools := s.toolsNamed(lookupOrder) + (*tools)[0].DisplayTitle, (*tools)[0].Executor = pointerTo("The device's title"), pointerTo(SessionToolExecutorClient) + opened := device.createSession(CreateSessionRequest{ConfigId: &config.ID, Tools: tools}) + worker := s.hostsLookupOrder(config.Name) + s.endHere(opened.Id) + s.Require().Equal(http.StatusOK, device.do(http.MethodPost, "/v1/agents/sessions/"+opened.Id+"/resume", ResumeSessionRequest{}, nil)) + + events := device.opens("/v1/agents/sessions/" + opened.Id + "/events") + + status, body := s.serverClient.actingFor(device).call(http.MethodPost, + "/v1/agents/sessions/"+opened.Id+"/respond", RespondRequest{Text: "where is my order", RequestId: pointerTo("request-" + s.utils.uuid())}) + s.Require().Equal(http.StatusOK, status, string(body)) + s.hostedCallUser(worker) + + s.Require().NoError(events.SetReadDeadline(time.Now().Add(settleFor))) + for { + var frame map[string]any + s.Require().NoError(events.ReadJSON(&frame)) + message, _ := frame["message"].(map[string]any) + parts, _ := message["parts"].([]any) + for _, part := range parts { + if step, _ := part.(map[string]any); step["name"] == lookupOrder { + s.Equal("server", step["executor"]) + s.NotEqual("The device's title", step["display_title"]) + return + } + } + } +} + +// assertTakenOver checks the session has the worker's lookup_order and the device's other +// tool, and that the device can still give it more. +func (s *SessionToolsSuite) assertTakenOver(device *testClient, id string) { + sources := s.toolSourcesAs(s.serverClient.actingFor(device), id) + s.Equal("session", sources[shareLocation]) + s.Equal("worker", sources[lookupOrder]) + s.Equal(http.StatusConflict, s.addTools(device, id, s.lookupOrder())) + s.Equal(http.StatusNoContent, s.addTools(device, id, SessionTool{Name: "open_camera", Description: "open the camera"})) + s.Equal(http.StatusNoContent, device.do(http.MethodDelete, "/v1/agents/sessions/"+id+"/tools/open_camera", nil, nil)) +} + +// assertWorkersTool checks createSession and the session socket refuse the device's session +// with the same answer, naming lookup_order alone. +func (s *SessionToolsSuite) assertWorkersTool(device *testClient, sent map[string]any) { + const message = "session: the session offers a tool by that name that is not its caller's: lookup_order" + status, body := device.call(http.MethodPost, "/v1/agents/sessions", sent) + s.Require().Equal(http.StatusConflict, status, string(body)) + var created ErrorResponse + s.Require().NoError(json.Unmarshal(body, &created)) + s.Equal(message, created.Error.Message) + s.Equal("conflict", created.Error.Code) + + connection := device.opens("/v1/agents/socket") + s.Require().NoError(connection.WriteJSON(map[string]any{"type": "start", "sample_rate": 24_000, "session": sent})) + refused := s.await(connection, "error") + s.Equal(message, refused["error"]) + _, _, err := connection.ReadMessage() + s.True(websocket.IsCloseError(err, websocket.ClosePolicyViolation), "the socket closes: %v", err) +} + +// ordersAgent is an agent config whose tool groups name a device's tools and a worker's. +func (s *SessionToolsSuite) ordersAgent() store.AgentConfig { + config := store.AgentConfig{CustomerID: s.customerID(), Name: "orders-" + s.utils.uuid(), + Mode: store.AgentModeText, Models: store.AgentModels{LLM: "tooling/tool-model"}, + VisibleTools: []string{lookupOrder}, + ToolGroups: []store.ToolGroup{{Name: "orders", Tools: []string{lookupOrder, shareLocation, "open_camera"}}}} + s.Require().NoError(s.store.AgentConfigs.Insert(context.Background(), &config)) + return config +} + +// toolsNamed are the tools a caller declares by name. +func (s *SessionToolsSuite) toolsNamed(names ...string) *[]SessionTool { + var tools []SessionTool + for _, name := range names { + tools = append(tools, SessionTool{Name: name, Description: "the caller's " + name}) + } + return &tools +} diff --git a/acceleration/internal/session/hosted_tools.go b/acceleration/internal/session/hosted_tools.go index efa94617d0..ed28ab6c10 100644 --- a/acceleration/internal/session/hosted_tools.go +++ b/acceleration/internal/session/hosted_tools.go @@ -3,13 +3,18 @@ package session import ( "context" "errors" + "fmt" "log/slog" + "slices" + "strings" "time" "github.com/GetStream/Vision-Agents/acceleration/internal/agent" + "github.com/GetStream/Vision-Agents/acceleration/internal/auth" "github.com/GetStream/Vision-Agents/acceleration/internal/dispatch" "github.com/GetStream/Vision-Agents/acceleration/internal/harness" "github.com/GetStream/Vision-Agents/acceleration/internal/llm" + "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) // ToolHosts are the workers that run tools for sessions they did not open. The dispatch pool @@ -23,33 +28,83 @@ type ToolHosts interface { // Set once, before sessions are served. func (m *Manager) HostTools(hosts ToolHosts) { m.hosts = hosts } -// hostedTools adds what workers run for the session's agent to what the caller declared, -// and returns the runner that sends those calls to them. A name the caller declared stays -// the caller's: whoever opened the session is the one it asked to run it. +// workerTools are the tools workers host for a session as it opens. +type workerTools struct { + // hostedAs is the agent id own are hosted under. + hostedAs string + own []dispatch.Tool + // everyAgent are the ones hosted for every agent (dispatch.EveryAgent). + everyAgent []dispatch.Tool +} + +// workerTools reads what workers host for the session's agent. // // The agent is the session's agent id, or failing that the name its config was opened by, -// since a session opened by name carries an agent id of its own. The worker running a call -// reaches the session through conversation. A tool no group of the session's config names -// is left out: the worker connected before the session opened, so there is nobody to refuse. -// -// Tools hosted for every agent (dispatch.EveryAgent) come after the agent's own, and only -// where a group of the session's config names them: registered once for the app, each agent -// takes the ones its agent.yaml enables, so the others are not worth a warning. -func (m *Manager) hostedTools(spec Spec, loading toolLoading, sessionID string, conversation dispatch.Progress, declared []harness.Tool, next agent.ToolRunner) ([]harness.Tool, agent.ToolRunner) { +// since a session opened by name carries an agent id of its own. +func (m *Manager) workerTools(spec Spec, loading toolLoading) workerTools { + var found workerTools if m.hosts == nil { - return declared, next + return found } - var offered []dispatch.Tool - hostedAs := "" for _, agentID := range []string{spec.AgentID, spec.AgentName} { if agentID == "" { continue } - if offered, _ = m.hosts.HostedTools(spec.CustomerID, agentID); len(offered) > 0 { - hostedAs = agentID + if found.own, _ = m.hosts.HostedTools(spec.CustomerID, agentID); len(found.own) > 0 { + found.hostedAs = agentID break } } + if loading.configured { + found.everyAgent, _ = m.hosts.HostedTools(spec.CustomerID, dispatch.EveryAgent) + } + return found +} + +// keepWorkersTools leaves the names workers host to the workers, in a session no backend +// opened: a worker is the app's backend, and a backend's tool is not a device's to run +// (Session.seatRuns). A new session that declares one is refused. A fork and a conversation +// carried on bring tools declared before, so the worker's is used in place of theirs. +func (w workerTools) keepWorkersTools(spec *Spec) error { + if spec.CallerKind == auth.KindServer { + return nil + } + hosted := func(tool harness.Tool) bool { + return slices.ContainsFunc(slices.Concat(w.own, w.everyAgent), + func(worker dispatch.Tool) bool { return worker.Name == tool.Name }) + } + if spec.Reopened.IsZero() && spec.ForkedFrom == "" { + var taken []string + for _, tool := range spec.Tools { + if hosted(tool) { + taken = append(taken, tool.Name) + } + } + if len(taken) > 0 { + return stack.Wrap(fmt.Errorf("%w: %s", ErrToolTaken, strings.Join(taken, ", "))) + } + return nil + } + spec.Tools = slices.DeleteFunc(slices.Clone(spec.Tools), hosted) + return nil +} + +// hostedTools adds what workers run for the session's agent to what the caller declared, +// and returns the runner that sends those calls to them. A name a backend declared on its +// session stays its own; no other caller has one a worker hosts (keepWorkersTools). +// +// The worker running a call reaches the session through conversation. A tool no group of the +// session's config names is left out: the worker connected before the session opened, so +// there is nobody to refuse. +// +// Tools hosted for every agent (dispatch.EveryAgent) come after the agent's own, and only +// where a group of the session's config names them: registered once for the app, each agent +// takes the ones its agent.yaml enables, so the others are not worth a warning. +func (m *Manager) hostedTools(spec Spec, loading toolLoading, workers workerTools, sessionID string, conversation dispatch.Progress, declared []harness.Tool, next agent.ToolRunner) ([]harness.Tool, agent.ToolRunner) { + if m.hosts == nil { + return declared, next + } + hostedAs := workers.hostedAs taken := map[string]bool{} for _, tool := range declared { taken[tool.Name] = true @@ -69,7 +124,7 @@ func (m *Manager) hostedTools(spec Spec, loading toolLoading, sessionID string, declared = append(declared, offered) } var ungrouped []string - for _, tool := range offered { + for _, tool := range workers.own { if taken[tool.Name] { continue } @@ -79,12 +134,9 @@ func (m *Manager) hostedTools(spec Spec, loading toolLoading, sessionID string, } offer(hostedAs, tool) } - if loading.configured { - everyAgent, _ := m.hosts.HostedTools(spec.CustomerID, dispatch.EveryAgent) - for _, tool := range everyAgent { - if !taken[tool.Name] && loading.grouped(tool.Name) { - offer(dispatch.EveryAgent, tool) - } + for _, tool := range workers.everyAgent { + if !taken[tool.Name] && loading.grouped(tool.Name) { + offer(dispatch.EveryAgent, tool) } } if len(ungrouped) > 0 { diff --git a/acceleration/internal/session/hosted_tools_test.go b/acceleration/internal/session/hosted_tools_test.go index 25eb93f7af..62af2cff01 100644 --- a/acceleration/internal/session/hosted_tools_test.go +++ b/acceleration/internal/session/hosted_tools_test.go @@ -6,6 +6,7 @@ import ( "testing" "time" + "github.com/GetStream/Vision-Agents/acceleration/internal/auth" "github.com/GetStream/Vision-Agents/acceleration/internal/dispatch" "github.com/GetStream/Vision-Agents/acceleration/internal/harness" "github.com/GetStream/Vision-Agents/acceleration/internal/llm" @@ -51,13 +52,13 @@ func TestASessionNamingAHostedAgentIsOfferedTheWorkersTools(t *testing.T) { hosts := &fakeHosts{} m := &Manager{logger: slog.Default(), hosts: hosts} caller := &callerTools{} - declared := []harness.Tool{{Name: "search_docs", Description: "The browser's search"}} + declared := []harness.Tool{{Name: "search_docs", Description: "The backend's search"}} - // The shape a browser opens: an agent id, no stored config, and its own search. - spec := Spec{CustomerID: "acme", AgentID: "stream-support"} - tools, runner := m.hostedTools(spec, newToolLoading(spec), "session-1", nil, declared, caller) + // The shape a backend opens: an agent id, no stored config, and its own search. + spec := Spec{CustomerID: "acme", AgentID: "stream-support", CallerKind: auth.KindServer} + tools, runner := m.hostedTools(spec, newToolLoading(spec), m.workerTools(spec, newToolLoading(spec)), "session-1", nil, declared, caller) - if len(tools) != 2 || tools[0].Description != "The browser's search" || tools[1].Name != "investigate_sdk" { + if len(tools) != 2 || tools[0].Description != "The backend's search" || tools[1].Name != "investigate_sdk" { t.Fatalf("offered %+v", tools) } if _, err := runner.Run(context.Background(), llm.ToolCall{ID: "1", Name: "investigate_sdk"}); err != nil { @@ -83,7 +84,7 @@ func TestASessionOpenedByAgentNameIsOfferedTheWorkersTools(t *testing.T) { CustomerID: "acme", AgentID: "01JC-generated", ConfigID: "cfg-1", AgentName: "stream-support", ToolGroups: []store.ToolGroup{{Name: "support", Tools: []string{"investigate_sdk", "search_docs"}}}, } - tools, runner := m.hostedTools(spec, newToolLoading(spec), "session-1", nil, nil, &callerTools{}) + tools, runner := m.hostedTools(spec, newToolLoading(spec), m.workerTools(spec, newToolLoading(spec)), "session-1", nil, nil, &callerTools{}) if len(tools) != 2 || tools[0].Name != "investigate_sdk" { t.Fatalf("offered %+v", tools) @@ -101,12 +102,12 @@ func TestASessionNamingAnotherAgentIsOfferedNothingHosted(t *testing.T) { caller := &callerTools{} sales := Spec{CustomerID: "acme", AgentID: "sales"} - tools, runner := m.hostedTools(sales, newToolLoading(sales), "s", nil, nil, caller) + tools, runner := m.hostedTools(sales, newToolLoading(sales), m.workerTools(sales, newToolLoading(sales)), "s", nil, nil, caller) if len(tools) != 0 || runner != caller { t.Fatalf("offered %+v", tools) } byConfig := Spec{CustomerID: "acme", ConfigID: "stream-support"} - tools, _ = m.hostedTools(byConfig, newToolLoading(byConfig), "s", nil, nil, caller) + tools, _ = m.hostedTools(byConfig, newToolLoading(byConfig), m.workerTools(byConfig, newToolLoading(byConfig)), "s", nil, nil, caller) if len(tools) != 0 { t.Fatalf("a session naming the agent only as a config was offered %+v", tools) } @@ -121,7 +122,7 @@ func TestAHostedCallCarriesTheConversationItWasMadeIn(t *testing.T) { conversation := hostedConversation{} spec := Spec{CustomerID: "acme", AgentID: "stream-support"} - _, runner := m.hostedTools(spec, newToolLoading(spec), "session-1", conversation, nil, nil) + _, runner := m.hostedTools(spec, newToolLoading(spec), m.workerTools(spec, newToolLoading(spec)), "session-1", conversation, nil, nil) if _, err := runner.Run(context.Background(), llm.ToolCall{ID: "1", Name: "investigate_sdk"}); err != nil { t.Fatal(err) } @@ -138,7 +139,7 @@ func TestAWorkersToolNoGroupNamesIsNotOffered(t *testing.T) { ToolGroups: []store.ToolGroup{{Name: "docs", Tools: []string{"search_docs"}}}, } - tools, _ := m.hostedTools(spec, newToolLoading(spec), "session-1", nil, nil, &callerTools{}) + tools, _ := m.hostedTools(spec, newToolLoading(spec), m.workerTools(spec, newToolLoading(spec)), "session-1", nil, nil, &callerTools{}) if len(tools) != 1 || tools[0].Name != "search_docs" { t.Fatalf("offered %+v", tools) @@ -156,7 +157,7 @@ func TestAToolHostedForEveryAgentIsOfferedWhereAToolGroupNamesIt(t *testing.T) { CustomerID: "acme", AgentID: "01JC-generated", ConfigID: "cfg-1", AgentName: "concierge", ToolGroups: []store.ToolGroup{{Name: "outside", Tools: []string{"weather_lookup"}}}, } - tools, runner := m.hostedTools(weather, newToolLoading(weather), "session-1", nil, nil, &callerTools{}) + tools, runner := m.hostedTools(weather, newToolLoading(weather), m.workerTools(weather, newToolLoading(weather)), "session-1", nil, nil, &callerTools{}) if len(tools) != 1 || tools[0].Name != "weather_lookup" { t.Fatalf("offered %+v", tools) } @@ -168,7 +169,7 @@ func TestAToolHostedForEveryAgentIsOfferedWhereAToolGroupNamesIt(t *testing.T) { } unconfigured := Spec{CustomerID: "acme", AgentID: "browser-agent"} - if tools, _ := m.hostedTools(unconfigured, newToolLoading(unconfigured), "s", nil, nil, &callerTools{}); len(tools) != 0 { + if tools, _ := m.hostedTools(unconfigured, newToolLoading(unconfigured), m.workerTools(unconfigured, newToolLoading(unconfigured)), "s", nil, nil, &callerTools{}); len(tools) != 0 { t.Errorf("a session with no config to enable them was offered %+v", tools) } } @@ -181,7 +182,7 @@ func TestAnAgentsOwnHostedToolWinsOverOneHostedForEveryAgent(t *testing.T) { ToolGroups: []store.ToolGroup{{Name: "docs", Tools: []string{"search_docs"}}}, } - tools, runner := m.hostedTools(spec, newToolLoading(spec), "session-1", nil, nil, &callerTools{}) + tools, runner := m.hostedTools(spec, newToolLoading(spec), m.workerTools(spec, newToolLoading(spec)), "session-1", nil, nil, &callerTools{}) if len(tools) != 1 || tools[0].Description != "The worker's search" { t.Fatalf("offered %+v", tools) } diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index 444ef4de46..e1d3e08080 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -541,6 +541,19 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er if err != nil { return nil, err } + // A conversation carried on says its agent once it is open. For every other session the + // tools are settled before anything is opened. + carriedOn := spec.PersistConversation && spec.ConversationID != "" + var workers workerTools + settleTools := func() error { + workers = m.workerTools(spec, loading) + return workers.keepWorkersTools(&spec) + } + if !carriedOn { + if err := settleTools(); err != nil { + return nil, err + } + } if spec.PersistConversation { service, err := m.Conversations() if err != nil { @@ -589,7 +602,6 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er // knows the one its transcript was written under. spec.AgentID = conv.Agent() spec.ContextTruncated = truncated - conv.DescribeTools(toolDisplays(spec.Tools)) // A fork opens an empty channel of its own and then reads the parent's, so the model // carries on from what was said while the transcripts stay separate. The parent's // half goes first because it happened first. @@ -608,6 +620,12 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er conv.Release() } }() + if carriedOn { + if err := settleTools(); err != nil { + return nil, err + } + } + conv.DescribeTools(toolDisplays(spec.Tools)) } else if spec.ConversationID != "" { service, err := m.Conversations() if err != nil { @@ -711,7 +729,7 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er sources := map[string]ToolSource{} markTools(sources, tools, ToolFromSession) var callers agent.ToolRunner = created.tools - tools, callers = m.hostedTools(spec, loading, created.id, hostedProgress{created}, tools, callers) + tools, callers = m.hostedTools(spec, loading, workers, created.id, hostedProgress{created}, tools, callers) markTools(sources, tools[len(spec.Tools):], ToolFromWorker) tools, callers = moderationTools(spec, stream, tools, callers) if line != nil || m.reading(spec) || m.searching(spec) || spec.endsCalls() { diff --git a/acceleration/internal/session/tool_policy_test.go b/acceleration/internal/session/tool_policy_test.go index 021fa2d8b2..72d8a0eedc 100644 --- a/acceleration/internal/session/tool_policy_test.go +++ b/acceleration/internal/session/tool_policy_test.go @@ -67,7 +67,7 @@ func (s *ToolPolicySuite) TestAWorkersToolKeepsItsPolicies() { }}} spec := Spec{CustomerID: "acme", AgentID: "support"} - tools, _ := m.hostedTools(spec, newToolLoading(spec), "session-1", nil, nil, nil) + tools, _ := m.hostedTools(spec, newToolLoading(spec), m.workerTools(spec, newToolLoading(spec)), "session-1", nil, nil, nil) s.Require().Len(tools, 1) s.True(tools[0].Interruptible) @@ -81,7 +81,7 @@ func (s *ToolPolicySuite) TestAWorkersToolAsksItsApprovalQuestion() { }}} spec := Spec{CustomerID: "acme", AgentID: "support"} - tools, _ := m.hostedTools(spec, newToolLoading(spec), "session-1", nil, nil, nil) + tools, _ := m.hostedTools(spec, newToolLoading(spec), m.workerTools(spec, newToolLoading(spec)), "session-1", nil, nil, nil) s.Require().Len(tools, 2) s.Equal(&harness.ToolApproval{Title: "Book flight {flight_id}?"}, tools[0].Approval) diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index b2f86d4169..f3ef485bd8 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -17071,7 +17071,7 @@ export interface operations { readonly 402: components["responses"]["PaymentRequired"]; readonly 403: components["responses"]["Forbidden"]; readonly 404: components["responses"]["NotFound"]; - /** @description A session with that id already exists, or the call placed for this phone session ended without an answer (call_unanswered) */ + /** @description A session with that id already exists, a tool an end user's device declared is one a worker hosts for the session's agent, or the call placed for this phone session ended without an answer (call_unanswered) */ readonly 409: { headers: { readonly [name: string]: unknown;