oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package pi
2
3import (
4 "amadan.net/oficina/equipo/internal/fakepi"
5 "bufio"
6 "context"
7 "crypto/sha256"
8 "encoding/hex"
9 "encoding/json"
10 "fmt"
11 "net"
12 "os"
13 "path/filepath"
14 "slices"
15 "sync"
16 "testing"
17 "time"
18
19 "amadan.net/oficina/equipo/internal/runner/containment"
20 "amadan.net/oficina/equipo/internal/runner/egress"
21 "amadan.net/oficina/equipo/internal/runner/provider"
22 "amadan.net/oficina/equipo/internal/testci"
23)
24
25// testKey is the key the tests deliver; the fake refuses any other.
26const testKey = fakepi.TestKey
27
28// toolServer is the runner's end of the attempt's tool socket: Equipo's
29// step tools over MCP, recording each call.
30type toolServer struct {
31 path string
32 mu sync.Mutex
33 calls []string
34}
35
36func (s *toolServer) called() []string {
37 s.mu.Lock()
38 defer s.mu.Unlock()
39 return append([]string(nil), s.calls...)
40}
41
42func startToolServer(t *testing.T, root string, tools []string) *toolServer {
43 t.Helper()
44 dir, err := os.MkdirTemp(root, "tool-")
45 if err != nil {
46 t.Fatal(err)
47 }
48 os.Chmod(dir, 0700)
49 s := &toolServer{path: filepath.Join(dir, "equipo.sock")}
50 ln, err := net.Listen("unix", s.path)
51 if err != nil {
52 t.Fatal(err)
53 }
54 os.Chmod(s.path, 0600)
55 t.Cleanup(func() { ln.Close() })
56 go func() {
57 for {
58 c, err := ln.Accept()
59 if err != nil {
60 return
61 }
62 go s.serve(c, tools)
63 }
64 }()
65 return s
66}
67
68func (s *toolServer) serve(c net.Conn, tools []string) {
69 defer c.Close()
70 r := bufio.NewReader(c)
71 for {
72 line, err := r.ReadBytes('\n')
73 if err != nil {
74 return
75 }
76 var q struct {
77 ID json.RawMessage `json:"id"`
78 Method string `json:"method"`
79 Params struct {
80 Name string `json:"name"`
81 Arguments json.RawMessage `json:"arguments"`
82 } `json:"params"`
83 }
84 if json.Unmarshal(line, &q) != nil || len(q.ID) == 0 {
85 continue
86 }
87 var result any
88 switch q.Method {
89 case "initialize":
90 result = map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{"tools": map[string]any{}}, "serverInfo": map[string]any{"name": "equipo", "version": "1"}}
91 case "tools/list":
92 var list []any
93 // Besides the role's tools, one no role pins: Pi must not
94 // declare or call it.
95 for _, name := range append(slices.Clone(tools), "merge_now") {
96 list = append(list, map[string]any{"name": name, "description": "Equipo's " + name, "inputSchema": map[string]any{"type": "object"}})
97 }
98 result = map[string]any{"tools": list}
99 case "tools/call":
100 s.mu.Lock()
101 s.calls = append(s.calls, q.Params.Name+" "+string(q.Params.Arguments))
102 s.mu.Unlock()
103 result = map[string]any{"content": []any{map[string]any{"type": "text", "text": "Recorded."}}}
104 default:
105 raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": q.ID, "error": map[string]any{"code": -32601, "message": "no"}})
106 c.Write(append(raw, '\n'))
107 continue
108 }
109 raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": q.ID, "result": result})
110 c.Write(append(raw, '\n'))
111 }
112}
113
114// harness runs Pi (the real pinned one, or fakepi) in the real
115// containment: bubblewrap, the egress relay to api.tensorx.ai only, the
116// key through the secret pipe.
117type harness struct {
118 t *testing.T
119 manager *containment.Manager
120 scratch string
121 install Install
122 proxy string
123 keyHome string
124 tensorx *fakepi.TensorX
125 goRoot, moduleCache string
126}
127
128func copyTestBinary(t *testing.T, dir, name string) string {
129 t.Helper()
130 self, err := os.Executable()
131 if err != nil {
132 t.Fatal(err)
133 }
134 raw, err := os.ReadFile(self)
135 if err != nil {
136 t.Fatal(err)
137 }
138 p := filepath.Join(dir, name)
139 if err := os.WriteFile(p, raw, 0755); err != nil {
140 t.Fatal(err)
141 }
142 return p
143}
144
145// realInstall is the pinned Pi this machine has (EQUIPO_PI_ROOT, laid out
146// as Paths says), or a skip, or on CI a failure.
147func realInstall(t *testing.T) Install {
148 t.Helper()
149 root := os.Getenv("EQUIPO_PI_ROOT")
150 if root == "" {
151 testci.Absent(t, "the pinned Pi (EQUIPO_PI_ROOT) is absent")
152 }
153 testci.Tools(t, "pi")
154 node, tree := Paths(root)
155 inst, ok := Install{Node: node, Tree: tree}.Pinned()
156 if !ok {
157 t.Skip("no Pi pins for this platform")
158 }
159 return inst
160}
161
162// fakeInstall is fakepi as the Pi CLI, run by a copy of this binary as
163// Node, with its digests as the pins.
164func fakeInstall(t *testing.T) Install {
165 t.Helper()
166 dir := t.TempDir()
167 node := copyTestBinary(t, dir, "node")
168 tree := filepath.Join(dir, "pi", "node_modules")
169 cli := filepath.Join(tree, "@earendil-works/pi-coding-agent/dist/bundle/cli.js")
170 if err := os.MkdirAll(filepath.Dir(cli), 0755); err != nil {
171 t.Fatal(err)
172 }
173 if err := os.WriteFile(cli, []byte("// fakepi stands in for Pi\n"), 0644); err != nil {
174 t.Fatal(err)
175 }
176 if err := Seal(tree); err != nil {
177 t.Fatal(err)
178 }
179 t.Cleanup(func() {
180 filepath.Walk(tree, func(p string, info os.FileInfo, err error) error {
181 if err == nil && info.IsDir() {
182 os.Chmod(p, 0755)
183 }
184 return nil
185 })
186 })
187 sum, err := TreeSHA256(tree)
188 if err != nil {
189 t.Fatal(err)
190 }
191 raw, _ := os.ReadFile(node)
192 return Install{Node: node, Tree: tree, NodeSHA256: digest(raw), TreeSHA256: sum}
193}
194
195func newHarness(t *testing.T, inst Install) *harness {
196 t.Helper()
197 testci.Tools(t, "bwrap")
198 if _, err := os.Stat("/usr/bin/bwrap"); err != nil {
199 testci.Absent(t, "bubblewrap is absent")
200 }
201 root := t.TempDir()
202 scratch := filepath.Join(root, "s")
203 if err := os.Mkdir(scratch, 0700); err != nil {
204 t.Fatal(err)
205 }
206 self, err := os.Executable()
207 if err != nil {
208 t.Fatal(err)
209 }
210 m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: scratch})
211 if err != nil {
212 testci.Absent(t, fmt.Sprintf("namespaces are unavailable here: %v", err))
213 }
214 bin := filepath.Join(root, "bin")
215 os.Mkdir(bin, 0755)
216 keyHome := filepath.Join(root, "tensorx-abcdef012345")
217 if err := os.Mkdir(keyHome, 0700); err != nil {
218 t.Fatal(err)
219 }
220 if err := os.WriteFile(filepath.Join(keyHome, provider.TokenFile), []byte(testKey), 0600); err != nil {
221 t.Fatal(err)
222 }
223 h := &harness{t: t, manager: m, scratch: scratch, install: inst, proxy: copyTestBinary(t, bin, "equipo-tool-proxy"), keyHome: keyHome}
224 h.tensorx = fakepi.StartTensorX(t)
225 return h
226}
227
228// run is one launch: Pi opened on the workspace for action, with the
229// step tools equipo served on its tool socket.
230type run struct {
231 launcher *Launcher
232 session provider.Session
233 process provider.Process
234 tools *toolServer
235 home string
236 events <-chan provider.Event
237 cleanup func()
238 kill context.CancelFunc
239 host *teeHost
240}
241
242// errors is what Pi wrote on stderr so far.
243func (r *run) errors() string {
244 time.Sleep(100 * time.Millisecond)
245 return r.host.stderr()
246}
247
248// teeHost keeps what the process writes on stderr.
249type teeHost struct {
250 host provider.ProcessHost
251 mu sync.Mutex
252 buf []byte
253}
254
255func (h *teeHost) stderr() string {
256 h.mu.Lock()
257 defer h.mu.Unlock()
258 return string(h.buf)
259}
260
261func (h *teeHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) {
262 p, err := h.host.Start(ctx, l, argv)
263 if err == nil {
264 go func() {
265 b := make([]byte, 4096)
266 for {
267 n, err := p.Stderr().Read(b)
268 h.mu.Lock()
269 if len(h.buf) < 1<<20 {
270 h.buf = append(h.buf, b[:n]...)
271 }
272 h.mu.Unlock()
273 if err != nil {
274 return
275 }
276 }
277 }()
278 }
279 return p, err
280}
281
282func contextTimeout(d time.Duration) (context.Context, context.CancelFunc) {
283 return context.WithTimeout(context.Background(), d)
284}
285
286// openKept resumes session id from the transcript kept in dir.
287func (h *harness) openKept(work, action string, equipo []string, id, dir string) *run {
288 return h.openWith(work, action, equipo, id, dir)
289}
290
291func (h *harness) open(work, action string, equipo []string, session string) *run {
292 return h.openWith(work, action, equipo, session, "")
293}
294
295func (h *harness) openWith(work, action string, equipo []string, session, kept string) *run {
296 t := h.t
297 t.Helper()
298 scratch, err := os.MkdirTemp(h.scratch, "policy-")
299 if err != nil {
300 t.Fatal(err)
301 }
302 if session == "" {
303 session = NewSessionID()
304 }
305 in, cleanup, err := Prepare(h.scratch, Run{GoRoot: h.goRoot, ModuleCache: h.moduleCache, Install: h.install, Bwrap: "/usr/bin/bwrap", ToolProxy: h.proxy, Scratch: scratch, Workspace: work, Action: action, Provider: "tensorx", Model: "z-ai/glm-5.3", Equipo: equipo, Resume: session, EgressHosts: egressHosts(t), ExtraCA: h.tensorx.CA})
306 if err != nil {
307 t.Fatal(err)
308 }
309 if kept != "" {
310 if err := RestoreSession(kept, session, in.Home); err != nil {
311 t.Fatal(err)
312 }
313 }
314 policy, err := provider.BuildPiPolicy(in)
315 if err != nil {
316 t.Fatal(err)
317 }
318 tools := startToolServer(t, h.scratch, equipo)
319 host := &teeHost{host: h.manager}
320 l, _ := New(host)
321 launch := provider.Launch{ToolSocket: tools.path, AttemptKey: "test/" + NewSessionID(), Workspace: work, Selection: provider.Selection{ConnectionID: "tensorx-abcdef012345", Provider: "tensorx", Model: "z-ai/glm-5.3", Family: Family("z-ai/glm-5.3")}, Binding: provider.PiBinding("tensorx-abcdef012345", in.Home, h.keyHome), Policy: policy}
322 // The context Open gets is the attempt's lifetime: cancelling it
323 // kills the namespace.
324 ctx, kill := context.WithCancel(context.Background())
325 sess, err := l.Open(ctx, launch)
326 if err != nil {
327 kill()
328 cleanup()
329 time.Sleep(200 * time.Millisecond)
330 t.Fatalf("open: %v\n%s", err, host.stderr())
331 }
332 proc, _ := l.Process(sess)
333 events, _ := l.Events(context.Background(), sess)
334 r := &run{launcher: l, session: sess, process: proc, tools: tools, home: in.Home, events: events}
335 r.host = host
336 r.kill = kill
337 r.cleanup = func() {
338 r.stop(t)
339 kill()
340 cleanup()
341 os.RemoveAll(scratch)
342 }
343 t.Cleanup(r.cleanup)
344 return r
345}
346
347func egressHosts(t *testing.T) []string {
348 p, err := egress.ProviderPolicy(provider.NetworkContract{Provider: "tensorx", Harness: "pi"}, false)
349 if err != nil {
350 t.Fatal(err)
351 }
352 return p.Hosts
353}
354
355// prompt sends one prompt and collects its events to its end, answering
356// every ask with answer.
357func (r *run) prompt(t *testing.T, text, answer string) []provider.Event {
358 t.Helper()
359 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
360 defer cancel()
361 if err := r.launcher.StartTurn(ctx, r.session, provider.Turn{ID: NewSessionID(), Prompt: text}); err != nil {
362 t.Fatalf("prompt: %v\n%s", err, r.errors())
363 }
364 var out []provider.Event
365 for {
366 select {
367 case <-ctx.Done():
368 t.Fatalf("no end; events %v", kinds(out))
369 case e, ok := <-r.events:
370 if !ok {
371 t.Fatalf("Pi ended; events %v\n%s", kinds(out), r.errors())
372 }
373 out = append(out, e)
374 if e.Kind == KindAsk {
375 if err := r.launcher.Respond(ctx, r.session, provider.Answer{RequestID: e.RequestID, Behavior: answer}); err != nil {
376 t.Fatal(err)
377 }
378 }
379 if e.Kind == KindDone {
380 return out
381 }
382 }
383 }
384}
385
386// stop closes Pi's stdin, kills the namespace and waits for its proof.
387func (r *run) stop(t *testing.T) error {
388 if r.process == nil {
389 return nil
390 }
391 r.launcher.Close(context.Background(), r.session)
392 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
393 defer cancel()
394 if c, ok := r.process.(interface{ Contain(context.Context) error }); ok {
395 c.Contain(ctx)
396 }
397 _, err := r.process.Wait(ctx)
398 r.process = nil
399 return err
400}
401
402func digest(raw []byte) string {
403 sum := sha256.Sum256(raw)
404 return hex.EncodeToString(sum[:])
405}
406