oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package runner
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "os"
8 "path/filepath"
9 "strings"
10 "sync"
11 "testing"
12
13 "amadan.net/oficina/equipo/internal/runner/egress"
14 "amadan.net/oficina/equipo/internal/runner/provider"
15 "amadan.net/oficina/equipo/internal/runner/workspace"
16)
17
18type graphCLI struct {
19 j *Journal
20 host provider.ProcessHost
21 mu sync.Mutex
22 sessions map[string]*graphCLISession
23 proxies map[string]*ToolProxy
24}
25type graphCLISession struct {
26 session provider.Session
27 capture *provider.Capture
28 events chan provider.Event
29 turn string
30 mu sync.Mutex
31}
32
33func fakeDirectGraph(t *testing.T, j *Journal, host provider.ProcessHost, root, scratch, helper string, progressFrames int) (map[string]provider.Launcher, func(context.Context, RunClaim, workspace.Workspace, *ToolProxy) (provider.Launch, func() error, error)) {
34 f := &graphCLI{j: j, host: host, sessions: map[string]*graphCLISession{}, proxies: map[string]*ToolProxy{}}
35 binary := filepath.Join(root, "fake-cli")
36 script := strings.ReplaceAll(graphScript, "PROGRESS_FRAMES", fmt.Sprint(progressFrames))
37 wfMust(t, os.WriteFile(binary, []byte(script), 0700))
38 launch := func(ctx context.Context, c RunClaim, ws workspace.Workspace, proxy *ToolProxy) (provider.Launch, func() error, error) {
39 name := c.Assignment.Selection.Provider
40 home := filepath.Join(root, "fixture-account-"+c.Assignment.StepKey)
41 wfMust(t, os.Mkdir(home, 0700))
42 id := provider.Identity{AccountID: "account", HomeID: "fake-" + c.Assignment.StepKey, ProviderVersion: map[string]string{"claude": "2.1.312", "codex": "0.165.0"}[name]}
43 wfMust(t, os.WriteFile(filepath.Join(home, provider.IdentityFile), marshal(id), 0600))
44 credential := map[string]string{"claude": ".credentials.json", "codex": "auth.json"}[name]
45 wfMust(t, os.WriteFile(filepath.Join(home, credential), []byte(`{"fixture":true}`), 0600))
46 lease, err := provider.OpenAccount(ctx, provider.Binding{ID: "fake-binding", Home: home, Provider: name, AccountID: "account", Expected: id, RuntimeRoot: filepath.Join(scratch, "homes")})
47 if err != nil {
48 return provider.Launch{}, nil, err
49 }
50 err = lease.Preflight(ctx, func(context.Context, provider.Binding) (provider.Identity, error) { return id, nil })
51 if err != nil {
52 return provider.Launch{}, lease.Close, err
53 }
54 binding := lease.Binding()
55 network, err := egress.ProviderPolicy(provider.NetworkContract{Provider: name}, true)
56 if err != nil {
57 return provider.Launch{}, lease.Close, err
58 }
59 policyScratch, err := os.MkdirTemp(scratch, "policy-")
60 if err != nil {
61 return provider.Launch{}, lease.Close, err
62 }
63 policy, err := provider.BuildPolicy(binding, provider.PolicyInputs{Action: c.Brief.Step.Action, Workspace: ws.Path, Scratch: policyScratch, ProviderVersion: id.ProviderVersion, LauncherVersion: "fixture", BwrapVersion: "0.11.0", Argv: []string{"/opt/fake-cli", name}, RuntimeFiles: []provider.Mount{{Source: binary, Target: "/opt/fake-cli", ReadOnly: true}, {Source: helper, Target: "/opt/helper", ReadOnly: true}, {Source: "/usr/bin/bwrap", Target: "/opt/bwrap", ReadOnly: true}}, EgressHosts: network.Hosts})
64 if err != nil {
65 return provider.Launch{}, lease.Close, err
66 }
67 l := provider.Launch{AttemptKey: attemptKey(c.Scope, c.Handle) + "/model", Workspace: ws.Path, Selection: provider.Selection{Provider: name, AccountID: "account", Family: c.Assignment.Selection.Family, Model: "model", ConnectionID: c.Assignment.Selection.ConnectionID}, Binding: binding, Policy: policy}
68 f.proxies[l.AttemptKey] = proxy
69 return l, lease.Close, nil
70 }
71 return map[string]provider.Launcher{"claude": f, "codex": f}, launch
72}
73func (f *graphCLI) Preflight(context.Context, provider.Binding, provider.Policy) (provider.Identity, error) {
74 return provider.Identity{}, nil
75}
76func (f *graphCLI) Open(ctx context.Context, l provider.Launch) (provider.Session, error) {
77 p, err := f.host.Start(ctx, l, []string{"/opt/fake-cli", l.Selection.Provider})
78 if err != nil {
79 return provider.Session{}, err
80 }
81 c, err := NewCaptureFactory(f.j).Open(ctx, p, l)
82 if err != nil {
83 return provider.Session{}, err
84 }
85 session := provider.Session{ID: l.AttemptKey + "-session", AttemptKey: l.AttemptKey, Provider: l.Selection.Provider, AccountID: l.Selection.AccountID, Model: l.Selection.Model, Family: l.Selection.Family}
86 if err = f.j.BindSession(ctx, session); err != nil {
87 return session, err
88 }
89 s := &graphCLISession{session: session, capture: c, events: make(chan provider.Event, 64)}
90 f.mu.Lock()
91 f.sessions[l.AttemptKey] = s
92 f.mu.Unlock()
93 go func() {
94 defer close(s.events)
95 for frame := range c.Frames {
96 s.mu.Lock()
97 turn := s.turn
98 s.mu.Unlock()
99 var payload struct {
100 Tool string
101 Arguments json.RawMessage
102 Final bool
103 }
104 if json.Unmarshal(frame.Bytes, &payload) != nil {
105 return
106 }
107 kind := "timeline"
108 if payload.Tool != "" {
109 if err := f.proxies[l.AttemptKey].submit(ctx, payload.Tool, payload.Tool, payload.Arguments); err != nil {
110 s.events <- provider.Event{SessionID: session.ID, TurnID: turn, Kind: "turn.failed"}
111 return
112 }
113 }
114 if payload.Tool == "ask_person" {
115 proxy := f.proxies[l.AttemptKey]
116 proxy.broker.mu.Lock()
117 bound := proxy.broker.binding
118 proxy.broker.mu.Unlock()
119 if _, err := bound.Ask(ctx, bound, payload.Tool, payload.Arguments); err != nil {
120 s.events <- provider.Event{SessionID: session.ID, TurnID: turn, Kind: "turn.failed"}
121 return
122 }
123 }
124 if payload.Final {
125 kind = "turn.completed"
126 }
127 e := provider.Event{Sequence: frame.Sequence, SessionID: session.ID, TurnID: turn, Kind: kind, Payload: frame.Bytes}
128 select {
129 case s.events <- e:
130 case <-ctx.Done():
131 return
132 }
133 }
134 }()
135 return session, nil
136}
137func (f *graphCLI) Events(_ context.Context, s provider.Session) (<-chan provider.Event, error) {
138 return f.sessions[s.AttemptKey].events, nil
139}
140func (f *graphCLI) StartTurn(ctx context.Context, session provider.Session, t provider.Turn) error {
141 s := f.sessions[session.AttemptKey]
142 s.mu.Lock()
143 s.turn = t.ID
144 s.mu.Unlock()
145 if err := f.j.BeginTurn(ctx, session, t); err != nil {
146 return err
147 }
148 var raw []byte
149 if session.Provider == "claude" {
150 raw = marshal(map[string]any{"type": "user", "session_id": session.ID, "message": map[string]string{"role": "user", "content": t.Prompt}})
151 } else {
152 raw = marshal(map[string]any{"method": "turn/start", "params": map[string]any{"threadId": session.ID, "input": []any{map[string]string{"type": "text", "text": t.Prompt}}}})
153 }
154 _, err := s.capture.Input.Write(append(raw, '\n'))
155 return err
156}
157func (f *graphCLI) Respond(context.Context, provider.Session, provider.Answer) error {
158 return fmt.Errorf("unexpected answer")
159}
160func (f *graphCLI) Interrupt(context.Context, provider.Session) error { return nil }
161func (f *graphCLI) Close(_ context.Context, s provider.Session) error {
162 c := f.sessions[s.AttemptKey].capture
163 c.Input.Close()
164 return <-c.Done
165}
166
167const graphScript = `#!/usr/bin/python3
168import sys,json,subprocess,os,base64
169def git(*args):
170 env={'PATH':'/usr/bin:/bin','GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null','GIT_AUTHOR_NAME':'fixture','GIT_AUTHOR_EMAIL':'fixture@example.test','GIT_COMMITTER_NAME':'fixture','GIT_COMMITTER_EMAIL':'fixture@example.test'}
171 return subprocess.check_output(['git',*args],env=env,stderr=subprocess.DEVNULL).decode().strip()
172for line in sys.stdin:
173 v=json.loads(line)
174 message=json.loads(v['message']['content'] if sys.argv[1]=='claude' else v['params']['input'][0]['text'])
175 step=message.get('Action') or message['Step']
176 if step in ['reproduce','scope']:
177 print(json.dumps({'tool':'ask_person','arguments':{'question':'Which case?'}}),flush=True)
178 tool='submit_acceptance' if step=='scope' else 'submit_reproduction'
179 args={'expected_symptom':'wrong value','files':[{'path':'bug_test.go','bytes':base64.b64encode(b'package fixture\nimport "testing"\nfunc TestBug(t *testing.T){if Value()!=2 {t.Fatal("wrong value")}}\n').decode()}],'test_names':[{'package':'fixture','name':'TestBug'}]}
180 elif step=='recommend':
181 assert not os.path.exists('.git')
182 tool='submit_answer';args={'body':'recommendation','sources':[message['sources'][0]['ref']]}
183 elif step in ['implement','copy','design']:
184 if step=='implement': open('value.go','w').write('package fixture\nfunc Value() int {return 2}\n')
185 else: open(step+'.txt','w').write(step+' captured artifact')
186 git('add','.')
187 git('commit','-m','fix')
188 tool='submit_candidate';args={'commit':git('rev-parse','HEAD')}
189 else:
190 tool='submit_review';args={'candidate':message['candidate_commit'],'decision':'approve','findings':[]}
191 for i in range(PROGRESS_FRAMES): print(json.dumps({'progress':i}),flush=True)
192 print(json.dumps({'tool':tool,'arguments':args}),flush=True)
193 if tool=='submit_candidate' and message.get('render_available'): print(json.dumps({'tool':'submit_render','arguments':args}),flush=True)
194 print(json.dumps({'final':True,'usage':{'input_tokens':2,'output_tokens':3}}),flush=True)
195`
196