| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "net" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/coordinator" |
| 16 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 17 | "amadan.net/oficina/equipo/internal/runner/provider/codex" |
| 18 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 19 | ) |
| 20 | |
| 21 | type CoordinatorToolBinding struct { |
| 22 | Claim runnerproto.CoordinatorClaim |
| 23 | Session provider.Session |
| 24 | Journal *Journal |
| 25 | Current func(context.Context) error |
| 26 | Call func(context.Context, runnerproto.CoordinatorToolCall) (runnerproto.CoordinatorToolResult, error) |
| 27 | } |
| 28 | type coordinatorBroker struct { |
| 29 | mu sync.Mutex |
| 30 | binding CoordinatorToolBinding |
| 31 | invalid bool |
| 32 | deadline time.Time |
| 33 | } |
| 34 | |
| 35 | func OpenCoordinatorToolProxy(ctx context.Context, b CoordinatorToolBinding) (*ToolProxy, error) { |
| 36 | c := b.Claim |
| 37 | if b.Journal == nil || b.Current == nil || b.Call == nil || c.Binding.ID == "" || c.Binding.Generation < 1 || c.Turn.ID == "" || c.Turn.Generation != c.Binding.Generation || c.Scope.Account == "" || c.Handle.Attempt <= 0 || c.Handle.Fence <= 0 || c.Brief.Target.Repository != "" || c.Brief.Selection.Isolation.Status != "confined" || !time.Now().Before(c.LeaseDeadline) || !time.Now().Before(c.AttemptDeadline) { |
| 38 | return nil, runnerproto.ErrInvalid |
| 39 | } |
| 40 | if err := b.Current(ctx); err != nil { |
| 41 | return nil, err |
| 42 | } |
| 43 | root := filepath.Dir(b.Journal.path) |
| 44 | parent, err := openPrivateDir(root) |
| 45 | if err != nil { |
| 46 | return nil, err |
| 47 | } |
| 48 | parent.Close() |
| 49 | dir, err := os.MkdirTemp(root, "coordinator-tool-") |
| 50 | if err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | ok := false |
| 54 | defer func() { |
| 55 | if !ok { |
| 56 | os.Remove(filepath.Join(dir, "equipo.sock")) |
| 57 | os.Remove(dir) |
| 58 | } |
| 59 | }() |
| 60 | fd, err := openPrivateDir(dir) |
| 61 | if err != nil { |
| 62 | return nil, err |
| 63 | } |
| 64 | defer fd.Close() |
| 65 | path := filepath.Join(dir, "equipo.sock") |
| 66 | listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: fmt.Sprintf("/proc/self/fd/%d/equipo.sock", fd.Fd()), Net: "unix"}) |
| 67 | if err != nil { |
| 68 | return nil, err |
| 69 | } |
| 70 | listener.SetUnlinkOnClose(false) |
| 71 | if err = os.Chmod(path, 0600); err != nil { |
| 72 | listener.Close() |
| 73 | return nil, err |
| 74 | } |
| 75 | ctx, cancel := context.WithCancel(ctx) |
| 76 | p := &ToolProxy{SocketPath: path, listener: listener, ctx: ctx, cancel: cancel, directory: dir, coordinator: &coordinatorBroker{binding: b, deadline: c.LeaseDeadline}} |
| 77 | p.workers.Add(1) |
| 78 | go p.accept() |
| 79 | context.AfterFunc(ctx, func() { _ = p.Close() }) |
| 80 | p.workers.Add(1) |
| 81 | go func() { |
| 82 | defer p.workers.Done() |
| 83 | tick := time.NewTicker(100 * time.Millisecond) |
| 84 | defer tick.Stop() |
| 85 | for { |
| 86 | select { |
| 87 | case <-ctx.Done(): |
| 88 | return |
| 89 | case <-tick.C: |
| 90 | if err := p.coordinator.check(ctx, false, false); err != nil { |
| 91 | cancel() |
| 92 | return |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | }() |
| 97 | ok = true |
| 98 | return p, nil |
| 99 | } |
| 100 | func (b *coordinatorBroker) current(ctx context.Context, dispatched bool) error { |
| 101 | return b.check(ctx, dispatched, true) |
| 102 | } |
| 103 | |
| 104 | // The local watchdog checks deadlines without renewing remote authority. Actual |
| 105 | // tool use rechecks authority, and the service renews at the lease cadence. |
| 106 | func (b *coordinatorBroker) check(ctx context.Context, dispatched, remote bool) error { |
| 107 | b.mu.Lock() |
| 108 | v, invalid, deadline := b.binding, b.invalid, b.deadline |
| 109 | b.mu.Unlock() |
| 110 | if invalid || ctx.Err() != nil || !time.Now().Before(deadline) || !time.Now().Before(v.Claim.AttemptDeadline) { |
| 111 | return runnerproto.ErrInvalid |
| 112 | } |
| 113 | if remote { |
| 114 | if err := v.Current(ctx); err != nil { |
| 115 | b.mu.Lock() |
| 116 | b.invalid = true |
| 117 | b.mu.Unlock() |
| 118 | return err |
| 119 | } |
| 120 | } |
| 121 | if v.Session.ID != "" { |
| 122 | if v.Session.Provider != v.Claim.Brief.Selection.Provider || v.Session.AccountID != v.Claim.Brief.Selection.AccountID || v.Session.Model != v.Claim.Brief.Selection.Model { |
| 123 | return runnerproto.ErrInvalid |
| 124 | } |
| 125 | if dispatched { |
| 126 | if err := v.Journal.currentDirectTurn(ctx, v.Session, v.Claim.Turn.ID); err != nil { |
| 127 | return err |
| 128 | } |
| 129 | } |
| 130 | } else if dispatched { |
| 131 | return runnerproto.ErrInvalid |
| 132 | } |
| 133 | return v.Journal.AdmissionAllowed(ctx) |
| 134 | } |
| 135 | func (p *ToolProxy) bindCoordinator(session provider.Session, turn string) error { |
| 136 | b := p.coordinator |
| 137 | if err := b.current(p.ctx, false); err != nil { |
| 138 | return err |
| 139 | } |
| 140 | b.mu.Lock() |
| 141 | defer b.mu.Unlock() |
| 142 | if turn != b.binding.Claim.Turn.ID || session.ID == "" || session.AttemptKey == "" || session.Provider != b.binding.Claim.Brief.Selection.Provider || session.AccountID != b.binding.Claim.Brief.Selection.AccountID || session.Model != b.binding.Claim.Brief.Selection.Model || (b.binding.Session.ID != "" && b.binding.Session != session) { |
| 143 | return runnerproto.ErrInvalid |
| 144 | } |
| 145 | var saved string |
| 146 | var recovered int |
| 147 | if err := b.binding.Journal.db.QueryRowContext(p.ctx, "SELECT session,recovered FROM direct_attempts WHERE attempt=?", session.AttemptKey).Scan(&saved, &recovered); err != nil || saved != session.ID || recovered != 0 { |
| 148 | return runnerproto.ErrInvalid |
| 149 | } |
| 150 | b.binding.Session = session |
| 151 | return nil |
| 152 | } |
| 153 | func (p *ToolProxy) ValidateCoordinatorApproval(ctx context.Context, call runnerproto.CoordinatorToolCall) error { |
| 154 | b := p.coordinator |
| 155 | if b == nil { |
| 156 | return runnerproto.ErrInvalid |
| 157 | } |
| 158 | if err := b.current(ctx, true); err != nil { |
| 159 | return err |
| 160 | } |
| 161 | b.mu.Lock() |
| 162 | v := b.binding |
| 163 | b.mu.Unlock() |
| 164 | return v.Journal.reserveCoordinatorTool(ctx, v.Claim, v.Session, call) |
| 165 | } |
| 166 | func (p *ToolProxy) CallCoordinatorTool(ctx context.Context, call runnerproto.CoordinatorToolCall) (runnerproto.CoordinatorToolResult, error) { |
| 167 | var zero runnerproto.CoordinatorToolResult |
| 168 | if err := p.ValidateCoordinatorApproval(ctx, call); err != nil { |
| 169 | return zero, err |
| 170 | } |
| 171 | b := p.coordinator |
| 172 | b.mu.Lock() |
| 173 | v := b.binding |
| 174 | b.mu.Unlock() |
| 175 | if err := v.Journal.submitCoordinatorTool(ctx, v.Claim, v.Session, call); err != nil { |
| 176 | return zero, err |
| 177 | } |
| 178 | // Always revisit instance authority, including acknowledged local replays. |
| 179 | out, err := v.Call(ctx, call) |
| 180 | if err != nil { |
| 181 | return zero, err |
| 182 | } |
| 183 | if err = b.current(ctx, true); err != nil { |
| 184 | return zero, err |
| 185 | } |
| 186 | if err = v.Journal.ackCoordinatorTool(ctx, v.Claim, v.Session, call, out); err != nil { |
| 187 | return zero, err |
| 188 | } |
| 189 | return out, nil |
| 190 | } |
| 191 | func coordinatorMCPCall(name string, raw json.RawMessage) (runnerproto.CoordinatorToolCall, error) { |
| 192 | var fields map[string]json.RawMessage |
| 193 | if runnerproto.DecodeLimit(bytes.NewReader(raw), &fields, maxToolFrame) != nil { |
| 194 | return runnerproto.CoordinatorToolCall{}, runnerproto.ErrInvalid |
| 195 | } |
| 196 | var id string |
| 197 | if json.Unmarshal(fields["request_id"], &id) != nil { |
| 198 | return runnerproto.CoordinatorToolCall{}, runnerproto.ErrInvalid |
| 199 | } |
| 200 | delete(fields, "request_id") |
| 201 | args, err := json.Marshal(fields) |
| 202 | call := runnerproto.CoordinatorToolCall{RequestID: id, Name: name, Arguments: args} |
| 203 | if err != nil { |
| 204 | return call, err |
| 205 | } |
| 206 | return coordinator.Canonical(call) |
| 207 | } |
| 208 | func (p *ToolProxy) coordinatorPermission(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) { |
| 209 | var q struct { |
| 210 | Tool string `json:"tool_name"` |
| 211 | UseID string `json:"tool_use_id,omitempty"` |
| 212 | Input json.RawMessage `json:"input"` |
| 213 | } |
| 214 | if runnerproto.DecodeLimit(bytes.NewReader(raw), &q, maxToolFrame) != nil || !strings.HasPrefix(q.Tool, "mcp__equipo__") { |
| 215 | return nil, runnerproto.ErrInvalid |
| 216 | } |
| 217 | call, err := coordinatorMCPCall(strings.TrimPrefix(q.Tool, "mcp__equipo__"), q.Input) |
| 218 | if err != nil { |
| 219 | return nil, err |
| 220 | } |
| 221 | if err = p.ValidateCoordinatorApproval(ctx, call); err != nil { |
| 222 | return nil, err |
| 223 | } |
| 224 | return json.RawMessage(`{"behavior":"allow"}`), nil |
| 225 | } |
| 226 | |
| 227 | // ApproveCoordinator binds Codex's captured MCP request to the same durable hash |
| 228 | // as execution. Native and uncorrelated requests are always denied. |
| 229 | func (p *ToolProxy) ApproveCoordinator(ctx context.Context, l provider.Launcher, ev provider.Event) error { |
| 230 | if p.coordinator == nil || l == nil { |
| 231 | return runnerproto.ErrInvalid |
| 232 | } |
| 233 | p.coordinator.mu.Lock() |
| 234 | b := p.coordinator.binding |
| 235 | p.coordinator.mu.Unlock() |
| 236 | authorize := func(ctx context.Context, original provider.Event) error { |
| 237 | if original.SessionID != b.Session.ID || original.TurnID != b.Claim.Turn.ID || original.RequestID != ev.RequestID || !bytes.Equal(original.Payload, ev.Payload) || !bytes.Equal(original.ToolCall, ev.ToolCall) { |
| 238 | return runnerproto.ErrInvalid |
| 239 | } |
| 240 | name, raw, err := codex.MCPApproval(original) |
| 241 | if err != nil { |
| 242 | return err |
| 243 | } |
| 244 | call, err := coordinatorMCPCall(name, raw) |
| 245 | if err != nil { |
| 246 | return err |
| 247 | } |
| 248 | return p.ValidateCoordinatorApproval(ctx, call) |
| 249 | } |
| 250 | behavior := "allow" |
| 251 | if err := authorize(ctx, ev); err != nil { |
| 252 | behavior = "deny" |
| 253 | } |
| 254 | return l.Respond(ctx, b.Session, provider.Answer{RequestID: ev.RequestID, TurnID: b.Claim.Turn.ID, Behavior: behavior, Authorize: authorize}) |
| 255 | } |
| 256 | func (p *ToolProxy) serveCoordinator(conn net.Conn) { |
| 257 | b := p.coordinator |
| 258 | b.mu.Lock() |
| 259 | claim := b.binding.Claim |
| 260 | b.mu.Unlock() |
| 261 | copy := ToolCopy{Accepted: claim.ToolCopy.Accepted, Rejected: claim.ToolCopy.Rejected, Coordinator: claim.ToolCopy.Descriptions} |
| 262 | cap := toolCapability{Coordinator: true, Copy: copy, Tools: coordinator.Names()} |
| 263 | var permission func(context.Context, json.RawMessage) (json.RawMessage, error) |
| 264 | if claim.Brief.Selection.Provider == "claude" { |
| 265 | permission = p.coordinatorPermission |
| 266 | } |
| 267 | _ = serveTools(p.ctx, &proxyReader{conn: conn}, conn, func() (toolCapability, error) { return cap, b.current(p.ctx, false) }, func(q toolRequest) (any, error) { |
| 268 | out, err := p.CallCoordinatorTool(p.ctx, runnerproto.CoordinatorToolCall{RequestID: q.RequestID, Name: q.Name, Arguments: q.Arguments}) |
| 269 | if err != nil { |
| 270 | return nil, err |
| 271 | } |
| 272 | raw, err := json.Marshal(out) |
| 273 | return map[string]any{"content": []any{map[string]string{"type": "text", "text": string(raw)}}}, err |
| 274 | }, permission) |
| 275 | } |
| 276 | |