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 "context"
5 "encoding/json"
6 "errors"
7 "maps"
8 "slices"
9 "sync"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/runner/provider"
13)
14
15// Launcher runs Pi in RPC mode in a namespace the ProcessHost owns
16// (provider.Launcher). One process is one session; a run is one prompt
17// and its events to the end. Ending a run is the namespace's work, never
18// Pi's (rev 3 §5): Interrupt asks Pi to abort, and the caller kills the
19// namespace and waits for its proof.
20type Launcher struct {
21 host provider.ProcessHost
22
23 mu sync.Mutex
24 sessions map[string]*session
25}
26
27var _ provider.Launcher = (*Launcher)(nil)
28
29type session struct {
30 launch provider.Launch
31 process provider.Process
32 client *Client
33 decoder *Decoder
34 events chan provider.Event
35 turn string
36
37 mu sync.Mutex
38 asks map[string]bool
39}
40
41// New is a launcher on host.
42func New(host provider.ProcessHost) (*Launcher, error) {
43 if host == nil {
44 return nil, provider.ErrPolicy
45 }
46 return &Launcher{host: host, sessions: map[string]*session{}}, nil
47}
48
49// Preflight checks the policy is a Pi one for this binding; the key and
50// the pins are checked again at the launch's attestation.
51func (l *Launcher) Preflight(_ context.Context, b provider.Binding, p provider.Policy) (provider.Identity, error) {
52 if !p.IsPi() || p.KeyEnv() == "" || !b.Token {
53 return provider.Identity{}, provider.ErrPolicy
54 }
55 return provider.Identity{AccountID: b.ID, ProviderVersion: Version}, nil
56}
57
58// Open starts Pi and reads its state: the provider, model and session
59// it runs must be the launch's. ctx is the attempt's lifetime: the
60// ProcessHost kills the namespace when it is cancelled.
61func (l *Launcher) Open(ctx context.Context, launch provider.Launch) (provider.Session, error) {
62 return l.OpenWithin(ctx, ctx, launch)
63}
64
65// OpenWithin is Open with the start bounded apart from the attempt's
66// lifetime: lifetime owns the namespace, startup bounds the wait for
67// Pi's state (a step's cancellation and deadline reach it).
68func (l *Launcher) OpenWithin(lifetime, startup context.Context, launch provider.Launch) (provider.Session, error) {
69 argv := launch.Policy.PiArgv()
70 if argv == nil {
71 return provider.Session{}, provider.ErrPolicy
72 }
73 return l.openWith(lifetime, startup, launch, argv)
74}
75
76func (l *Launcher) openWith(ctx, startup context.Context, launch provider.Launch, argv []string) (provider.Session, error) {
77 proc, err := l.host.Start(ctx, launch, argv)
78 if err != nil {
79 return provider.Session{}, err
80 }
81 s := &session{launch: launch, process: proc, client: NewClient(proc.Stdout(), proc.Stdin()), decoder: &Decoder{}, events: make(chan provider.Event, 64), asks: map[string]bool{}}
82 sctx, cancel := context.WithTimeout(startup, 60*time.Second)
83 defer cancel()
84 r, err := s.client.Call(sctx, map[string]any{"type": "get_state"})
85 var state struct {
86 SessionID string `json:"sessionId"`
87 Model struct {
88 ID, Provider string
89 } `json:"model"`
90 }
91 if err == nil && json.Unmarshal(r.Data, &state) != nil {
92 err = provider.ErrPolicy
93 }
94 if err == nil && (state.Model.ID != launch.Selection.Model || state.Model.Provider != launch.Selection.Provider || state.SessionID == "" || launch.ResumeSessionID != "" && state.SessionID != launch.ResumeSessionID) {
95 err = provider.ErrIdentity
96 }
97 if err != nil {
98 proc.Stdin().Close()
99 return provider.Session{}, err
100 }
101 sess := provider.Session{ID: state.SessionID, AttemptKey: launch.AttemptKey, Provider: launch.Selection.Provider, AccountID: launch.Selection.AccountID, Model: launch.Selection.Model, Family: launch.Selection.Family}
102 go s.read(sess.ID)
103 l.mu.Lock()
104 l.sessions[sess.ID] = s
105 l.mu.Unlock()
106 return sess, nil
107}
108
109// read decodes Pi's records into the session's events until stdout ends.
110func (s *session) read(id string) {
111 defer close(s.events)
112 for line := range s.client.Records {
113 s.mu.Lock()
114 evs, err := s.decoder.Decode(line)
115 s.mu.Unlock()
116 s.client.Release(len(line))
117 if err != nil {
118 continue
119 }
120 for _, e := range evs {
121 e.SessionID = id
122 s.mu.Lock()
123 e.TurnID = s.turn
124 if e.Kind == KindAsk {
125 var a Ask
126 _ = json.Unmarshal(e.Payload, &a)
127 s.asks[a.ID] = true
128 e.RequestID = a.ID
129 }
130 s.mu.Unlock()
131 s.events <- e
132 }
133 }
134}
135
136func (l *Launcher) state(sess provider.Session) (*session, error) {
137 l.mu.Lock()
138 defer l.mu.Unlock()
139 s := l.sessions[sess.ID]
140 if s == nil {
141 return nil, provider.ErrIdentity
142 }
143 return s, nil
144}
145
146// Events are the session's decoded events, closed when Pi's stdout ends.
147func (l *Launcher) Events(_ context.Context, sess provider.Session) (<-chan provider.Event, error) {
148 s, err := l.state(sess)
149 if err != nil {
150 return nil, err
151 }
152 return s.events, nil
153}
154
155// StartTurn sends the prompt; Pi must start a run for it.
156func (l *Launcher) StartTurn(ctx context.Context, sess provider.Session, t provider.Turn) error {
157 s, err := l.state(sess)
158 if err != nil {
159 return err
160 }
161 s.mu.Lock()
162 s.turn = t.ID
163 s.mu.Unlock()
164 r, err := s.client.Call(ctx, map[string]any{"type": "prompt", "message": t.Prompt})
165 if err != nil {
166 return err
167 }
168 var d struct{ Disposition string }
169 if json.Unmarshal(r.Data, &d) != nil || d.Disposition != "started" {
170 return errors.New("pi: the prompt started no run")
171 }
172 return nil
173}
174
175// Respond answers the extension's question: Behavior "allow" lets the
176// call run; anything else blocks it.
177func (l *Launcher) Respond(ctx context.Context, sess provider.Session, a provider.Answer) error {
178 s, err := l.state(sess)
179 if err != nil {
180 return err
181 }
182 s.mu.Lock()
183 pending := s.asks[a.RequestID]
184 delete(s.asks, a.RequestID)
185 s.mu.Unlock()
186 if !pending {
187 return provider.ErrIdentity
188 }
189 return s.client.Send(ctx, map[string]any{"type": "extension_ui_response", "id": a.RequestID, "confirmed": a.Behavior == "allow"})
190}
191
192// Interrupt cancels any question Pi waits on (an abort does not end a
193// pending dialog), then aborts the run. It gives up when ctx ends: the
194// run's end is the namespace's kill, never Pi's answer.
195func (l *Launcher) Interrupt(ctx context.Context, sess provider.Session) error {
196 s, err := l.state(sess)
197 if err != nil {
198 return err
199 }
200 s.mu.Lock()
201 ids := make([]string, 0, len(s.asks))
202 for id := range s.asks {
203 ids = append(ids, id)
204 }
205 s.asks = map[string]bool{}
206 s.mu.Unlock()
207 slices.Sort(ids)
208 for _, id := range ids {
209 if err := s.client.Send(ctx, map[string]any{"type": "extension_ui_response", "id": id, "cancelled": true}); err != nil {
210 return err
211 }
212 }
213 _, err = s.client.Call(ctx, map[string]any{"type": "abort"})
214 return err
215}
216
217// Close closes Pi's stdin, its request for an orderly shutdown. The
218// namespace's end is the ProcessHost's.
219func (l *Launcher) Close(_ context.Context, sess provider.Session) error {
220 s, err := l.state(sess)
221 if err != nil {
222 return err
223 }
224 l.mu.Lock()
225 delete(l.sessions, sess.ID)
226 l.mu.Unlock()
227 return s.process.Stdin().Close()
228}
229
230// Process is the session's process (its namespace record and Wait).
231func (l *Launcher) Process(sess provider.Session) (provider.Process, error) {
232 s, err := l.state(sess)
233 if err != nil {
234 return nil, err
235 }
236 return s.process, nil
237}
238
239// Unknown is how many records of each unknown type the session dropped.
240func (l *Launcher) Unknown(sess provider.Session) map[string]int {
241 s, err := l.state(sess)
242 if err != nil {
243 return nil
244 }
245 s.mu.Lock()
246 defer s.mu.Unlock()
247 return maps.Clone(s.decoder.Unknown)
248}
249