-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathconversation_context.go
More file actions
225 lines (213 loc) · 7.12 KB
/
Copy pathconversation_context.go
File metadata and controls
225 lines (213 loc) · 7.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package daemon
import (
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/Kocoro-lab/ShanClaw/internal/agents"
"github.com/Kocoro-lab/ShanClaw/internal/client"
"github.com/Kocoro-lab/ShanClaw/internal/session"
)
const maxSideChatHistoryMessages = 100
type forkSessionRequest struct {
Agent string `json:"agent,omitempty"`
TargetAgent *string `json:"target_agent,omitempty"`
MessageIndex int `json:"message_index"`
}
type forkSessionResponse struct {
SessionID string `json:"session_id"`
Title string `json:"title"`
}
type sideChatHistoryMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type sideChatRequest struct {
Agent string `json:"agent,omitempty"`
MessageIndex int `json:"message_index"`
Text string `json:"text"`
History []sideChatHistoryMessage `json:"history,omitempty"`
}
func (s *Server) handleForkSession(w http.ResponseWriter, r *http.Request) {
if s.deps == nil || s.deps.SessionCache == nil {
writeError(w, http.StatusInternalServerError, "daemon deps not configured")
return
}
id, body, ok := s.decodeConversationContextRequest(w, r)
if !ok {
return
}
sourceManager := s.deps.SessionCache.GetOrCreateManager(s.deps.SessionCache.SessionsDir(body.Agent))
targetAgent := body.Agent
if body.TargetAgent != nil {
targetAgent = *body.TargetAgent
}
// GetOrCreateManager creates the target session directory, so a typo'd
// agent would silently file the fork where no UI ever lists it.
if !s.conversationAgentExists(targetAgent) {
writeErrorCode(w, http.StatusBadRequest, "agent_not_found",
fmt.Sprintf("agent not found: %s", targetAgent))
return
}
targetManager := s.deps.SessionCache.GetOrCreateManager(s.deps.SessionCache.SessionsDir(targetAgent))
fork, err := sourceManager.ForkSessionInto(id, body.MessageIndex, targetManager)
if err != nil {
writeConversationContextError(w, id, err)
return
}
writeJSON(w, http.StatusCreated, forkSessionResponse{SessionID: fork.ID, Title: fork.Title})
}
func (s *Server) handleSideChat(w http.ResponseWriter, r *http.Request) {
if s.deps == nil || s.deps.SessionCache == nil {
writeError(w, http.StatusInternalServerError, "daemon deps not configured")
return
}
id := r.PathValue("id")
if err := ValidateSessionID(id); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
var body sideChatRequest
if !decodeBody(w, r, &body) {
return
}
if body.Agent == "default" {
body.Agent = ""
}
if body.Agent != "" {
if err := agents.ValidateAgentName(body.Agent); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
}
// The ephemeral run executes AS this agent; failing here beats a late
// "agent not found" 500 out of RunAgent.
if !s.conversationAgentExists(body.Agent) {
writeErrorCode(w, http.StatusBadRequest, "agent_not_found",
fmt.Sprintf("agent not found: %s", body.Agent))
return
}
if strings.TrimSpace(body.Text) == "" {
writeError(w, http.StatusBadRequest, "text is required")
return
}
if len(body.History) > maxSideChatHistoryMessages {
writeError(w, http.StatusBadRequest, "side chat history is too long")
return
}
mgr := s.deps.SessionCache.GetOrCreateManager(s.deps.SessionCache.SessionsDir(body.Agent))
source, err := mgr.Load(id)
if err != nil {
writeConversationContextError(w, id, err)
return
}
index := body.MessageIndex
if index == 0 {
index = len(source.Messages)
}
history, err := mgr.CopyHistoryThrough(id, index)
if err != nil {
writeConversationContextError(w, id, err)
return
}
for _, item := range body.History {
role := strings.TrimSpace(item.Role)
content := strings.TrimSpace(item.Content)
if (role != "user" && role != "assistant") || content == "" {
writeError(w, http.StatusBadRequest, "side chat history must contain non-empty user/assistant messages")
return
}
history = append(history, client.Message{Role: role, Content: client.NewTextContent(content)})
}
// Side chats run with the normal tool registry and permission engine —
// identical capability to the primary conversation, only the lifecycle is
// ephemeral. Approvals flow over the per-request SSE stream like any
// /message run.
req := RunAgentRequest{
Text: body.Text,
Agent: body.Agent,
Source: "desktop",
CWD: source.CWD,
ProjectID: source.ProjectID,
NewSession: true,
Ephemeral: true,
BypassRouting: true,
SessionHistory: history,
SuppressBusEvents: true,
StickyContext: "This is a temporary side conversation branched from the primary conversation; its transcript is not saved. You have your normal tools — use them when they help answer. Do not modify or claim to modify the primary conversation itself.",
}
if err := req.Validate(); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if strings.Contains(r.Header.Get("Accept"), "text/event-stream") {
s.handleMessageSSE(w, r, req)
return
}
handler := &httpEventHandler{}
result, err := RunAgent(r.Context(), s.deps, req, handler)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, result)
}
func (s *Server) decodeConversationContextRequest(w http.ResponseWriter, r *http.Request) (string, forkSessionRequest, bool) {
id := r.PathValue("id")
if err := ValidateSessionID(id); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return "", forkSessionRequest{}, false
}
var body forkSessionRequest
if !decodeBody(w, r, &body) {
return "", forkSessionRequest{}, false
}
if body.Agent == "default" {
body.Agent = ""
}
if body.Agent != "" {
if err := agents.ValidateAgentName(body.Agent); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return "", forkSessionRequest{}, false
}
}
if body.TargetAgent != nil {
target := *body.TargetAgent
if target == "default" {
target = ""
}
if target != "" {
if err := agents.ValidateAgentName(target); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return "", forkSessionRequest{}, false
}
}
body.TargetAgent = &target
}
return id, body, true
}
// conversationAgentExists reports whether a named agent is defined (user dir
// or _builtin fallback, mirroring agents.LoadAgent's resolution). The empty
// name is the default agent, which always exists.
func (s *Server) conversationAgentExists(name string) bool {
if name == "" {
return true
}
if _, err := os.Stat(filepath.Join(s.deps.AgentsDir, name, "AGENT.md")); err == nil {
return true
}
_, err := os.Stat(filepath.Join(s.deps.AgentsDir, "_builtin", name, "AGENT.md"))
return err == nil
}
func writeConversationContextError(w http.ResponseWriter, id string, err error) {
switch {
case errors.Is(err, os.ErrNotExist):
writeError(w, http.StatusNotFound, fmt.Sprintf("session %q not found", id))
case errors.Is(err, session.ErrMessageIndexOutOfRange), errors.Is(err, session.ErrIncompleteTurnBoundary):
writeError(w, http.StatusBadRequest, err.Error())
default:
writeError(w, http.StatusInternalServerError, err.Error())
}
}