diff --git a/pkg/acp/agent.go b/pkg/acp/agent.go index 8f93a1046e..140bf04251 100644 --- a/pkg/acp/agent.go +++ b/pkg/acp/agent.go @@ -706,6 +706,11 @@ func (a *Agent) reconnectSession(ctx context.Context, params acp.ResumeSessionRe } acpSess.rememberModelSelection(name, value, "", selected.SnapshotModelOverride()) } + if restorer, ok := acpSess.rt.(interface { + RestoreSessionToolsetState(ctx context.Context, sess *session.Session) + }); ok { + restorer.RestoreSessionToolsetState(ctx, sess) + } acpSess.id = sid acpSess.sess = sess acpSess.workingDir = sess.WorkingDir diff --git a/pkg/runtime/durable.go b/pkg/runtime/durable.go index 120c92893e..b916268b96 100644 --- a/pkg/runtime/durable.go +++ b/pkg/runtime/durable.go @@ -158,7 +158,7 @@ func (r *DurableRuntime) giveUp(ctx context.Context, sess *session.Session, why // endRun stores sess, which stands at its run's last finished step, and // drops the run's record. The record goes last: until the store holds the // session, the record is all that says where it stood. -func (r *DurableRuntime) endRun(ctx context.Context, sess *session.Session) error { +func (r *LocalRuntime) endRun(ctx context.Context, sess *session.Session) error { if err := r.sessionStore.UpdateSession(ctx, sess); err != nil { return fmt.Errorf("storing session %q: %w", sess.ID, err) } @@ -221,6 +221,22 @@ type sessionState struct { OutputTokens int64 `json:"output_tokens,omitempty"` SafetyPolicy session.SafetyPolicy `json:"safety_policy,omitempty"` Permissions *session.PermissionsConfig `json:"permissions,omitempty"` + Attributes map[string]string `json:"attributes,omitempty"` + HasToolsetState bool `json:"has_toolset_state,omitempty"` +} + +func toolsetAttributesOf(attrs map[string]string) map[string]string { + var filtered map[string]string + for k, v := range attrs { + if !session.IsToolsetAttributeKey(k) { + continue + } + if filtered == nil { + filtered = make(map[string]string) + } + filtered[k] = v + } + return filtered } func sessionStateOf(sess *session.Session) sessionState { @@ -228,6 +244,8 @@ func sessionStateOf(sess *session.Session) sessionState { InstructionContext: sess.InstructionContextSnapshot(), SafetyPolicy: sess.GetSafetyPolicy(), Permissions: sess.ClonePermissions(), + Attributes: toolsetAttributesOf(sess.AttributesSnapshot()), + HasToolsetState: true, } state.InputTokens, state.OutputTokens = sess.Usage() return state @@ -238,6 +256,10 @@ func (state sessionState) restore(sess *session.Session) { sess.SetUsage(state.InputTokens, state.OutputTokens) sess.SetSafetyPolicy(state.SafetyPolicy) sess.SetPermissions(state.Permissions) + toolsetAttrs := toolsetAttributesOf(state.Attributes) + if state.HasToolsetState || len(toolsetAttrs) > 0 { + sess.ReplaceToolsetAttributes(toolsetAttrs) + } } // agentState is what puts a conversation with an agent: the runtime's current @@ -343,7 +365,8 @@ type runRecord struct { cp checkpoint // failed is why the record stopped following the run. From then on // nothing more is saved, and the run stops. - failed error + failed error + toolsetDirty bool } // newRunRecord returns the record this stream keeps of sess's run, or nil @@ -536,6 +559,15 @@ func (rec *runRecord) CallStarted(ctx context.Context, callID string, call tools return rec.noteCall(ctx, callID, toolexec.CallRecord{Progress: toolexec.CallStarted, Call: &call}) } +func (rec *runRecord) saveToolsetStateLocked(ctx context.Context) { + if rec.r == nil || rec.sess == nil { + return + } + if rec.r.saveAgentToolsetState(ctx, rec.sess, rec.r.turnAgent(rec.sess, &rec.cp), false) { + rec.toolsetDirty = true + } +} + // CallRecorded implements [toolexec.Journal]. The record is locked while the // result goes to the session, so every checkpoint holds the results of // exactly the calls it says have theirs. @@ -543,6 +575,7 @@ func (rec *runRecord) CallRecorded(ctx context.Context, callID string, result *t rec.mu.Lock() defer rec.mu.Unlock() record() + rec.saveToolsetStateLocked(ctx) return rec.noteCall(ctx, callID, toolexec.CallRecord{ Progress: toolexec.CallRecorded, Call: rec.cp.Calls[callID].Call, @@ -557,6 +590,7 @@ func (rec *runRecord) CallFinished(ctx context.Context, callID string, outcome t if record != nil { record() } + rec.saveToolsetStateLocked(ctx) return rec.noteCall(ctx, callID, toolexec.CallRecord{Progress: toolexec.CallFinished, Outcome: outcome}) } @@ -593,12 +627,19 @@ func (rec *runRecord) settle(ctx context.Context) error { return nil case cancelled: // A run its host cancelled is over, whatever of it reached the store. - err = rec.r.runs.EndRun(ctx, rec.sess.ID) + rec.mu.Lock() + dirty := rec.toolsetDirty + rec.mu.Unlock() + if dirty { + err = rec.r.endRun(ctx, rec.sess) + } else { + err = rec.r.runs.EndRun(ctx, rec.sess.ID) + } default: // Until the store holds the run's last words, the record is what // lets the run be found again. if err = rec.transcriptStored(ctx); err == nil { - err = rec.r.runs.EndRun(ctx, rec.sess.ID) + err = rec.r.endRun(ctx, rec.sess) } return err } diff --git a/pkg/runtime/loop.go b/pkg/runtime/loop.go index 0f116490be..187198cbb1 100644 --- a/pkg/runtime/loop.go +++ b/pkg/runtime/loop.go @@ -196,6 +196,7 @@ func (r *LocalRuntime) runStream(ctx context.Context, sess *session.Session, idl func (r *LocalRuntime) runStreamLoop(ctx context.Context, sess *session.Session, liveEntry *liveSessionEntry, resume *checkpoint, events chan Event) { sink := &channelSink{ch: events} ctx = context.WithValue(ctx, scratchpadRootKey{}, liveEntry.treeRootID) + ctx = tools.WithStateScope(ctx, sess.ID) // Seed the cagent session ID at the run-loop boundary so any // gateway-bound HTTP call originating from this loop can correlate @@ -405,6 +406,10 @@ func (r *LocalRuntime) runStreamLoop(ctx context.Context, sess *session.Session, } } + restoredAgents := make(map[string]struct{}) + r.restoreAgentToolsetState(ctx, sess, a) + restoredAgents[a.Name()] = struct{}{} + agentTools, err := r.getTools(ctx, sess, a, sessionSpan, sink, true) if err != nil { sink.Emit(ErrorWithCodeForSession(sess.ID, ErrorCodeToolFailed, fmt.Sprintf("failed to get tools: %v", err))) @@ -541,6 +546,11 @@ func (r *LocalRuntime) runStreamLoop(ctx context.Context, sess *session.Session, r.emitAgentWarnings(a, sink) + if _, ok := restoredAgents[a.Name()]; !ok { + r.restoreAgentToolsetState(ctx, sess, a) + restoredAgents[a.Name()] = struct{}{} + } + agentTools, err := r.getTools(ctx, sess, a, sessionSpan, sink, true) if err != nil { sink.Emit(ErrorWithCodeForSession(sess.ID, ErrorCodeToolFailed, fmt.Sprintf("failed to get tools: %v", err))) @@ -1180,6 +1190,9 @@ func (r *LocalRuntime) runTools(ctx context.Context, t *turn, answer *modelAnswe loopSink.recall(own[min(messageCountBeforeTools, len(own)):], answer.Calls, agentTools) } stopRun, stopMsg := r.processToolCalls(ctx, sess, a, dispatchCalls, agentTools, loopSink, t.rec.journal()) + if len(answer.Calls) > 0 { + r.saveAgentToolsetState(ctx, sess, a, r.runs == nil) + } if err := t.rec.failure(); err != nil { return turnExit, r.stopUnrecorded(ctx, sess, a, err, events), true } @@ -1584,7 +1597,8 @@ func (r *LocalRuntime) getTools(ctx context.Context, sess *session.Session, a *a } // Catalog tools ride through the same session filters below. - agentTools, err := listAgentTools(ctx, a) + listCtx := tools.WithDiscoveryTimeout(ctx, r.toolListTimeout) + agentTools, err := listAgentTools(listCtx, a) if err == nil { agentTools = filterExcludedTools(agentTools, sess.ExcludedTools) agentTools = r.skillSubSessionTools(ctx, sess, a, agentTools) diff --git a/pkg/runtime/startup_info.go b/pkg/runtime/startup_info.go index 606e618535..8e1128a10b 100644 --- a/pkg/runtime/startup_info.go +++ b/pkg/runtime/startup_info.go @@ -156,6 +156,11 @@ func (r *LocalRuntime) EmitStartupInfo(ctx context.Context, sess *session.Sessio // the TUI is not yet ready to render. The actual prompt happens on // the first RunStream when the user is interacting with the agent. nonInteractiveCtx := tools.WithoutInteractivePrompts(ctx) + if sess != nil { + nonInteractiveCtx = tools.WithStateScope(nonInteractiveCtx, sess.ID) + } + nonInteractiveCtx = tools.WithDiscoveryTimeout(nonInteractiveCtx, r.toolListTimeout) + r.RestoreSessionToolsetState(nonInteractiveCtx, sess) r.emitToolsProgressively(nonInteractiveCtx, a, send) // Flush any agent warnings: load-time warnings recorded at agent diff --git a/pkg/runtime/toolset_state.go b/pkg/runtime/toolset_state.go new file mode 100644 index 0000000000..34ec9a76d0 --- /dev/null +++ b/pkg/runtime/toolset_state.go @@ -0,0 +1,108 @@ +package runtime + +import ( + "context" + "log/slog" + + "github.com/docker/docker-agent/pkg/agent" + "github.com/docker/docker-agent/pkg/session" + "github.com/docker/docker-agent/pkg/tools" +) + +func toolsetStateAttributeKey(agentName, stateKey string) string { + return session.ToolsetAttributeKey(agentName, stateKey) +} + +func collectStatefulToolSets(a *agent.Agent, extras []tools.ToolSet) []tools.Stateful { + var sets []tools.ToolSet + if a != nil { + sets = append(sets, a.ToolSets()...) + } + sets = append(sets, extras...) + + var result []tools.Stateful + seen := make(map[tools.Stateful]struct{}) + for _, root := range sets { + tools.Walk(root, func(ts tools.ToolSet) bool { + s, ok := ts.(tools.Stateful) + if !ok { + return true + } + if _, exists := seen[s]; exists { + return true + } + seen[s] = struct{}{} + result = append(result, s) + return true + }) + } + return result +} + +func (r *LocalRuntime) restoreAgentToolsetState(ctx context.Context, sess *session.Session, a *agent.Agent) { + if sess == nil || a == nil { + return + } + statefuls := collectStatefulToolSets(a, sess.ExtraToolSets) + if len(statefuls) == 0 { + return + } + + scopedCtx := tools.WithStateScope(ctx, sess.ID) + attrs := sess.AttributesSnapshot() + for _, s := range statefuls { + key := toolsetStateAttributeKey(a.Name(), s.StateKey()) + if err := s.RestoreState(scopedCtx, attrs[key]); err != nil { + slog.WarnContext(ctx, "Failed to restore toolset state", + "session_id", sess.ID, "agent", a.Name(), "toolset", s.StateKey(), "error", err) + } + } +} + +func (r *LocalRuntime) saveAgentToolsetState(ctx context.Context, sess *session.Session, a *agent.Agent, persist bool) bool { + if sess == nil || a == nil { + return false + } + statefuls := collectStatefulToolSets(a, sess.ExtraToolSets) + if len(statefuls) == 0 { + return false + } + + scopedCtx := tools.WithStateScope(ctx, sess.ID) + changed := false + for _, s := range statefuls { + snapshot, err := s.SnapshotState(scopedCtx) + if err != nil { + slog.WarnContext(ctx, "Failed to snapshot toolset state", + "session_id", sess.ID, "agent", a.Name(), "toolset", s.StateKey(), "error", err) + continue + } + if sess.SetToolsetState(a.Name(), s.StateKey(), snapshot) { + changed = true + } + } + + if changed && persist && !sess.IsSubSession() && r.sessionStore != nil { + if err := r.sessionStore.UpdateSession(context.WithoutCancel(ctx), sess); err != nil { + slog.WarnContext(ctx, "Failed to persist toolset state", + "session_id", sess.ID, "agent", a.Name(), "error", err) + } + } + return changed +} + +// RestoreSessionToolsetState restores persisted stateful toolset state from sess +// onto the configured agents in this runtime. +func (r *LocalRuntime) RestoreSessionToolsetState(ctx context.Context, sess *session.Session) { + if sess == nil || r.team == nil { + return + } + scopedCtx := tools.WithStateScope(ctx, sess.ID) + for _, name := range r.team.AgentNames() { + a, err := r.team.Agent(name) + if err != nil || a == nil { + continue + } + r.restoreAgentToolsetState(scopedCtx, sess, a) + } +} diff --git a/pkg/runtime/toolset_state_test.go b/pkg/runtime/toolset_state_test.go new file mode 100644 index 0000000000..e5ecf9f356 --- /dev/null +++ b/pkg/runtime/toolset_state_test.go @@ -0,0 +1,945 @@ +package runtime + +import ( + "context" + "encoding/json" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/docker/docker-agent/pkg/agent" + "github.com/docker/docker-agent/pkg/chat" + "github.com/docker/docker-agent/pkg/config/latest" + "github.com/docker/docker-agent/pkg/hooks" + "github.com/docker/docker-agent/pkg/model/provider" + "github.com/docker/docker-agent/pkg/model/provider/base" + "github.com/docker/docker-agent/pkg/modelsdev" + "github.com/docker/docker-agent/pkg/runtime/toolexec" + "github.com/docker/docker-agent/pkg/session" + "github.com/docker/docker-agent/pkg/team" + "github.com/docker/docker-agent/pkg/tools" + "github.com/docker/docker-agent/pkg/tools/builtin/deferred" +) + +type staticToolSet struct { + list []tools.Tool +} + +func (s *staticToolSet) Tools(context.Context) ([]tools.Tool, error) { + return s.list, nil +} + +func newDeferredAgent(m provider.Provider, pingCalls *atomic.Int32, extraTools ...tools.Tool) *agent.Agent { + ping := tools.Tool{ + Name: "secret_ping", + Description: "Responds pong", + Parameters: map[string]any{"type": "object"}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + pingCalls.Add(1) + return tools.ResultSuccess("pong"), nil + }, + } + + dt := deferred.New() + dt.AddSource(&staticToolSet{list: []tools.Tool{ping}}, true, nil) + + opts := []agent.Opt{ + agent.WithModel(m), + agent.WithToolSets(dt), + } + if len(extraTools) > 0 { + opts = append(opts, agent.WithTools(extraTools...)) + } + return agent.New("root", "You are a test agent", opts...) +} + +func TestLocalRuntime_DeferredToolsPersistAcrossSQLiteResume(t *testing.T) { + t.Parallel() + ctx := t.Context() + store := durableStore(t) + + var pingCalls atomic.Int32 + model1 := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_1", deferred.ToolNameAddTool). + AddToolCallArguments("call_1", `{"name":"secret_ping"}`). + AddStopWithUsage(1, 1). + Build(), + newStreamBuilder(). + AddContent("activated"). + AddStopWithUsage(1, 1). + Build(), + }, + } + + rt1, err := NewLocalRuntime(ctx, team.New(team.WithAgents(newDeferredAgent(model1, &pingCalls))), + WithSessionStore(store), WithSessionCompaction(false), WithModelStore(mockModelStore{})) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, rt1.Close()) }) + + sess := session.New(session.WithUserMessage("activate secret_ping"), session.WithToolsApproved(true)) + require.NoError(t, store.AddSession(ctx, sess)) + + _, err = rt1.Run(ctx, sess) + require.NoError(t, err) + + // New process: brand-new runtime, agent, and empty deferred toolset loading from SQLite. + reloaded, err := store.GetSession(ctx, sess.ID) + require.NoError(t, err) + assert.Contains(t, reloaded.AttributesSnapshot()[toolsetStateAttributeKey("root", "deferred")], `"secret_ping"`) + + model2 := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_2", "secret_ping"). + AddToolCallArguments("call_2", `{}`). + AddStopWithUsage(1, 1). + Build(), + newStreamBuilder(). + AddContent("done"). + AddStopWithUsage(1, 1). + Build(), + }, + } + + rt2, err := NewLocalRuntime(ctx, team.New(team.WithAgents(newDeferredAgent(model2, &pingCalls))), + WithSessionStore(store), WithSessionCompaction(false), WithModelStore(mockModelStore{})) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, rt2.Close()) }) + + // Startup info restoration also exposes the activated tool immediately for this session. + rt2.RestoreSessionToolsetState(ctx, reloaded) + currentTools, err := rt2.CurrentAgentTools(tools.WithStateScope(ctx, reloaded.ID)) + require.NoError(t, err) + assert.Contains(t, toolNames(currentTools), "secret_ping") + + reloaded.AddMessage(session.UserMessage("call secret_ping now")) + msgs, err := rt2.Run(ctx, reloaded) + require.NoError(t, err) + require.NotEmpty(t, msgs) + assert.Equal(t, int32(1), pingCalls.Load(), "secret_ping should execute directly after resume without add_tool") +} + +func TestLocalRuntime_StatefulSessionIsolation(t *testing.T) { + t.Parallel() + ctx := t.Context() + store := durableStore(t) + + var pingCalls atomic.Int32 + model := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + // Session A activates secret_ping. + newStreamBuilder(). + AddToolCallName("call_1", deferred.ToolNameAddTool). + AddToolCallArguments("call_1", `{"name":"secret_ping"}`). + AddStopWithUsage(1, 1). + Build(), + newStreamBuilder().AddContent("activated").AddStopWithUsage(1, 1).Build(), + // Session B tries to call secret_ping directly without activating it. + newStreamBuilder(). + AddToolCallName("call_2", "secret_ping"). + AddToolCallArguments("call_2", `{}`). + AddStopWithUsage(1, 1). + Build(), + newStreamBuilder().AddContent("failed as expected").AddStopWithUsage(1, 1).Build(), + }, + } + + rt, err := NewLocalRuntime(ctx, team.New(team.WithAgents(newDeferredAgent(model, &pingCalls))), + WithSessionStore(store), WithSessionCompaction(false), WithModelStore(mockModelStore{})) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, rt.Close()) }) + + sessA := session.New(session.WithUserMessage("activate"), session.WithToolsApproved(true)) + require.NoError(t, store.AddSession(ctx, sessA)) + _, err = rt.Run(ctx, sessA) + require.NoError(t, err) + + sessB := session.New(session.WithUserMessage("call directly"), session.WithToolsApproved(true)) + require.NoError(t, store.AddSession(ctx, sessB)) + _, err = rt.Run(ctx, sessB) + require.NoError(t, err) + + assert.Zero(t, pingCalls.Load(), "session B must not inherit session A's activated deferred tools") + assert.NotContains(t, sessB.AttributesSnapshot(), toolsetStateAttributeKey("root", "deferred")) +} + +func TestDurableRuntime_DeferredToolsSurviveSuspendAndContinueStream(t *testing.T) { + t.Parallel() + ctx := t.Context() + store := durableStore(t) + + var pingCalls atomic.Int32 + running := make(chan struct{}) + pauseTool := tools.Tool{ + Name: "pause_here", + Parameters: map[string]any{"type": "object"}, + Annotations: tools.ToolAnnotations{IdempotentHint: true}, + Handler: func(toolCtx context.Context, _ tools.ToolCall, _ tools.Runtime) (*tools.ToolCallResult, error) { + close(running) + <-toolCtx.Done() + return nil, toolCtx.Err() + }, + } + + model1 := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_1", deferred.ToolNameAddTool). + AddToolCallArguments("call_1", `{"name":"secret_ping"}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder(). + AddToolCallName("call_2", "pause_here"). + AddToolCallArguments("call_2", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + }, + } + rt1 := durableRuntime(t, store, newDeferredAgent(model1, &pingCalls, pauseTool)) + t.Cleanup(func() { require.NoError(t, rt1.Close()) }) + + runCtx, cancelRun := context.WithCancelCause(ctx) + defer cancelRun(nil) + sess := session.New(session.WithUserMessage("activate and pause"), session.WithToolsApproved(true)) + for ev := range rt1.RunStream(runCtx, sess) { + if tcEv, ok := ev.(*ToolCallEvent); ok && tcEv.ToolCall.Function.Name == "pause_here" { + <-running + cancelRun(ErrSuspended) + } + } + + // New durable runtime takes up the suspended run: call_2 resumes cleanly, + // and on the next model step secret_ping is available without calling add_tool again. + var pauseRuns atomic.Int32 + resumePauseTool := tools.Tool{ + Name: "pause_here", + Parameters: map[string]any{"type": "object"}, + Annotations: tools.ToolAnnotations{IdempotentHint: true}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + pauseRuns.Add(1) + return tools.ResultSuccess("resumed"), nil + }, + } + model2 := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_3", "secret_ping"). + AddToolCallArguments("call_3", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder(). + AddContent("done"). + AddStopWithUsage(1, 1). + Build(), + }, + } + rt2 := durableRuntime(t, store, newDeferredAgent(model2, &pingCalls, resumePauseTool)) + t.Cleanup(func() { require.NoError(t, rt2.Close()) }) + + continued(t, rt2, sess.ID) + + assert.Equal(t, int32(1), pauseRuns.Load()) + assert.Equal(t, int32(1), pingCalls.Load(), "secret_ping must stay activated across DurableRuntime.ContinueStream") +} + +type runSaveNotifier struct { + session.Store + session.RunStore + + onSave func(checkpoint []byte) +} + +func (s *runSaveNotifier) SaveRun(ctx context.Context, sessionID string, data []byte) error { + err := s.RunStore.SaveRun(ctx, sessionID, data) + if err == nil && s.onSave != nil { + s.onSave(data) + } + return err +} + +// Exercises a durable run interrupted mid-batch right after add_tool checkpoints, +// before the second tool call finishes. +func TestDurableRuntime_DeferredToolsSurviveMidBatchSuspend(t *testing.T) { + t.Parallel() + ctx := t.Context() + sqlite := durableStore(t) + + addToolCheckpointed := make(chan struct{}) + var notifyOnce sync.Once + store := &runSaveNotifier{ + Store: sqlite, + RunStore: sqlite.(session.RunStore), + onSave: func(data []byte) { + var cp checkpoint + if json.Unmarshal(data, &cp) == nil && cp.Session.Attributes[toolsetStateAttributeKey("root", "deferred")] != "" { + notifyOnce.Do(func() { close(addToolCheckpointed) }) + } + }, + } + + var pingCalls atomic.Int32 + pauseTool := tools.Tool{ + Name: "pause_here", + Parameters: map[string]any{"type": "object"}, + Annotations: tools.ToolAnnotations{IdempotentHint: true}, + Handler: func(toolCtx context.Context, _ tools.ToolCall, _ tools.Runtime) (*tools.ToolCallResult, error) { + <-toolCtx.Done() + return nil, toolCtx.Err() + }, + } + + model1 := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_1", deferred.ToolNameAddTool). + AddToolCallArguments("call_1", `{"name":"secret_ping"}`). + AddToolCallName("call_2", "pause_here"). + AddToolCallArguments("call_2", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + }, + } + rt1 := durableRuntime(t, store, newDeferredAgent(model1, &pingCalls, pauseTool)) + t.Cleanup(func() { require.NoError(t, rt1.Close()) }) + + runCtx, cancelRun := context.WithCancelCause(ctx) + defer cancelRun(nil) + sess := session.New(session.WithUserMessage("activate and pause mid-batch"), session.WithToolsApproved(true)) + go func() { + <-addToolCheckpointed + cancelRun(ErrSuspended) + }() + drain(rt1.RunStream(runCtx, sess)) + + var pauseRuns atomic.Int32 + resumePauseTool := tools.Tool{ + Name: "pause_here", + Parameters: map[string]any{"type": "object"}, + Annotations: tools.ToolAnnotations{IdempotentHint: true}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + pauseRuns.Add(1) + return tools.ResultSuccess("resumed"), nil + }, + } + model2 := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_3", "secret_ping"). + AddToolCallArguments("call_3", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder(). + AddContent("done"). + AddStopWithUsage(1, 1). + Build(), + }, + } + rt2 := durableRuntime(t, sqlite, newDeferredAgent(model2, &pingCalls, resumePauseTool)) + t.Cleanup(func() { require.NoError(t, rt2.Close()) }) + + continued(t, rt2, sess.ID) + + assert.Equal(t, int32(1), pauseRuns.Load()) + assert.Equal(t, int32(1), pingCalls.Load(), "add_tool activation recorded mid-batch must survive ContinueStream") +} + +// A durable run that finishes normally must persist final toolset attributes +// to SQLite before dropping the run record so a fresh runtime can reload without ContinueStream. +func TestDurableRuntime_NormalCompletionPersistsAcrossSQLiteReload(t *testing.T) { + t.Parallel() + ctx := t.Context() + store := durableStore(t) + + var pingCalls atomic.Int32 + model1 := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_1", deferred.ToolNameAddTool). + AddToolCallArguments("call_1", `{"name":"secret_ping"}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder(). + AddContent("activated"). + AddStopWithUsage(1, 1). + Build(), + }, + } + + rt1 := durableRuntime(t, store, newDeferredAgent(model1, &pingCalls)) + t.Cleanup(func() { require.NoError(t, rt1.Close()) }) + + sess := session.New(session.WithUserMessage("activate tool"), session.WithToolsApproved(true)) + drain(rt1.RunStream(ctx, sess)) + assert.Empty(t, recordedRuns(t, store), "completed durable run drops its run record") + + reloaded, err := store.GetSession(ctx, sess.ID) + require.NoError(t, err) + assert.Contains(t, reloaded.AttributesSnapshot()[toolsetStateAttributeKey("root", "deferred")], `"secret_ping"`) + + model2 := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_2", "secret_ping"). + AddToolCallArguments("call_2", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder(). + AddContent("done"). + AddStopWithUsage(1, 1). + Build(), + }, + } + rt2 := durableRuntime(t, store, newDeferredAgent(model2, &pingCalls)) + t.Cleanup(func() { require.NoError(t, rt2.Close()) }) + + reloaded.AddMessage(session.UserMessage("run secret_ping without ContinueStream")) + drain(rt2.RunStream(ctx, reloaded)) + + assert.Equal(t, int32(1), pingCalls.Load(), "fresh runtime loading SQLite after normal durable run must keep secret_ping active") +} + +// Suspending inside a post_tool_use hook (CallRecorded checkpoint) happens before +// CallFinished; resume skips add_tool and runs only the hook, so the activation +// must already be checkpointed with CallRecorded. +func TestDurableRuntime_DeferredToolsSurviveCallRecordedSuspendInPostHook(t *testing.T) { + t.Parallel() + ctx := t.Context() + store := durableStore(t) + + runCtx, cancelRun := context.WithCancelCause(ctx) + defer cancelRun(nil) + + var pingCalls atomic.Int32 + var postHookCalls atomic.Int32 + + makeRegistry := func(suspendFirstCall bool) *hooks.Registry { + reg := hooks.NewRegistry() + require.NoError(t, reg.RegisterBuiltin("post_add_hook", func(context.Context, *hooks.Input, []string) (*hooks.Output, error) { + n := postHookCalls.Add(1) + if suspendFirstCall && n == 1 { + // Confirm CallRecorded + toolset activation are ALREADY checkpointed before hook finishes. + runs := recordedRuns(t, store) + if assert.Len(t, runs, 1) { + var cp checkpoint + require.NoError(t, json.Unmarshal(runs[0].Checkpoint, &cp)) + assert.Equal(t, toolexec.CallRecorded, cp.Calls["call_1"].Progress) + assert.Contains(t, cp.Session.Attributes[toolsetStateAttributeKey("root", "deferred")], `"secret_ping"`) + } + cancelRun(ErrSuspended) + } + return nil, nil + })) + return reg + } + + hookCfg := &latest.HooksConfig{ + PostToolUse: []latest.HookMatcherConfig{{ + Matcher: deferred.ToolNameAddTool, + Hooks: []latest.HookDefinition{{Type: "builtin", Command: "post_add_hook"}}, + }}, + } + + model1 := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_1", deferred.ToolNameAddTool). + AddToolCallArguments("call_1", `{"name":"secret_ping"}`). + AddToolCallStopWithUsage(1, 1). + Build(), + }, + } + rt1 := durableRuntime(t, store, newDeferredAgentWithHooks(model1, &pingCalls, hookCfg)) + rt1.hooksRegistry = makeRegistry(true) + rt1.buildHooksExecutors() + t.Cleanup(func() { require.NoError(t, rt1.Close()) }) + + sess := session.New(session.WithUserMessage("activate with post hook"), session.WithToolsApproved(true)) + drain(rt1.RunStream(runCtx, sess)) + assert.Equal(t, int32(1), postHookCalls.Load()) + + model2 := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_2", "secret_ping"). + AddToolCallArguments("call_2", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder(). + AddContent("done"). + AddStopWithUsage(1, 1). + Build(), + }, + } + rt2 := durableRuntime(t, store, newDeferredAgentWithHooks(model2, &pingCalls, hookCfg)) + rt2.hooksRegistry = makeRegistry(false) + rt2.buildHooksExecutors() + t.Cleanup(func() { require.NoError(t, rt2.Close()) }) + + continued(t, rt2, sess.ID) + + assert.Equal(t, int32(2), postHookCalls.Load(), "resumed CallRecorded step must re-run post_tool_use hook") + assert.Equal(t, int32(1), pingCalls.Load(), "secret_ping activation saved at CallRecorded must survive resume without re-running add_tool") +} + +func newDeferredAgentWithHooks(m provider.Provider, pingCalls *atomic.Int32, hookCfg *latest.HooksConfig) *agent.Agent { + ping := tools.Tool{ + Name: "secret_ping", + Description: "Responds pong", + Parameters: map[string]any{"type": "object"}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + pingCalls.Add(1) + return tools.ResultSuccess("pong"), nil + }, + } + dt := deferred.New() + dt.AddSource(&staticToolSet{list: []tools.Tool{ping}}, true, nil) + + return agent.New("root", "You are a test agent", + agent.WithModel(m), + agent.WithToolSets(dt), + agent.WithHooks(hookCfg), + ) +} + +// Pre-change v1 checkpoints omit `attributes`; DiscardRun and ContinueStream +// must preserve unrelated host attributes stored in SQLite. +func TestDurableRuntime_PreChangeV1CheckpointPreservesAttributes(t *testing.T) { + t.Parallel() + ctx := t.Context() + store := durableStore(t) + runs := store.(session.RunStore) + + preChangePayload := []byte(`{"version":1,"phase":"starting","agent":{"current":"root"},"session":{},"state":{}}`) + + t.Run("DiscardRun", func(t *testing.T) { + sess := session.New( + session.WithUserMessage("legacy run"), + session.WithAttributes(map[string]string{ + "daw.workspace_path": "/ws", + "daw.worktree_id": "wt-1", + }), + ) + require.NoError(t, runs.BeginRun(ctx, sess, nil, preChangePayload)) + require.NoError(t, runs.SuspendRun(ctx, sess.ID)) + + rt := durableRuntime(t, store, rootAgent(&transcriptProvider{})) + t.Cleanup(func() { require.NoError(t, rt.Close()) }) + + require.NoError(t, rt.DiscardRun(ctx, sess.ID)) + + reloaded, err := store.GetSession(ctx, sess.ID) + require.NoError(t, err) + assert.Equal(t, map[string]string{ + "daw.workspace_path": "/ws", + "daw.worktree_id": "wt-1", + }, reloaded.AttributesSnapshot()) + }) + + t.Run("ContinueStream", func(t *testing.T) { + sess := session.New( + session.WithUserMessage("legacy resume"), + session.WithAttributes(map[string]string{ + "daw.workspace_path": "/ws2", + "daw.worktree_id": "wt-2", + }), + ) + require.NoError(t, runs.BeginRun(ctx, sess, nil, preChangePayload)) + require.NoError(t, runs.SuspendRun(ctx, sess.ID)) + + model := &transcriptProvider{ + answer: func(context.Context) chat.MessageStream { + return newStreamBuilder().AddContent("resumed").AddStopWithUsage(1, 1).Build() + }, + } + rt := durableRuntime(t, store, rootAgent(model)) + t.Cleanup(func() { require.NoError(t, rt.Close()) }) + + continued(t, rt, sess.ID) + + reloaded, err := store.GetSession(ctx, sess.ID) + require.NoError(t, err) + assert.Equal(t, map[string]string{ + "daw.workspace_path": "/ws2", + "daw.worktree_id": "wt-2", + }, reloaded.AttributesSnapshot()) + }) +} + +// Two overlapping streams pinned to the same agent must keep their activated +// deferred tools isolated across restore, listing, execution, and snapshotting. +func TestLocalRuntime_OverlappingSessionsIsolateDeferredTools(t *testing.T) { + t.Parallel() + ctx := t.Context() + store := durableStore(t) + + var aCalls, bCalls atomic.Int32 + barrierStarted := make(chan struct{}) + releaseA := make(chan struct{}) + + toolA := tools.Tool{ + Name: "tool_a", + Description: "Session A tool", + Parameters: map[string]any{"type": "object"}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + aCalls.Add(1) + return tools.ResultSuccess("ok a"), nil + }, + } + toolB := tools.Tool{ + Name: "tool_b", + Description: "Session B tool", + Parameters: map[string]any{"type": "object"}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + bCalls.Add(1) + return tools.ResultSuccess("ok b"), nil + }, + } + syncTool := tools.Tool{ + Name: "pause_a", + Description: "Pauses session A mid-turn before next tool listing", + Parameters: map[string]any{"type": "object"}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + close(barrierStarted) + <-releaseA + return tools.ResultSuccess("continued"), nil + }, + } + + dt := deferred.New() + dt.AddSource(&staticToolSet{list: []tools.Tool{toolA, toolB}}, true, nil) + + streamA := []chat.MessageStream{ + // Session A activates tool_a. + newStreamBuilder(). + AddToolCallName("a1", deferred.ToolNameAddTool). + AddToolCallArguments("a1", `{"name":"tool_a"}`). + AddToolCallStopWithUsage(1, 1). + Build(), + // Session A pauses in pause_a before listing tools for its next turn. + newStreamBuilder(). + AddToolCallName("a2", "pause_a"). + AddToolCallArguments("a2", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + // After Session B runs concurrently and restores empty state, A must still call tool_a cleanly. + newStreamBuilder(). + AddToolCallName("a3", "tool_a"). + AddToolCallArguments("a3", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder().AddContent("A done").AddStopWithUsage(1, 1).Build(), + } + streamB := []chat.MessageStream{ + // Session B starts while A has tool_a active, tries calling tool_a directly (must fail), then activates tool_b. + newStreamBuilder(). + AddToolCallName("b1", "tool_a"). + AddToolCallArguments("b1", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder(). + AddToolCallName("b2", deferred.ToolNameAddTool). + AddToolCallArguments("b2", `{"name":"tool_b"}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder(). + AddToolCallName("b3", "tool_b"). + AddToolCallArguments("b3", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder().AddContent("B done").AddStopWithUsage(1, 1).Build(), + } + + var idxA, idxB atomic.Int32 + routingModel := &funcProvider{ + id: "test/mock-model", + fn: func(_ context.Context, msgs []chat.Message) chat.MessageStream { + for _, m := range msgs { + if m.Role == chat.MessageRoleUser && m.Content == "session A prompt" { + i := int(idxA.Add(1)) - 1 + return streamA[i] + } + } + i := int(idxB.Add(1)) - 1 + return streamB[i] + }, + } + + root := agent.New("root", "You are a test agent", + agent.WithModel(routingModel), + agent.WithToolSets(dt), + agent.WithTools(syncTool), + ) + rt, err := NewLocalRuntime(ctx, team.New(team.WithAgents(root)), + WithSessionStore(store), WithSessionCompaction(false), WithModelStore(mockModelStore{})) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, rt.Close()) }) + + sessA := session.New(session.WithUserMessage("session A prompt"), session.WithAgentName("root"), session.WithToolsApproved(true)) + sessB := session.New(session.WithUserMessage("session B prompt"), session.WithAgentName("root"), session.WithToolsApproved(true)) + require.NoError(t, store.AddSession(ctx, sessA)) + require.NoError(t, store.AddSession(ctx, sessB)) + + doneA := make(chan struct{}) + go func() { + defer close(doneA) + drain(rt.RunStream(ctx, sessA)) + }() + + <-barrierStarted + drain(rt.RunStream(ctx, sessB)) + close(releaseA) + <-doneA + + assert.Equal(t, int32(1), aCalls.Load(), "Session A must still execute tool_a after Session B overlapped on same agent") + assert.Equal(t, int32(1), bCalls.Load(), "Session B must execute only its own tool_b") + assert.Contains(t, sessA.AttributesSnapshot()[toolsetStateAttributeKey("root", "deferred")], `"tool_a"`) + assert.NotContains(t, sessA.AttributesSnapshot()[toolsetStateAttributeKey("root", "deferred")], `"tool_b"`) + assert.Contains(t, sessB.AttributesSnapshot()[toolsetStateAttributeKey("root", "deferred")], `"tool_b"`) + assert.NotContains(t, sessB.AttributesSnapshot()[toolsetStateAttributeKey("root", "deferred")], `"tool_a"`) +} + +type funcProvider struct { + id string + fn func(ctx context.Context, msgs []chat.Message) chat.MessageStream +} + +func (p *funcProvider) ID() modelsdev.ID { return modelsdev.ParseIDOrZero(p.id) } + +func (p *funcProvider) CreateChatCompletionStream(ctx context.Context, msgs []chat.Message, _ []tools.Tool) (chat.MessageStream, error) { + return p.fn(ctx, msgs), nil +} + +func (p *funcProvider) BaseConfig() base.Config { return base.Config{} } + +func (p *funcProvider) MaxTokens() int { return 0 } + +// BranchSession and ForkSession truncate the transcript at a point; activation +// state must follow that fork point (before vs after add_tool). +func TestLocalRuntime_BranchedSessionFollowsActivationPoint(t *testing.T) { + t.Parallel() + ctx := t.Context() + store := durableStore(t) + + var pingCalls atomic.Int32 + secondTool := tools.Tool{ + Name: "second_ping", + Description: "Second deferred tool", + Parameters: map[string]any{"type": "object"}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + return tools.ResultSuccess("second"), nil + }, + } + newTwoDeferredAgent := func(m provider.Provider) *agent.Agent { + ping := tools.Tool{ + Name: "secret_ping", + Description: "Responds pong", + Parameters: map[string]any{"type": "object"}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + pingCalls.Add(1) + return tools.ResultSuccess("pong"), nil + }, + } + dt := deferred.New() + dt.AddSource(&staticToolSet{list: []tools.Tool{ping, secondTool}}, true, nil) + return agent.New("root", "You are a test agent", agent.WithModel(m), agent.WithToolSets(dt)) + } + + model1 := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + // Turn 1: no activation + newStreamBuilder().AddContent("hello").AddStopWithUsage(1, 1).Build(), + // Turn 2: activate secret_ping + newStreamBuilder(). + AddToolCallName("call_1", deferred.ToolNameAddTool). + AddToolCallArguments("call_1", `{"name":"secret_ping"}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder().AddContent("activated 1").AddStopWithUsage(1, 1).Build(), + // Turn 3: activate second_ping + newStreamBuilder(). + AddToolCallName("call_2", deferred.ToolNameAddTool). + AddToolCallArguments("call_2", `{"name":"second_ping"}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder().AddContent("activated 2").AddStopWithUsage(1, 1).Build(), + }, + } + + rt1, err := NewLocalRuntime(ctx, team.New(team.WithAgents(newTwoDeferredAgent(model1))), + WithSessionStore(store), WithSessionCompaction(false), WithModelStore(mockModelStore{})) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, rt1.Close()) }) + + sess := session.New(session.WithUserMessage("turn 1"), session.WithToolsApproved(true)) + require.NoError(t, store.AddSession(ctx, sess)) + _, err = rt1.Run(ctx, sess) + require.NoError(t, err) + + posBeforeActivation := sess.ItemCount() + sess.AddMessage(session.UserMessage("turn 2")) + _, err = rt1.Run(ctx, sess) + require.NoError(t, err) + + posAfterFirstActivation := sess.ItemCount() + sess.AddMessage(session.UserMessage("turn 3")) + _, err = rt1.Run(ctx, sess) + require.NoError(t, err) + + // Fork before first activation: neither tool may be exposed on a fresh runtime. + forkBefore, err := session.ForkSession(sess, posBeforeActivation) + require.NoError(t, err) + require.NoError(t, store.AddSession(ctx, forkBefore)) + + rtBefore, err := NewLocalRuntime(ctx, team.New(team.WithAgents(newTwoDeferredAgent(&queueProvider{id: "test/mock-model"}))), + WithSessionStore(store), WithSessionCompaction(false), WithModelStore(mockModelStore{})) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, rtBefore.Close()) }) + + loadedBefore, err := store.GetSession(ctx, forkBefore.ID) + require.NoError(t, err) + rtBefore.RestoreSessionToolsetState(ctx, loadedBefore) + toolsBefore, err := rtBefore.CurrentAgentTools(tools.WithStateScope(ctx, loadedBefore.ID)) + require.NoError(t, err) + assert.NotContains(t, toolNames(toolsBefore), "secret_ping") + assert.NotContains(t, toolNames(toolsBefore), "second_ping") + + // Branch after first activation and before second: only secret_ping is exposed. + branchBetween, err := session.BranchSession(sess, posAfterFirstActivation) + require.NoError(t, err) + require.NoError(t, store.AddSession(ctx, branchBetween)) + + modelBetween := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_run", "secret_ping"). + AddToolCallArguments("call_run", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder().AddContent("used secret_ping").AddStopWithUsage(1, 1).Build(), + }, + } + rtBetween, err := NewLocalRuntime(ctx, team.New(team.WithAgents(newTwoDeferredAgent(modelBetween))), + WithSessionStore(store), WithSessionCompaction(false), WithModelStore(mockModelStore{})) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, rtBetween.Close()) }) + + loadedBetween, err := store.GetSession(ctx, branchBetween.ID) + require.NoError(t, err) + rtBetween.RestoreSessionToolsetState(ctx, loadedBetween) + toolsBetween, err := rtBetween.CurrentAgentTools(tools.WithStateScope(ctx, loadedBetween.ID)) + require.NoError(t, err) + assert.Contains(t, toolNames(toolsBetween), "secret_ping") + assert.NotContains(t, toolNames(toolsBetween), "second_ping") + + loadedBetween.AddMessage(session.UserMessage("call secret_ping")) + _, err = rtBetween.Run(ctx, loadedBetween) + require.NoError(t, err) + assert.Equal(t, int32(1), pingCalls.Load()) +} + +type describedStaticToolSet struct { + desc string + list []tools.Tool +} + +func (s *describedStaticToolSet) Describe() string { return s.desc } + +func (s *describedStaticToolSet) Tools(context.Context) ([]tools.Tool, error) { return s.list, nil } + +type stalledToolSet struct { + desc string + release chan struct{} + calls atomic.Int32 +} + +func (s *stalledToolSet) Describe() string { return s.desc } + +func (s *stalledToolSet) Tools(context.Context) ([]tools.Tool, error) { + s.calls.Add(1) + <-s.release + return nil, nil +} + +// EmitStartupInfo and resumed turns must bound stalled deferred sources and skip +// unrelated ones so startup and resumed turns never hang on an unresponsive MCP tools/list. +func TestLocalRuntime_StartupAndResumeBoundStalledDeferredSource(t *testing.T) { + t.Parallel() + ctx := t.Context() + store := durableStore(t) + + release := make(chan struct{}) + defer close(release) + + var fastCalls atomic.Int32 + fastTool := tools.Tool{ + Name: "fast_tool", + Description: "Responds fast", + Parameters: map[string]any{"type": "object"}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + fastCalls.Add(1) + return tools.ResultSuccess("fast"), nil + }, + } + + dt := deferred.New() + dt.AddSource(&describedStaticToolSet{desc: "fast-src", list: []tools.Tool{fastTool}}, true, nil) + stalled := &stalledToolSet{desc: "stalled-src", release: release} + dt.AddSource(stalled, true, nil) + + model := &queueProvider{ + id: "test/mock-model", + streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("call_1", "fast_tool"). + AddToolCallArguments("call_1", `{}`). + AddToolCallStopWithUsage(1, 1). + Build(), + newStreamBuilder().AddContent("done").AddStopWithUsage(1, 1).Build(), + }, + } + root := agent.New("root", "You are a test agent", agent.WithModel(model), agent.WithToolSets(dt)) + + rt, err := NewLocalRuntime(ctx, team.New(team.WithAgents(root)), + WithSessionStore(store), + WithSessionCompaction(false), + WithModelStore(mockModelStore{}), + WithToolListTimeout(60*time.Millisecond), + ) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, rt.Close()) }) + + sess := session.New(session.WithUserMessage("resume with stalled source"), session.WithToolsApproved(true)) + sess.SetToolsetState("root", "deferred", `[{"name":"fast_tool","source":"fast-src#0"},{"name":"stalled_tool","source":"stalled-src#0"}]`) + require.NoError(t, store.AddSession(ctx, sess)) + + events := make(chan Event, 32) + start := time.Now() + rt.EmitStartupInfo(ctx, sess, NewChannelSink(events)) + assert.Less(t, time.Since(start), 500*time.Millisecond, "EmitStartupInfo must bound stalled deferred source") + + start = time.Now() + _, err = rt.Run(ctx, sess) + require.NoError(t, err) + assert.Less(t, time.Since(start), 500*time.Millisecond, "resumed turn must not hang on stalled deferred source") + assert.Equal(t, int32(1), fastCalls.Load(), "fast_tool must still activate and run when sibling deferred source stalls") + assert.Contains(t, sess.AttributesSnapshot()[toolsetStateAttributeKey("root", "deferred")], `"stalled_tool"`) +} diff --git a/pkg/session/branch.go b/pkg/session/branch.go index 206868acd6..fecee6121d 100644 --- a/pkg/session/branch.go +++ b/pkg/session/branch.go @@ -47,6 +47,7 @@ func branchSessionWithTitle(parent *Session, branchAtPosition int, titleFn func( branched := New() copySessionMetadata(branched, parent, titleFn(parent.TitleSnapshot())) + reconcileBranchedToolsetAttributes(branched, branchAtPosition) branched.Messages = make([]Item, 0, branchAtPosition) for i := range branchAtPosition { diff --git a/pkg/session/toolset_state.go b/pkg/session/toolset_state.go new file mode 100644 index 0000000000..78073307b8 --- /dev/null +++ b/pkg/session/toolset_state.go @@ -0,0 +1,181 @@ +package session + +import ( + "encoding/json" + "maps" + "strings" +) + +const ( + // ToolsetAttributePrefix namespaces persisted stateful toolset snapshots + // on Session.Attributes (keyed by .). + ToolsetAttributePrefix = "docker-agent.toolset." + + // ToolsetHistoryAttributePrefix stores item-position checkpoints alongside + // each toolset attribute so BranchSession and ForkSession can restore the + // activation state matching the fork point. + ToolsetHistoryAttributePrefix = "docker-agent.toolset-history." +) + +// ToolsetHistoryEntry records a toolset state snapshot as of transcript length At. +type ToolsetHistoryEntry struct { + At int `json:"at"` + State string `json:"state"` +} + +// ToolsetAttributeKey returns the Session.Attributes key for an agent toolset state. +func ToolsetAttributeKey(agentName, stateKey string) string { + return ToolsetAttributePrefix + agentName + "." + stateKey +} + +// ToolsetHistoryAttributeKey returns the Session.Attributes key storing the +// branch/fork position history for an agent toolset state. +func ToolsetHistoryAttributeKey(agentName, stateKey string) string { + return ToolsetHistoryAttributePrefix + agentName + "." + stateKey +} + +// IsToolsetAttributeKey reports whether key belongs to runtime-managed toolset +// persistence (current state or branch timeline history). +func IsToolsetAttributeKey(key string) bool { + return strings.HasPrefix(key, ToolsetAttributePrefix) || strings.HasPrefix(key, ToolsetHistoryAttributePrefix) +} + +// SetToolsetState atomically updates the persisted snapshot and transcript +// position history for one agent toolset, returning true if the state changed. +func (s *Session) SetToolsetState(agentName, stateKey, snapshot string) bool { + if s == nil { + return false + } + + key := ToolsetAttributeKey(agentName, stateKey) + histKey := ToolsetHistoryAttributeKey(agentName, stateKey) + + s.mu.Lock() + defer s.mu.Unlock() + + if s.Attributes == nil { + if snapshot == "" { + return false + } + s.Attributes = make(map[string]string) + } + + prev, exists := s.Attributes[key] + if snapshot == "" { + if !exists { + return false + } + delete(s.Attributes, key) + } else { + if exists && prev == snapshot { + return false + } + s.Attributes[key] = snapshot + } + + at := len(s.Messages) + var entries []ToolsetHistoryEntry + if raw := s.Attributes[histKey]; raw != "" { + _ = json.Unmarshal([]byte(raw), &entries) + } else if exists && prev != "" { + entries = append(entries, ToolsetHistoryEntry{At: 0, State: prev}) + } + + // Trim any entries past the current transcript length in case messages were cut back. + kept := entries[:0] + for _, entry := range entries { + if entry.At < at { + kept = append(kept, entry) + } + } + entries = append(kept, ToolsetHistoryEntry{At: at, State: snapshot}) + + if encoded, err := json.Marshal(entries); err == nil { + s.Attributes[histKey] = string(encoded) + } + return true +} + +// ReplaceToolsetAttributes updates only runtime-managed toolset attributes on s, +// leaving any unrelated host or embedder attributes untouched. +func (s *Session) ReplaceToolsetAttributes(attrs map[string]string) { + if s == nil { + return + } + + s.mu.Lock() + defer s.mu.Unlock() + + if s.Attributes == nil && len(attrs) == 0 { + return + } + + for k := range s.Attributes { + if IsToolsetAttributeKey(k) { + delete(s.Attributes, k) + } + } + for k, v := range attrs { + if !IsToolsetAttributeKey(k) { + continue + } + if s.Attributes == nil { + s.Attributes = make(map[string]string) + } + s.Attributes[k] = v + } +} + +// reconcileBranchedToolsetAttributes adjusts toolset attributes on a newly +// branched/forked session to match branchAtPosition. +func reconcileBranchedToolsetAttributes(branched *Session, branchAtPosition int) { + if branched == nil || len(branched.Attributes) == 0 { + return + } + + // Work on a snapshot of keys while mutating branched.Attributes. + keys := make([]string, 0, len(branched.Attributes)) + for k := range branched.Attributes { + keys = append(keys, k) + } + for _, k := range keys { + suffix, ok := strings.CutPrefix(k, ToolsetHistoryAttributePrefix) + if !ok { + continue + } + var entries []ToolsetHistoryEntry + if err := json.Unmarshal([]byte(branched.Attributes[k]), &entries); err != nil { + continue + } + + var kept []ToolsetHistoryEntry + for _, entry := range entries { + if entry.At <= branchAtPosition { + kept = append(kept, entry) + } + } + + stateAttrKey := ToolsetAttributePrefix + suffix + if len(kept) == 0 { + delete(branched.Attributes, stateAttrKey) + delete(branched.Attributes, k) + continue + } + + latest := kept[len(kept)-1].State + if latest == "" { + delete(branched.Attributes, stateAttrKey) + } else { + branched.Attributes[stateAttrKey] = latest + } + if encoded, err := json.Marshal(kept); err == nil { + branched.Attributes[k] = string(encoded) + } + } + + if len(branched.Attributes) == 0 { + branched.Attributes = nil + } else { + branched.Attributes = maps.Clone(branched.Attributes) + } +} diff --git a/pkg/tools/builtin/deferred/deferred.go b/pkg/tools/builtin/deferred/deferred.go index 67532fab6b..3396cb5a77 100644 --- a/pkg/tools/builtin/deferred/deferred.go +++ b/pkg/tools/builtin/deferred/deferred.go @@ -4,12 +4,14 @@ import ( "cmp" "context" "encoding/json" + "errors" "fmt" "log/slog" "maps" "slices" "strings" "sync" + "time" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" @@ -21,6 +23,8 @@ import ( const ( ToolNameSearchTool = "search_tool" ToolNameAddTool = "add_tool" + + defaultDiscoveryTimeout = 10 * time.Second ) // ToolSet exposes search_tool/add_tool over the deferred tools of its @@ -28,10 +32,14 @@ const ( // it can be listed, rather than at start: the sources are the agent's other // toolsets and may still be starting when the first turn runs, so a // start-time snapshot would race them and fail the whole toolset. +// +// Activation state is keyed by [tools.StateScope] so a team's shared deferred +// toolset isolates concurrent sessions running on the same agent. type ToolSet struct { - mu sync.RWMutex - activatedTools map[string]tools.Tool - sources []*deferredSource + mu sync.RWMutex + states map[string]*activationState + sources []*deferredSource + discoveryTimeout time.Duration } // Verify interface compliance @@ -40,9 +48,12 @@ var ( _ tools.Instructable = (*ToolSet)(nil) _ tools.Named = (*ToolSet)(nil) _ tools.Catalog = (*ToolSet)(nil) + _ tools.Stateful = (*ToolSet)(nil) ) type deferredSource struct { + id string + base string toolset tools.ToolSet deferAll bool tools []string @@ -57,10 +68,42 @@ func (s *deferredSource) defers(name string) bool { return s.deferAll || slices.Contains(s.tools, name) } +type activationState struct { + activatedTools map[string]tools.Tool + activatedBy map[string]string + pendingRestore map[string]string +} + +func newActivationState() *activationState { + return &activationState{ + activatedTools: make(map[string]tools.Tool), + activatedBy: make(map[string]string), + pendingRestore: make(map[string]string), + } +} + +type persistedActivation struct { + Name string `json:"name"` + Source string `json:"source,omitempty"` +} + func New() *ToolSet { return &ToolSet{ - activatedTools: make(map[string]tools.Tool), + states: make(map[string]*activationState), + discoveryTimeout: defaultDiscoveryTimeout, + } +} + +// SetDiscoveryTimeout overrides the per-call bound used when listing +// deferred sources. Non-positive values restore the default timeout. +func (d *ToolSet) SetDiscoveryTimeout(timeout time.Duration) { + d.mu.Lock() + defer d.mu.Unlock() + if timeout <= 0 { + d.discoveryTimeout = defaultDiscoveryTimeout + return } + d.discoveryTimeout = timeout } // Name implements tools.Named; loader-created, so no registry WithName wrapper. @@ -68,11 +111,166 @@ func (d *ToolSet) Name() string { return "deferred" } +// StateKey implements tools.Stateful. +func (d *ToolSet) StateKey() string { + return d.Name() +} + +// ensureStateLocked returns the activation state for ctx's scope, creating it +// if needed. d.mu must be held for writing. +func (d *ToolSet) ensureStateLocked(ctx context.Context) *activationState { + if d.states == nil { + d.states = make(map[string]*activationState) + } + scope := tools.StateScope(ctx) + state, ok := d.states[scope] + if !ok { + state = newActivationState() + d.states[scope] = state + } + return state +} + +// stateLocked returns the activation state for ctx's scope, or nil. +// d.mu must be held for reading or writing. +func (d *ToolSet) stateLocked(ctx context.Context) *activationState { + return d.states[tools.StateScope(ctx)] +} + +// SnapshotState implements tools.Stateful by returning the sorted JSON list of +// activated tools (with source identities) and pending restore entries for +// ctx's session scope. +func (d *ToolSet) SnapshotState(ctx context.Context) (string, error) { + d.mu.RLock() + defer d.mu.RUnlock() + + state := d.stateLocked(ctx) + if state == nil || (len(state.activatedTools) == 0 && len(state.pendingRestore) == 0) { + return "", nil + } + + byName := make(map[string]string, len(state.activatedTools)+len(state.pendingRestore)) + maps.Copy(byName, state.pendingRestore) + for name := range state.activatedTools { + byName[name] = state.activatedBy[name] + } + + names := slices.Sorted(maps.Keys(byName)) + entries := make([]persistedActivation, 0, len(names)) + for _, name := range names { + entries = append(entries, persistedActivation{ + Name: name, + Source: byName[name], + }) + } + + data, err := json.Marshal(entries) + if err != nil { + return "", fmt.Errorf("marshaling deferred tool state: %w", err) + } + return string(data), nil +} + +// RestoreState implements tools.Stateful, replacing active deferred tools for +// ctx's session scope without eagerly calling Tools() on unlisted sources. +// Already-listed sources are reconciled immediately; unlisted sources stay +// pending and are probed lazily under a bounded deadline when Tools() runs. +func (d *ToolSet) RestoreState(ctx context.Context, data string) error { + scope := tools.StateScope(ctx) + if strings.TrimSpace(data) == "" { + d.mu.Lock() + delete(d.states, scope) + d.mu.Unlock() + return nil + } + + entries, err := unmarshalActivations(data) + if err != nil { + return err + } + + d.mu.Lock() + defer d.mu.Unlock() + + state := newActivationState() + for _, entry := range entries { + if entry.Name == "" { + continue + } + state.pendingRestore[entry.Name] = entry.Source + } + if d.states == nil { + d.states = make(map[string]*activationState) + } + d.states[scope] = state + d.reconcilePendingLocked(state) + return nil +} + +func unmarshalActivations(data string) ([]persistedActivation, error) { + var entries []persistedActivation + if err := json.Unmarshal([]byte(data), &entries); err == nil { + return entries, nil + } + + // Accept legacy []string state produced before source identity tracking. + var names []string + if err := json.Unmarshal([]byte(data), &names); err == nil { + entries = make([]persistedActivation, 0, len(names)) + for _, name := range names { + entries = append(entries, persistedActivation{Name: name}) + } + return entries, nil + } + + return nil, errors.New("unmarshaling deferred tool state: invalid payload") +} + +// reconcilePendingLocked activates any pending restored names found in their +// matching already-listed sources. d.mu must be held for writing. +func (d *ToolSet) reconcilePendingLocked(state *activationState) { + for name, sourceID := range state.pendingRestore { + if outcome, _ := d.activateFromLocked(state, name, sourceID); outcome != outcomeNotFound { + delete(state.pendingRestore, name) + } + } +} + +// reconcilePendingAllLocked reconciles pending restores across every session +// scope after a deferred source finishes listing. d.mu must be held for writing. +func (d *ToolSet) reconcilePendingAllLocked() { + for _, state := range d.states { + if len(state.pendingRestore) > 0 { + d.reconcilePendingLocked(state) + } + } +} + +func (d *ToolSet) pendingRestoreCopy(ctx context.Context) map[string]string { + d.mu.RLock() + defer d.mu.RUnlock() + state := d.stateLocked(ctx) + if state == nil || len(state.pendingRestore) == 0 { + return nil + } + return maps.Clone(state.pendingRestore) +} + func (d *ToolSet) AddSource(toolset tools.ToolSet, deferAll bool, toolNames []string) { d.mu.Lock() defer d.mu.Unlock() + base := tools.DescribeToolSet(toolset) + occurrence := 0 + for _, existing := range d.sources { + if existing.base == base { + occurrence++ + } + } + d.sources = append(d.sources, &deferredSource{ + id: fmt.Sprintf("%s#%d", base, occurrence), + base: base, toolset: toolset, deferAll: deferAll, tools: toolNames, @@ -104,41 +302,125 @@ type AddToolArgs struct { Name string `json:"name" jsonschema:"The name of the tool to activate"` } -// snapshotPendingSources lists every source not yet snapshotted. Sources are -// listed without holding d.mu (an MCP list may be a network round-trip); -// a source that cannot list yet (typically still starting) is skipped and -// retried on the next call, so its tools show up once it is ready. -func (d *ToolSet) snapshotPendingSources(ctx context.Context) { +func (d *ToolSet) boundedDiscoveryTimeout(ctx context.Context) time.Duration { d.mu.RLock() - var pending []*deferredSource - for _, source := range d.sources { - if !source.listed { - pending = append(pending, source) + timeout := d.discoveryTimeout + d.mu.RUnlock() + if timeout <= 0 { + timeout = defaultDiscoveryTimeout + } + if ctxTimeout := tools.DiscoveryTimeout(ctx); ctxTimeout > 0 && ctxTimeout < timeout { + timeout = ctxTimeout + } + if deadline, ok := ctx.Deadline(); ok { + rem := time.Until(deadline) + if rem <= 0 { + return 0 + } + // Keep a thin margin under an outer deadline (e.g. listToolsWithTimeout) + // so responsive sources finish before the outer list is aborted. + if rem < timeout { + if margin := rem * 4 / 5; margin > 0 { + return margin + } + return rem } } - d.mu.RUnlock() + return timeout +} - for _, source := range pending { - allTools, err := source.toolset.Tools(ctx) - if err != nil { - slog.DebugContext(ctx, "Deferred source unavailable; skipping", "source", tools.DescribeToolSet(source.toolset), "error", err) +func sourceMatchesPending(source *deferredSource, pending map[string]string) bool { + if pending == nil { + return true + } + for name, sourceID := range pending { + if sourceID != "" && source.id != sourceID { continue } - - var snapshot []tools.Tool - for _, tool := range allTools { - if source.defers(tool.Name) { - snapshot = append(snapshot, tool) - } + if source.defers(name) { + return true } + } + return false +} - d.mu.Lock() - // A concurrent call may have snapshotted the same source; first wins. - if !source.listed { - source.snapshot = snapshot - source.listed = true +// snapshotSources probes unlisted sources concurrently under a bounded +// deadline. When pendingFilter is non-nil, only sources matching a pending +// restore entry are queried; otherwise every unlisted source is queried. +func (d *ToolSet) snapshotSources(ctx context.Context, pendingFilter map[string]string) { + if ctx.Err() != nil { + return + } + + d.mu.RLock() + var targets []*deferredSource + for _, source := range d.sources { + if !source.listed && sourceMatchesPending(source, pendingFilter) { + targets = append(targets, source) } - d.mu.Unlock() + } + d.mu.RUnlock() + + if len(targets) == 0 { + return + } + + timeout := d.boundedDiscoveryTimeout(ctx) + if timeout <= 0 { + return + } + + probeCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + var wg sync.WaitGroup + for _, source := range targets { + wg.Go(func() { + allTools, err := callToolsBounded(probeCtx, source.toolset) + if err != nil { + slog.DebugContext(probeCtx, "Deferred source unavailable; skipping", "source", source.id, "error", err) + return + } + + var snapshot []tools.Tool + for _, tool := range allTools { + if source.defers(tool.Name) { + snapshot = append(snapshot, tool) + } + } + + d.recordSourceSnapshot(source, snapshot) + }) + } + wg.Wait() +} + +func (d *ToolSet) recordSourceSnapshot(source *deferredSource, snapshot []tools.Tool) { + d.mu.Lock() + defer d.mu.Unlock() + if !source.listed { + source.snapshot = snapshot + source.listed = true + d.reconcilePendingAllLocked() + } +} + +func callToolsBounded(ctx context.Context, toolset tools.ToolSet) ([]tools.Tool, error) { + type result struct { + tools []tools.Tool + err error + } + done := make(chan result, 1) + go func() { + ts, err := toolset.Tools(ctx) + done <- result{tools: ts, err: err} + }() + + select { + case <-ctx.Done(): + return nil, ctx.Err() + case res := <-done: + return res.tools, res.err } } @@ -147,16 +429,19 @@ func (d *ToolSet) snapshotPendingSources(ctx context.Context) { // includeActivated: search_tool offers only what add_tool can still activate, // while the catalog covers every deferred tool regardless of activation. func (d *ToolSet) deferredTools(ctx context.Context, includeActivated bool) map[string]tools.Tool { - d.snapshotPendingSources(ctx) + d.snapshotSources(ctx, nil) d.mu.RLock() defer d.mu.RUnlock() + state := d.stateLocked(ctx) result := make(map[string]tools.Tool) for _, source := range d.sources { for _, tool := range source.snapshot { - if _, active := d.activatedTools[tool.Name]; active && !includeActivated { - continue + if !includeActivated && state != nil { + if _, active := state.activatedTools[tool.Name]; active { + continue + } } if _, exists := result[tool.Name]; !exists { result[tool.Name] = tool @@ -248,13 +533,17 @@ const ( ) func (d *ToolSet) handleAddTool(ctx context.Context, args AddToolArgs) (*tools.ToolCallResult, error) { - d.snapshotPendingSources(ctx) + d.snapshotSources(ctx, nil) // Decide and apply under one lock so concurrent add_tool calls for the // same name report exactly one activation. d.mu.Lock() - outcome, tool := d.activateLocked(args.Name) - activatedCount := len(d.activatedTools) + state := d.ensureStateLocked(ctx) + outcome, tool := d.activateFromLocked(state, args.Name, "") + if outcome != outcomeNotFound { + delete(state.pendingRestore, args.Name) + } + activatedCount := len(state.activatedTools) d.mu.Unlock() if span := trace.SpanFromContext(ctx); span.IsRecording() { @@ -276,16 +565,24 @@ func (d *ToolSet) handleAddTool(ctx context.Context, args AddToolArgs) (*tools.T } } -// activateLocked activates name from the first listed source that defers it. +// activateFromLocked activates name from the specified source (or the first +// listed source that defers it when requiredSourceID is empty). // d.mu must be held for writing. -func (d *ToolSet) activateLocked(name string) (addOutcome, tools.Tool) { - if tool, active := d.activatedTools[name]; active { +func (d *ToolSet) activateFromLocked(state *activationState, name, requiredSourceID string) (addOutcome, tools.Tool) { + if tool, active := state.activatedTools[name]; active { return outcomeAlreadyActive, tool } for _, source := range d.sources { + if !source.listed { + continue + } + if requiredSourceID != "" && source.id != requiredSourceID { + continue + } for _, tool := range source.snapshot { if tool.Name == name { - d.activatedTools[name] = tool + state.activatedTools[name] = tool + state.activatedBy[name] = source.id return outcomeActivated, tool } } @@ -293,7 +590,11 @@ func (d *ToolSet) activateLocked(name string) (addOutcome, tools.Tool) { return outcomeNotFound, tools.Tool{} } -func (d *ToolSet) Tools(context.Context) ([]tools.Tool, error) { +func (d *ToolSet) Tools(ctx context.Context) ([]tools.Tool, error) { + if pending := d.pendingRestoreCopy(ctx); len(pending) > 0 { + d.snapshotSources(ctx, pending) + } + d.mu.RLock() defer d.mu.RUnlock() @@ -324,8 +625,11 @@ func (d *ToolSet) Tools(context.Context) ([]tools.Tool, error) { }, } - for _, tool := range d.activatedTools { - result = append(result, tool) + if state := d.stateLocked(ctx); state != nil && len(state.activatedTools) > 0 { + names := slices.Sorted(maps.Keys(state.activatedTools)) + for _, name := range names { + result = append(result, state.activatedTools[name]) + } } return result, nil diff --git a/pkg/tools/builtin/deferred/deferred_test.go b/pkg/tools/builtin/deferred/deferred_test.go index 93a4cb824b..33bac996a2 100644 --- a/pkg/tools/builtin/deferred/deferred_test.go +++ b/pkg/tools/builtin/deferred/deferred_test.go @@ -7,6 +7,7 @@ import ( "sync" "sync/atomic" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -346,3 +347,265 @@ func catalogNames(catalog []tools.Tool) []string { } return names } + +func TestDeferredToolset_SnapshotAndRestore(t *testing.T) { + t.Parallel() + ctx := t.Context() + + handler := tools.NewHandler(func(context.Context, struct{}) (*tools.ToolCallResult, error) { + return tools.ResultSuccess("ok"), nil + }) + source := &mockToolSet{toolList: []tools.Tool{ + {Name: "tool1", Description: "First tool", Handler: handler}, + {Name: "tool2", Description: "Second tool", Handler: handler}, + }} + + dt1 := New() + dt1.AddSource(source, true, nil) + + snap, err := dt1.SnapshotState(ctx) + require.NoError(t, err) + assert.Empty(t, snap) + + _, err = dt1.handleAddTool(ctx, AddToolArgs{Name: "tool1"}) + require.NoError(t, err) + + snap, err = dt1.SnapshotState(ctx) + require.NoError(t, err) + assert.Contains(t, snap, `"tool1"`) + + // New process / fresh deferred toolset restores tool1 without needing add_tool again. + dt2 := New() + dt2.AddSource(&mockToolSet{toolList: source.toolList}, true, nil) + require.NoError(t, dt2.RestoreState(ctx, snap)) + + restoredTools, err := dt2.Tools(ctx) + require.NoError(t, err) + assert.Equal(t, []string{ToolNameSearchTool, ToolNameAddTool, "tool1"}, catalogNames(restoredTools)) + + searchRes, err := dt2.handleSearchTool(ctx, SearchToolArgs{Query: "tool"}) + require.NoError(t, err) + assert.Contains(t, searchRes.Output, "tool2") + assert.NotContains(t, searchRes.Output, `"tool1"`) + + // Legacy []string snapshots remain restorable. + dtLegacy := New() + dtLegacy.AddSource(&mockToolSet{toolList: source.toolList}, true, nil) + require.NoError(t, dtLegacy.RestoreState(ctx, `["tool1"]`)) + legacyTools, err := dtLegacy.Tools(ctx) + require.NoError(t, err) + assert.Equal(t, []string{ToolNameSearchTool, ToolNameAddTool, "tool1"}, catalogNames(legacyTools)) + + // Invalid JSON leaves active state intact. + require.Error(t, dt2.RestoreState(ctx, "{bad")) + snapAfterErr, err := dt2.SnapshotState(ctx) + require.NoError(t, err) + assert.Equal(t, snap, snapAfterErr) + + // Empty state clears previously activated tools. + require.NoError(t, dt2.RestoreState(ctx, "")) + clearedTools, err := dt2.Tools(ctx) + require.NoError(t, err) + assert.Equal(t, []string{ToolNameSearchTool, ToolNameAddTool}, catalogNames(clearedTools)) + snapCleared, err := dt2.SnapshotState(ctx) + require.NoError(t, err) + assert.Empty(t, snapCleared) +} + +func TestDeferredToolset_RestoreSlowSource(t *testing.T) { + t.Parallel() + ctx := t.Context() + + slow := &mockToolSet{toolList: []tools.Tool{{Name: "slow_tool", Description: "Slow"}}} + slow.notStarted.Store(true) + ready := &mockToolSet{toolList: []tools.Tool{{Name: "ready_tool", Description: "Ready"}}} + + dt := New() + dt.AddSource(slow, true, nil) + dt.AddSource(ready, true, nil) + + require.NoError(t, dt.RestoreState(ctx, `["slow_tool","ready_tool"]`)) + + // ready_tool is immediately active, and slow_tool remains in the snapshot while starting. + current, err := dt.Tools(ctx) + require.NoError(t, err) + assert.Equal(t, []string{ToolNameSearchTool, ToolNameAddTool, "ready_tool"}, catalogNames(current)) + + snap, err := dt.SnapshotState(ctx) + require.NoError(t, err) + assert.Contains(t, snap, `"ready_tool"`) + assert.Contains(t, snap, `"slow_tool"`) + + // Once slow finishes starting, Tools activates slow_tool automatically. + slow.notStarted.Store(false) + current, err = dt.Tools(ctx) + require.NoError(t, err) + assert.ElementsMatch(t, []string{ToolNameSearchTool, ToolNameAddTool, "ready_tool", "slow_tool"}, catalogNames(current)) +} + +func TestDeferredToolset_ConcurrentSessionIsolation(t *testing.T) { + t.Parallel() + + source := &mockToolSet{toolList: []tools.Tool{ + {Name: "tool_a", Description: "Tool A"}, + {Name: "tool_b", Description: "Tool B"}, + }} + dt := New() + dt.AddSource(source, true, nil) + + ctxA := tools.WithStateScope(t.Context(), "session-a") + ctxB := tools.WithStateScope(t.Context(), "session-b") + + _, err := dt.handleAddTool(ctxA, AddToolArgs{Name: "tool_a"}) + require.NoError(t, err) + + // Restoring empty state in session B must not wipe session A's activation. + require.NoError(t, dt.RestoreState(ctxB, "")) + + toolsA, err := dt.Tools(ctxA) + require.NoError(t, err) + assert.Equal(t, []string{ToolNameSearchTool, ToolNameAddTool, "tool_a"}, catalogNames(toolsA)) + + toolsB, err := dt.Tools(ctxB) + require.NoError(t, err) + assert.Equal(t, []string{ToolNameSearchTool, ToolNameAddTool}, catalogNames(toolsB)) + + snapA, err := dt.SnapshotState(ctxA) + require.NoError(t, err) + assert.Contains(t, snapA, `"tool_a"`) + snapB, err := dt.SnapshotState(ctxB) + require.NoError(t, err) + assert.Empty(t, snapB) + + searchB, err := dt.handleSearchTool(ctxB, SearchToolArgs{Query: "tool_"}) + require.NoError(t, err) + assert.Contains(t, searchB.Output, "tool_a") +} + +type describedMockToolSet struct { + *mockToolSet + + desc string +} + +func (d *describedMockToolSet) Describe() string { return d.desc } + +func TestDeferredToolset_DuplicateNameDelayedOriginalSource(t *testing.T) { + t.Parallel() + ctx := t.Context() + + firstA := &describedMockToolSet{ + desc: "source-alpha", + mockToolSet: &mockToolSet{toolList: []tools.Tool{{Name: "dup", Description: "from alpha"}}}, + } + firstB := &describedMockToolSet{ + desc: "source-beta", + mockToolSet: &mockToolSet{toolList: []tools.Tool{{Name: "dup", Description: "from beta"}}}, + } + + dt1 := New() + dt1.AddSource(firstA, true, nil) + dt1.AddSource(firstB, true, nil) + + _, err := dt1.handleAddTool(ctx, AddToolArgs{Name: "dup"}) + require.NoError(t, err) + snap, err := dt1.SnapshotState(ctx) + require.NoError(t, err) + + // On resume, the original source-alpha is delayed while source-beta lists immediately. + resumedA := &describedMockToolSet{ + desc: "source-alpha", + mockToolSet: &mockToolSet{toolList: []tools.Tool{{Name: "dup", Description: "from alpha"}}}, + } + resumedA.notStarted.Store(true) + resumedB := &describedMockToolSet{ + desc: "source-beta", + mockToolSet: &mockToolSet{toolList: []tools.Tool{{Name: "dup", Description: "from beta"}}}, + } + + dt2 := New() + dt2.AddSource(resumedA, true, nil) + dt2.AddSource(resumedB, true, nil) + require.NoError(t, dt2.RestoreState(ctx, snap)) + + // Even if source-beta gets listed first via search_tool, "dup" must not bind to source-beta. + _, err = dt2.handleSearchTool(ctx, SearchToolArgs{Query: "nonexistent"}) + require.NoError(t, err) + + current, err := dt2.Tools(ctx) + require.NoError(t, err) + assert.Equal(t, []string{ToolNameSearchTool, ToolNameAddTool}, catalogNames(current)) + + // Once source-alpha comes online, "dup" activates with source-alpha's definition. + resumedA.notStarted.Store(false) + current, err = dt2.Tools(ctx) + require.NoError(t, err) + require.Len(t, current, 3) + assert.Equal(t, "dup", current[2].Name) + assert.Equal(t, "from alpha", current[2].Description) +} + +type blockingMockToolSet struct { + release chan struct{} + calls atomic.Int32 +} + +func (b *blockingMockToolSet) Tools(context.Context) ([]tools.Tool, error) { + b.calls.Add(1) + <-b.release + return nil, nil +} + +func TestDeferredToolset_RestoreSkipsIrrelevantSourcesAndBoundsStalled(t *testing.T) { + t.Parallel() + ctx := t.Context() + + release := make(chan struct{}) + defer close(release) + + ready := &describedMockToolSet{ + desc: "ready-src", + mockToolSet: &mockToolSet{toolList: []tools.Tool{{Name: "fast_tool", Description: "Fast"}}}, + } + stalled := &blockingMockToolSet{release: release} + + // Capture state with fast_tool active. + dt1 := New() + dt1.AddSource(ready, true, nil) + _, err := dt1.handleAddTool(ctx, AddToolArgs{Name: "fast_tool"}) + require.NoError(t, err) + snapFastOnly, err := dt1.SnapshotState(ctx) + require.NoError(t, err) + + // RestoreState itself must not eagerly list unrelated or stalled sources. + dt2 := New() + dt2.SetDiscoveryTimeout(40 * time.Millisecond) + dt2.AddSource(&describedMockToolSet{ + desc: "ready-src", + mockToolSet: &mockToolSet{toolList: []tools.Tool{{Name: "fast_tool", Description: "Fast"}}}, + }, true, nil) + dt2.AddSource(stalled, true, nil) + + require.NoError(t, dt2.RestoreState(ctx, snapFastOnly)) + assert.Zero(t, stalled.calls.Load(), "RestoreState must not eagerly query sources") + + start := time.Now() + listed, err := dt2.Tools(ctx) + require.NoError(t, err) + assert.Less(t, time.Since(start), 200*time.Millisecond) + assert.Equal(t, []string{ToolNameSearchTool, ToolNameAddTool, "fast_tool"}, catalogNames(listed)) + assert.Zero(t, stalled.calls.Load(), "unrelated deferred source must not be probed") + + // When a pending tool belongs to the stalled source itself (which ignores ctx), + // Tools() must still finish within the discovery bound and keep it pending. + require.NoError(t, dt2.RestoreState(ctx, `[{"name":"fast_tool","source":"ready-src#0"},{"name":"stalled_tool","source":"*deferred.blockingMockToolSet#0"}]`)) + start = time.Now() + listed, err = dt2.Tools(ctx) + require.NoError(t, err) + assert.Less(t, time.Since(start), 300*time.Millisecond) + assert.Equal(t, []string{ToolNameSearchTool, ToolNameAddTool, "fast_tool"}, catalogNames(listed)) + + snapAfterTimeout, err := dt2.SnapshotState(ctx) + require.NoError(t, err) + assert.Contains(t, snapAfterTimeout, `"stalled_tool"`) +} diff --git a/pkg/tools/stateful.go b/pkg/tools/stateful.go new file mode 100644 index 0000000000..4926c00319 --- /dev/null +++ b/pkg/tools/stateful.go @@ -0,0 +1,53 @@ +package tools + +import ( + "context" + "time" +) + +type ( + stateScopeKey struct{} + discoveryTimeoutKey struct{} +) + +// WithStateScope binds a session identifier to ctx so Stateful toolsets +// shared across sessions keep per-session state isolated. +func WithStateScope(ctx context.Context, scope string) context.Context { + if scope == "" { + return ctx + } + return context.WithValue(ctx, stateScopeKey{}, scope) +} + +// StateScope returns the session scope identifier bound to ctx, or "". +func StateScope(ctx context.Context) string { + scope, _ := ctx.Value(stateScopeKey{}).(string) + return scope +} + +// WithDiscoveryTimeout bounds lazy source discovery inside a single list call +// so an unresponsive deferred source cannot block startup or resumed turns. +func WithDiscoveryTimeout(ctx context.Context, d time.Duration) context.Context { + if d <= 0 { + return ctx + } + return context.WithValue(ctx, discoveryTimeoutKey{}, d) +} + +// DiscoveryTimeout returns the discovery bound attached to ctx, or 0. +func DiscoveryTimeout(ctx context.Context) time.Duration { + d, _ := ctx.Value(discoveryTimeoutKey{}).(time.Duration) + return d +} + +// Stateful is implemented by toolsets whose in-memory state depends on the +// active session (for example, deferred tools activated with add_tool). +// +// Implementations provide a stable key plus snapshot and restore methods so the +// runtime can persist per-agent state on the session and re-apply it when +// resuming a session or continuing a durable run. +type Stateful interface { + StateKey() string + SnapshotState(ctx context.Context) (string, error) + RestoreState(ctx context.Context, data string) error +}