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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions pkg/acp/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
49 changes: 45 additions & 4 deletions pkg/runtime/durable.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -221,13 +221,31 @@ 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 {
state := sessionState{
InstructionContext: sess.InstructionContextSnapshot(),
SafetyPolicy: sess.GetSafetyPolicy(),
Permissions: sess.ClonePermissions(),
Attributes: toolsetAttributesOf(sess.AttributesSnapshot()),
HasToolsetState: true,
}
state.InputTokens, state.OutputTokens = sess.Usage()
return state
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -536,13 +559,23 @@ 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.
func (rec *runRecord) CallRecorded(ctx context.Context, callID string, result *tools.ToolCallResult, record func()) error {
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,
Expand All @@ -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})
}

Expand Down Expand Up @@ -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
}
Expand Down
16 changes: 15 additions & 1 deletion pkg/runtime/loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)))
Expand Down Expand Up @@ -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)))
Expand Down Expand Up @@ -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)
Comment thread
iemafzalhassan marked this conversation as resolved.
Resolved
}
if err := t.rec.failure(); err != nil {
return turnExit, r.stopUnrecorded(ctx, sess, a, err, events), true
}
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions pkg/runtime/startup_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
108 changes: 108 additions & 0 deletions pkg/runtime/toolset_state.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading