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 "amadan.net/oficina/equipo/internal/chatstream"
5 "context"
6 "database/sql"
7 "encoding/json"
8 "errors"
9 "path/filepath"
10 "sync/atomic"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/coordinator"
14 "amadan.net/oficina/equipo/internal/runner/provider"
15 "amadan.net/oficina/equipo/internal/runnerproto"
16)
17
18type CoordinatorAPI interface {
19 CoordinatorCall(context.Context, string, runnerproto.CoordinatorRequest, any) error
20}
21type CoordinatorService struct {
22 release func() error
23 retry map[string]coordinatorRetry
24 now func() time.Time
25 RecoverFiles func(context.Context, runnerproto.CoordinatorClaim) error
26 Journal *Journal
27 API CoordinatorAPI
28 Launchers map[string]provider.Launcher
29 OpenLaunch func(context.Context, runnerproto.CoordinatorClaim, *ToolProxy) (provider.Launch, func() error, error)
30 Contain func(context.Context, runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error)
31 NamespaceContext func(context.Context, runnerproto.CoordinatorClaim) context.Context
32}
33type coordinatorState struct {
34 Claim runnerproto.CoordinatorClaim
35 Session provider.Session
36 Finished bool
37 Refused bool
38 RefusalOperation string
39 RefusalStatus int
40 RefusalCode string
41 DeliveryRefusal *RefusalError
42 Containment *runnerproto.ContainmentProof
43}
44
45func (s *CoordinatorService) call(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error {
46 q.Version = 2
47 q.Capabilities = []string{runnerproto.CoordinatorCapability}
48 err := s.API.CoordinatorCall(ctx, op, q, out)
49 if err == nil || ctx.Err() != nil {
50 return err
51 }
52 var refusal *RefusalError
53 if errors.As(err, &refusal) && refusal.CoordinatorDefinitive() {
54 return refusal
55 }
56 // Remote contract/authentication failures cannot kill unrelated runner work.
57 return ErrTransient
58}
59func (s *CoordinatorService) Poll(ctx context.Context) error {
60 if s.Journal == nil || s.API == nil || s.OpenLaunch == nil || s.Contain == nil {
61 return provider.ErrContract
62 }
63 if err := s.Journal.AdmissionAllowed(ctx); err != nil {
64 return err
65 }
66 var turns []runnerproto.CoordinatorTurn
67 if err := s.call(ctx, "poll", runnerproto.CoordinatorRequest{}, &turns); err != nil {
68 return err
69 }
70 for _, turn := range turns {
71 if !s.retryDue(turn.ID) {
72 continue
73 }
74 var saved int
75 if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_supervisor WHERE kind IN ('coordinator','coordinator-claim') AND state_key=?", turn.ID).Scan(&saved); err != nil {
76 return err
77 }
78 if saved != 0 {
79 continue
80 }
81 q := runnerproto.CoordinatorRequest{TurnID: turn.ID, Revision: turn.Revision}
82 if err := s.Journal.saveState(ctx, "coordinator-claim", turn.ID, q); err != nil {
83 return err
84 }
85 var c runnerproto.CoordinatorClaim
86 if err := s.call(ctx, "claim", q, &c); err != nil {
87 r := coordinatorState{Claim: runnerproto.CoordinatorClaim{Turn: turn}}
88 if err = s.refusedCall(ctx, &r, "claim", err); err != nil {
89 return err
90 }
91 continue
92 }
93 if err := s.RunTurn(ctx, c); err != nil {
94 if errors.Is(err, ErrTransient) {
95 s.deferRetry(c.Turn.ID)
96 continue
97 }
98 return err
99 }
100 }
101 return nil
102}
103func (s *CoordinatorService) RunTurn(ctx context.Context, c runnerproto.CoordinatorClaim) (result error) {
104 state := coordinatorState{Claim: c}
105 // No saved turn, even one interrupted before stdin, can enter RunTurn again.
106 var count int
107 if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_supervisor WHERE kind='coordinator' AND state_key=?", c.Turn.ID).Scan(&count); err != nil {
108 return err
109 }
110 if count != 0 {
111 return provider.ErrUncertain
112 }
113 if _, err := runnerproto.CoordinatorPrompt(c.Context); err != nil {
114 return err
115 }
116 if err := s.Journal.saveState(ctx, "coordinator", c.Turn.ID, state); err != nil {
117 return err
118 }
119 var proxy *ToolProxy
120 var proxyRef atomic.Pointer[ToolProxy]
121 var release func() error
122 runCtx, cancel := context.WithCancel(ctx)
123 defer cancel()
124 if s.NamespaceContext != nil {
125 runCtx = s.NamespaceContext(runCtx, c)
126 }
127 // Cleanup proves all namespaces dead before releasing the account lease.
128 defer func() {
129 cleanup, stop := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
130 defer stop()
131 if proxy != nil {
132 result = errors.Join(result, proxy.Close())
133 }
134 proof, err := s.Contain(cleanup, c)
135 if err != nil {
136 result = errors.Join(result, err)
137 return
138 }
139 if state.Session.AttemptKey != "" {
140 if err = s.Journal.interruptDirect(cleanup, state.Session.AttemptKey, true); err != nil {
141 result = errors.Join(result, err)
142 return
143 }
144 }
145 if release != nil {
146 if err = release(); err != nil {
147 result = errors.Join(result, err)
148 return
149 }
150 s.release = nil
151 }
152 var deliveryErr error
153 if result == nil {
154 deliveryErr = s.finishDelivery(cleanup, state)
155 }
156 err = s.finishContained(cleanup, &state, proof, deliveryErr)
157 result = errors.Join(result, err)
158 }()
159 launcher := s.Launchers[c.Brief.Selection.Provider]
160 if launcher == nil {
161 return provider.ErrProvider
162 }
163 current := func(ctx context.Context) error {
164 var deadline time.Time
165 if err := s.call(ctx, "renew", runnerproto.NewCoordinatorRequest(c), &deadline); err != nil {
166 return err
167 }
168 if !time.Now().Before(deadline) || !time.Now().Before(c.AttemptDeadline) {
169 return provider.ErrUncertain
170 }
171 if currentProxy := proxyRef.Load(); currentProxy != nil {
172 currentProxy.coordinator.mu.Lock()
173 currentProxy.coordinator.deadline = deadline
174 currentProxy.coordinator.mu.Unlock()
175 }
176 return nil
177 }
178 if err := current(runCtx); err != nil {
179 return err
180 }
181 var err error
182 proxy, err = OpenCoordinatorToolProxy(runCtx, CoordinatorToolBinding{Claim: c, Journal: s.Journal, Current: current, Call: func(ctx context.Context, call runnerproto.CoordinatorToolCall) (runnerproto.CoordinatorToolResult, error) {
183 var out runnerproto.CoordinatorToolResult
184 q := runnerproto.NewCoordinatorRequest(c)
185 q.ToolCall = &call
186 err := s.call(ctx, "tool", q, &out)
187 return out, err
188 }})
189 if err != nil {
190 return err
191 }
192 proxyRef.Store(proxy)
193 // The short-lived admission is consumed before preflight's first provider
194 // process. A saved consumption can only be reconciled after a restart.
195 dir := filepath.Join(filepath.Dir(s.Journal.path), "coordinator-admissions")
196 request := runnerproto.RunnerRequest{Version: 2, AssignmentID: c.Turn.ID, RequestID: c.Turn.ID, Scope: c.Scope, Handle: c.Handle, ActionID: c.Admission.Dispatch.Action}
197 if err = runnerproto.JournalAdmission(dir, request); err != nil {
198 return err
199 }
200 if err = runnerproto.ConsumeTicket(dir, c.Turn.ID, c.Admission, time.Now().UTC(), c.Admission.Incarnation); err != nil {
201 return err
202 }
203 wrapped := &coordinatorLauncher{Launcher: launcher, open: func(session provider.Session) error {
204 state.Session = session
205 return s.Journal.saveState(runCtx, "coordinator", c.Turn.ID, state)
206 }, start: func(ctx context.Context, session provider.Session, turn provider.Turn) error {
207 if err := current(ctx); err != nil {
208 return err
209 }
210 return proxy.BindTurn(session, turn.ID)
211 }}
212 stream := chatstream.Forwarder{Send: func(ctx context.Context, text string, sequence int64) error {
213 e := chatstream.TextEvent(s.template(state), text, sequence)
214 if err := s.Journal.Append(ctx, e); err != nil {
215 return err
216 }
217 return s.flush(ctx, state)
218 }}
219 runtime, err := coordinator.New(coordinator.Config{Launcher: wrapped, Tools: coordinator.ToolFunc(proxy.CallCoordinatorTool), OpenLaunch: func(ctx context.Context, c runnerproto.CoordinatorClaim) (provider.Launch, error) {
220 var l provider.Launch
221 var err error
222 l, release, err = s.OpenLaunch(ctx, c, proxy)
223 s.release = release
224 return l, err
225 }, Record: func(ctx context.Context, e provider.Event) error {
226 if e.Kind == "session.bound" {
227 return s.emit(ctx, state, "session.bound", json.RawMessage(`{}`))
228 }
229 pump := EventPump{Journal: s.Journal, Contain: func(ctx context.Context) error { return launcher.Interrupt(ctx, state.Session) }}
230 if err := pump.AppendDirect(ctx, state.Session, e, s.template(state)); err != nil {
231 return err
232 }
233 if e.Kind == "message.delta" {
234 return stream.Add(ctx, e.Payload)
235 }
236 if e.Kind == "request" {
237 return proxy.ApproveCoordinator(ctx, launcher, e)
238 }
239 return nil
240 }})
241 if err != nil {
242 return err
243 }
244 // Revocation and lease renewal continue even while a provider emits no frames.
245 done := make(chan struct{})
246 go func() {
247 defer close(done)
248 tick := time.NewTicker(leaseRenewInterval)
249 defer tick.Stop()
250 for {
251 select {
252 case <-runCtx.Done():
253 return
254 case <-tick.C:
255 if current(runCtx) != nil {
256 cancel()
257 return
258 }
259 }
260 }
261 }()
262 defer func() { cancel(); <-done }()
263 result = runtime.RunTurn(runCtx, c)
264 if result == nil {
265 result = s.Journal.requireDirectCompletion(ctx, state.Session, c.Turn.ID)
266 }
267 return result
268}
269
270type coordinatorLauncher struct {
271 provider.Launcher
272 open func(provider.Session) error
273 start func(context.Context, provider.Session, provider.Turn) error
274}
275
276func (l *coordinatorLauncher) Open(ctx context.Context, v provider.Launch) (provider.Session, error) {
277 s, err := l.Launcher.Open(ctx, v)
278 if err == nil {
279 err = l.open(s)
280 }
281 if err != nil && s.ID != "" {
282 _ = l.Launcher.Close(context.WithoutCancel(ctx), s)
283 }
284 return s, err
285}
286func (l *coordinatorLauncher) StartTurn(ctx context.Context, s provider.Session, t provider.Turn) error {
287 if _, err := runnerproto.CoordinatorTurnIntentPayload(s.Provider, s.Model, t.Prompt); err != nil {
288 return err
289 }
290 if err := l.start(ctx, s, t); err != nil {
291 return err
292 }
293 return l.Launcher.StartTurn(ctx, s, t)
294}
295func (s *CoordinatorService) template(r coordinatorState) Event {
296 c := r.Claim
297 return Event{Version: 2, TaskID: c.Turn.ID, AssignmentID: c.Turn.ID, Scope: c.Scope, Handle: c.Handle, ServerID: "direct", AgentID: r.Session.AttemptKey, SessionID: r.Session.ID, TurnID: c.Turn.ID, ActionID: c.Admission.Dispatch.Action, SourceTime: time.Now().UTC(), Isolation: c.Brief.Selection.Isolation}
298}
299func (s *CoordinatorService) emit(ctx context.Context, r coordinatorState, kind string, payload json.RawMessage) error {
300 e := s.template(r)
301 e.Kind = kind
302 e.ID = runnerproto.EventHash([]string{r.Claim.Turn.ID, kind, r.Session.ID})
303 e.Payload = payload
304 var old []byte
305 err := s.Journal.db.QueryRowContext(ctx, "SELECT body FROM journal_events WHERE id=?", e.ID).Scan(&old)
306 if err == nil {
307 if json.Unmarshal(old, &e) != nil {
308 return ErrJournal
309 }
310 } else if !errors.Is(err, sql.ErrNoRows) {
311 return err
312 }
313 if err = s.Journal.Append(ctx, e); err != nil {
314 return err
315 }
316 return s.flush(ctx, r)
317}
318func (s *CoordinatorService) flush(ctx context.Context, r coordinatorState) error {
319 rows, err := s.Journal.db.QueryContext(ctx, "SELECT body FROM journal_events WHERE acked=0 AND json_extract(body,'$.assignment_id')=? ORDER BY rowid", r.Claim.Turn.ID)
320 if err != nil {
321 return err
322 }
323 var events []Event
324 for rows.Next() {
325 var raw []byte
326 var e Event
327 if err = rows.Scan(&raw); err != nil {
328 break
329 }
330 if err = json.Unmarshal(raw, &e); err != nil {
331 break
332 }
333 events = append(events, e)
334 }
335 rowErr := rows.Err()
336 rows.Close()
337 if err != nil {
338 return err
339 }
340 if rowErr != nil {
341 return rowErr
342 }
343 for _, e := range events {
344 switch e.Kind {
345 case "coordinator.text", "namespace.owner", "namespace.launch", "session.bound", "turn.completed", "turn.failed", "turn.uncertain", "coordinator.delivery":
346 q := runnerproto.NewCoordinatorRequest(r.Claim)
347 q.Event = &e
348 if err = s.call(ctx, "event", q, nil); err != nil {
349 return err
350 }
351 }
352 if err = s.Journal.Ack(ctx, e.ID); err != nil {
353 return err
354 }
355 }
356 return nil
357}
358func (s *CoordinatorService) finishDelivery(ctx context.Context, r coordinatorState) error {
359 if err := s.flush(ctx, r); err != nil {
360 return err
361 }
362 var delivered int
363 if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_events WHERE acked=1 AND json_extract(body,'$.assignment_id')=? AND json_extract(body,'$.kind')='coordinator.delivery'", r.Claim.Turn.ID).Scan(&delivered); err != nil {
364 return err
365 }
366 if delivered != 0 {
367 return nil
368 }
369 var raw, body []byte
370 err := s.Journal.db.QueryRowContext(ctx, `SELECT t.body,t.result FROM coordinator_tools t JOIN coordinator_tool_claims c ON c.claim_ref=json_extract(t.body,'$.claim_ref') WHERE c.turn_key=? AND t.acked=1 AND json_extract(t.result,'$.value.tool') IN ('propose_project','post_message','propose_plan','ask_person','route_to_task','suggest_preference','suggest_specialist','suggest_playbook') ORDER BY t.ordinal LIMIT 1`, coordinatorTurnKey(r.Claim, r.Session)).Scan(&body, &raw)
371 if err != nil {
372 if errors.Is(err, sql.ErrNoRows) {
373 return provider.ErrUncertain
374 }
375 return err
376 }
377 var record coordinatorToolRecord
378 var out runnerproto.CoordinatorToolResult
379 if json.Unmarshal(body, &record) != nil || json.Unmarshal(raw, &out) != nil {
380 return ErrJournal
381 }
382 return s.emit(ctx, r, "coordinator.delivery", marshal(map[string]string{"request_id": record.Call.RequestID, "resource_id": out.ResourceID}))
383}
384