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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
|
package main
// The HTTP interface.
//
// hans is a coding agent that other language models can read and drive. The
// reading half is the same move mailweb makes: render state the program already
// holds as plain text, framed, with every response listing the routes reachable
// from it, so a client can navigate the whole interface from one request to /.
//
// The driving half is new, and is the part that needed an argument. What makes
// it tolerable is the tree: a turn does not mutate a conversation, it appends a
// node to it. Two clients prompting the same node produce siblings, so a second
// agent cannot damage the conversation a first one is having — the worst it can
// do is start a branch nobody reads. That is why there is no lock here despite
// turns taking a minute and several clients being able to arrive at once.
//
// What is deliberately NOT here: authentication, authorisation, and any check
// on what a tool may touch. See the caveats in hans.1. The posture is mailweb's
// — bind loopback, say so loudly — and it is only defensible because the thing
// on the other end of the socket is already able to run as this user.
import (
_ "embed"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
//go:embed templates/sessions.llm
var sessionsLLMSrc string
//go:embed templates/session.llm
var sessionLLMSrc string
//go:embed templates/node.llm
var nodeLLMSrc string
//go:embed templates/path.llm
var pathLLMSrc string
var (
sessionsTmpl = mustParseLLM("sessions.llm", sessionsLLMSrc)
sessionTmpl = mustParseLLM("session.llm", sessionLLMSrc)
nodeTmpl = mustParseLLM("node.llm", nodeLLMSrc)
pathTmpl = mustParseLLM("path.llm", pathLLMSrc)
)
// httpServer holds what the handlers need.
type httpServer struct {
store *store
agent *agent
// model is what new sessions are created with.
model string
// cwd is the directory the process runs in, and therefore the only
// directory its tools can act on. A session started elsewhere can be read
// but not continued; see runPrompt.
cwd string
}
// serve runs the HTTP interface until the process is killed.
func serve(addr string, st *store, b backend, model string) error {
cwd, err := os.Getwd()
if err != nil {
return err
}
s := &httpServer{
store: st,
agent: &agent{store: st, backend: b, actor: "http"},
model: model,
cwd: cwd,
}
srv := &http.Server{
Addr: addr,
Handler: s.routes(),
// A turn blocks its request for as long as the model takes, which is
// seconds normally and minutes when tools run in a loop. A write
// timeout would cut the response off mid-turn and hand the client a
// truncated document, so there is none. The read timeout stays: it
// bounds how long an idle connection can hold a slot, which is a
// different problem with a different answer.
WriteTimeout: 0,
ReadHeaderTimeout: 30 * time.Second,
}
log.Printf("hans: serving %s on http://%s", st.Path, addr)
log.Printf("hans: turns run in %s", cwd)
return srv.ListenAndServe()
}
func (s *httpServer) routes() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", s.handleSessions)
mux.HandleFunc("GET /session/{name}", s.handleSession)
mux.HandleFunc("GET /session/{name}/head", s.handleHead)
mux.HandleFunc("GET /node/{id}", s.handleNode)
mux.HandleFunc("GET /node/{id}/path", s.handlePath)
mux.HandleFunc("POST /session", s.handleCreateSession)
mux.HandleFunc("POST /session/{name}/prompt", s.handleSessionPrompt)
mux.HandleFunc("POST /node/{id}/prompt", s.handleNodePrompt)
return mux
}
// ============================================================================
// Reading
// ============================================================================
func (s *httpServer) handleSessions(w http.ResponseWriter, r *http.Request) {
sessions, err := s.store.listSessions()
if err != nil {
serverError(w, err)
return
}
p := parsePaging(r, len(sessions), defaultLimit)
writeLLM(w, r, sessionsTmpl, sessionsData{
Sessions: slicePage(sessions, p),
Paging: p,
})
}
func (s *httpServer) handleSession(w http.ResponseWriter, r *http.Request) {
sess, ok := s.lookupSession(w, r)
if !ok {
return
}
nodes, err := s.store.sessionNodes(sess.ID)
if err != nil {
serverError(w, err)
return
}
rows := buildTree(nodes)
p := parsePaging(r, len(rows), defaultLimit)
leaves := 0
for _, n := range nodes {
if n.IsLeaf() {
leaves++
}
}
var headID int64
if head, err := s.store.head(sess.ID); err == nil && head != nil {
headID = head.ID
}
writeLLM(w, r, sessionTmpl, sessionData{
Session: *sess,
Rows: slicePage(rows, p),
Paging: p,
Head: headID,
Leaves: leaves,
})
}
// handleHead redirects to the path ending at the session's newest leaf, which
// is what "show me this conversation" means for a tree that may have branched.
//
// A redirect rather than rendering the path here: the answer is a particular
// node's path, and saying so in the URL means a client that follows it can tell
// which branch it got, and can come back to that same one later.
func (s *httpServer) handleHead(w http.ResponseWriter, r *http.Request) {
sess, ok := s.lookupSession(w, r)
if !ok {
return
}
head, err := s.store.head(sess.ID)
if err != nil {
serverError(w, err)
return
}
if head == nil {
http.Error(w, fmt.Sprintf("session %s has no turns yet; POST to /session/%s/prompt to start it\n",
sess.Name, sess.Name), http.StatusNotFound)
return
}
http.Redirect(w, r, fmt.Sprintf("/node/%d/path%s", head.ID, viewSuffix(r)), http.StatusSeeOther)
}
func (s *httpServer) handleNode(w http.ResponseWriter, r *http.Request) {
n, ok := s.lookupNode(w, r)
if !ok {
return
}
sess, err := s.sessionOf(n.SessionID)
if err != nil {
serverError(w, err)
return
}
all, err := s.store.sessionNodes(n.SessionID)
if err != nil {
serverError(w, err)
return
}
var children []nodeView
for _, c := range all {
if c.ParentID == n.ID {
children = append(children, viewNode(c))
}
}
writeLLM(w, r, nodeTmpl, nodeData{
Session: *sess,
Node: viewNode(*n),
Children: children,
})
}
func (s *httpServer) handlePath(w http.ResponseWriter, r *http.Request) {
n, ok := s.lookupNode(w, r)
if !ok {
return
}
sess, err := s.sessionOf(n.SessionID)
if err != nil {
serverError(w, err)
return
}
path, err := s.store.pathTo(n.ID)
if err != nil {
serverError(w, err)
return
}
p := parsePaging(r, len(path), defaultLimit)
writeLLM(w, r, pathTmpl, pathData{
Session: *sess,
Nodes: viewNodes(slicePage(path, p)),
Paging: p,
Node: n.ID,
})
}
// ============================================================================
// Writing
// ============================================================================
func (s *httpServer) handleCreateSession(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "cannot parse form; send application/x-www-form-urlencoded\n",
http.StatusBadRequest)
return
}
name := strings.TrimSpace(r.PostFormValue("name"))
sess, err := s.store.createSession(name, s.cwd, s.model)
if errors.Is(err, errNameTaken) {
http.Error(w, fmt.Sprintf(
"a session called %q already exists; read it at /session/%s,\n"+
"or omit the name to have one generated.\n", name, name),
http.StatusConflict)
return
}
if err != nil {
serverError(w, err)
return
}
http.Redirect(w, r, "/session/"+sess.Name+viewSuffix(r), http.StatusSeeOther)
}
func (s *httpServer) handleSessionPrompt(w http.ResponseWriter, r *http.Request) {
sess, ok := s.lookupSession(w, r)
if !ok {
return
}
var parentID int64
head, err := s.store.head(sess.ID)
if err != nil {
serverError(w, err)
return
}
if head != nil {
parentID = head.ID
}
s.runPrompt(w, r, sess, parentID)
}
func (s *httpServer) handleNodePrompt(w http.ResponseWriter, r *http.Request) {
n, ok := s.lookupNode(w, r)
if !ok {
return
}
sess, err := s.sessionOf(n.SessionID)
if err != nil {
serverError(w, err)
return
}
s.runPrompt(w, r, sess, n.ID)
}
// runPrompt runs one turn and answers with the node it produced.
//
// It blocks. A turn takes seconds to minutes, and this holds the request open
// for all of it. That is a deliberate trade for a simpler client: one request
// answers with the result, and no polling loop has to be written by every
// caller. What makes it survivable is that the turn is not tied to the
// connection — the nodes are committed as they are made, so a client that
// disconnects loses the rendering and nothing else, and finds the turn under
// /session/{name} afterwards.
func (s *httpServer) runPrompt(w http.ResponseWriter, r *http.Request, sess *session, parentID int64) {
if err := r.ParseForm(); err != nil {
http.Error(w, "cannot parse form; send application/x-www-form-urlencoded\n",
http.StatusBadRequest)
return
}
text := strings.TrimSpace(r.PostFormValue("text"))
if text == "" {
// Naming the encoding is not pedantry. A JSON body — the obvious guess
// for a machine interface — parses without error in Go's form parser
// and yields no fields at all, so the likeliest reason to be here is a
// client that sent JSON and would otherwise be told its empty prompt
// succeeded.
http.Error(w, "field `text` is required, as application/x-www-form-urlencoded.\n"+
"A JSON body parses as an empty form and looks exactly like this error.\n",
http.StatusBadRequest)
return
}
// A session records the directory its turns ran in, and this process can
// only act on its own. Continuing a session from elsewhere would run tools
// against paths that mean something different from what the transcript
// says, so it is refused rather than silently done in the wrong place.
if sess.Cwd != s.cwd {
http.Error(w, fmt.Sprintf(
"session %s belongs to %s, but this hans serves %s.\n"+
"Run a hans in that directory to continue it.\n",
sess.Name, sess.Cwd, s.cwd), http.StatusConflict)
return
}
// The turn is bound to the request's context, so a client that hangs up
// stops the work rather than leaving it running for nobody. The nodes made
// up to that point remain, marked interrupted.
out := sink{Answer: io.Discard, Notes: nil}
last, err := s.agent.runTurn(r.Context(), sess, parentID, text, out)
if err != nil {
if last == nil {
serverError(w, err)
return
}
// A partial turn still has a node worth showing, so fall through and
// render it; its error field says what went wrong.
}
if last == nil {
serverError(w, fmt.Errorf("turn produced no node"))
return
}
http.Redirect(w, r, fmt.Sprintf("/node/%d%s", last.ID, viewSuffix(r)), http.StatusSeeOther)
}
// ============================================================================
// Helpers
// ============================================================================
// lookupSession resolves the {name} path value, answering 404 itself when there
// is no such session.
func (s *httpServer) lookupSession(w http.ResponseWriter, r *http.Request) (*session, bool) {
ref := r.PathValue("name")
sess, err := s.store.findSession(ref)
if err != nil {
serverError(w, err)
return nil, false
}
if sess == nil {
http.Error(w, fmt.Sprintf("no session %q; see / for the list\n", ref), http.StatusNotFound)
return nil, false
}
return sess, true
}
// lookupNode resolves the {id} path value.
func (s *httpServer) lookupNode(w http.ResponseWriter, r *http.Request) (*node, bool) {
idStr := r.PathValue("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.Error(w, fmt.Sprintf("node id %q is not a number\n", idStr), http.StatusBadRequest)
return nil, false
}
n, err := s.store.getNode(id)
if err != nil {
serverError(w, err)
return nil, false
}
if n == nil {
http.Error(w, fmt.Sprintf("no node %d\n", id), http.StatusNotFound)
return nil, false
}
return n, true
}
// sessionOf returns the session a node belongs to. It looks up by row id
// exclusively: this id came out of the nodes table, and resolving it as a name
// would let a session called "5" answer for session 5.
func (s *httpServer) sessionOf(id int64) (*session, error) {
sess, err := s.store.sessionByID(id)
if err != nil {
return nil, err
}
if sess == nil {
return nil, fmt.Errorf("node belongs to session %d, which does not exist", id)
}
return sess, nil
}
// viewSuffix preserves the ?view=llm selection across a redirect. A browser
// following a link cannot set an Accept header, so losing the parameter would
// land it on a route it cannot read.
func viewSuffix(r *http.Request) string {
if viaViewParam(r) {
return "?" + viewParam + "=" + viewValue
}
return ""
}
// serverError logs the detail and tells the client only that something broke.
func serverError(w http.ResponseWriter, err error) {
log.Printf("hans: %v", err)
http.Error(w, "internal error\n", http.StatusInternalServerError)
}
|