thin: Pi steps and questions through the metered guard
Engineering and Review run on a metered connection through Pi (runPi): admitted, charged and settled by Meter.Run, the namespace recorded in the slot before it starts, the key refused marks the connection, a held step waits deferred. A question on a kept Pi session resumes it through S1's guard (askPi as MeteredAsk). connect.Choose takes the harness's capability (pi: Engineering and Review) and an explicit leave to spend, false in every release build until S3; metered comes after any subscription. Review's family is the model that ran. A real pinned Pi Review on a fake TensorX records other_family (the finish line), with fakepi covering budget, no usage, a refused key, Ask and Engineering.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
17 files changed,
+1,536
−234
internal/fakepi/fake.go+13 −2internal/fakepi/tensorx.go+194 −0internal/runner/config.go+9 −2internal/runner/connect/choose.go+43 −15internal/runner/connect/choose_test.go+38 −1internal/runner/provider/pi/harness_test.go+5 −165internal/runner/provider/pi/real_test.go+6 −6internal/runner/thin/conns.go+66 −4internal/runner/thin/contract_test.go+16 −1internal/runner/thin/engineer.go+35 −15internal/runner/thin/fixround_test.go+1 −1internal/runner/thin/judge.go+48 −20internal/runner/thin/pistep.go+528 −0internal/runner/thin/pistep_test.go+472 −0internal/runner/thin/run.go+22 −2internal/runner/thin/spend.go+25 −0internal/runner/thin/spend_testbuild.go+15 −0
diff --git a/internal/fakepi/fake.go b/internal/fakepi/fake.go| index 34aaa4be..30ebb556 100644 |
| --- a/internal/fakepi/fake.go |
| +++ b/internal/fakepi/fake.go |
| @@ -23,7 +23,8 @@ |
| // answers; "read:<path>" reads a file (asked when outside the |
| // confinement); "keyrefused" fails as a 401, "ratelimited" as a 429 after |
| // Pi's three retries, "nousage" ends with no message_end, "sleep:<ms>" |
| -// pauses mid-reply, "unknown-event" emits a record of a type Equipo does |
| +// pauses mid-reply, "answeredby:<model>" reports that model as the one |
| +// that answered, "unknown-event" emits a record of a type Equipo does |
| // not know. |
| package fakepi |
| @@ -51,6 +52,7 @@ var ( |
| reviewChanges = regexp.MustCompile(`review:changes:([^|\n]+)\|([0-9]+)\|([^\n;]*)`) |
| readWord = regexp.MustCompile(`read:(\S+)`) |
| sleepWord = regexp.MustCompile(`sleep:([0-9]+)`) |
| + answeredWord = regexp.MustCompile(`answeredby:(\S+)`) |
| ) |
| type fake struct { |
| @@ -69,6 +71,8 @@ type fake struct { |
| abortOnce sync.Once |
| running sync.Mutex |
| uiID int |
| + // answered is the model the provider says answered ("" the selected). |
| + answered string |
| } |
| type answer struct { |
| @@ -213,7 +217,11 @@ func (f *fake) record(role, text string) { |
| } |
| func (f *fake) assistant(stop string, usage bool, content []any, errorMessage string) map[string]any { |
| - m := map[string]any{"role": "assistant", "content": content, "api": "openai-completions", "provider": f.provider, "model": f.model, "stopReason": stop} |
| + model := f.model |
| + if f.answered != "" { |
| + model = f.answered |
| + } |
| + m := map[string]any{"role": "assistant", "content": content, "api": "openai-completions", "provider": f.provider, "model": model, "stopReason": stop} |
| u := map[string]any{"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "reasoning": 0, "totalTokens": 0, "cost": map[string]any{"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0, "totalFromProvider": false}} |
| if usage { |
| u["input"], u["output"], u["cacheRead"], u["totalTokens"] = 100, 10, 20, 130 |
| @@ -238,6 +246,9 @@ func (f *fake) stopped() bool { |
| func (f *fake) run(prompt string) { |
| f.running.Lock() |
| defer f.running.Unlock() |
| + if m := answeredWord.FindStringSubmatch(prompt); m != nil { |
| + f.answered = m[1] |
| + } |
| f.messages++ |
| f.record("user", prompt) |
| f.send(map[string]any{"type": "agent_start"}) |
diff --git a/internal/fakepi/tensorx.go b/internal/fakepi/tensorx.go| new file mode 100644 |
| index 00000000..9d5aa9e5 |
| --- /dev/null |
| +++ b/internal/fakepi/tensorx.go |
| @@ -0,0 +1,194 @@ |
| +package fakepi |
| + |
| +import ( |
| + "crypto/ecdsa" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "crypto/x509/pkix" |
| + "encoding/json" |
| + "encoding/pem" |
| + "fmt" |
| + "io" |
| + "math/big" |
| + "net" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// TestKey is the key tests deliver to a real Pi; TensorX refuses any |
| +// other with a 401. |
| +const TestKey = "tx-equipo-test-key-0123456789" |
| + |
| +// steps turns Equipo's step prompts into the calls a model would make: |
| +// a Review step submits an approval, an Engineering step its candidate. |
| +func steps(text string) string { |
| + switch { |
| + case strings.HasPrefix(text, "[Equipo: review]"): |
| + return `CALL mcp__equipo__submit_review {"verdict":"approve","headline":"Approved.","summary":"The change does what the task asks. (from TensorX)","findings":[]}` |
| + case strings.HasPrefix(text, "[Equipo: engineering]"): |
| + return `CALL mcp__equipo__submit_candidate {}` |
| + } |
| + return text |
| +} |
| + |
| +// TensorX is an OpenAI-compatible provider on 127.0.0.1, serving TLS |
| +// as api.tensorx.ai under a test authority. It answers a user message |
| +// "CALL <tool> <json>" with that tool call, a tool result with "done", |
| +// and anything else with "ok done", each with usage; it records what it |
| +// was sent. |
| +type TensorX struct { |
| + // Addr is where it listens; CA is its authority's certificate (PEM). |
| + Addr, CA string |
| + mu sync.Mutex |
| + requests []Request |
| +} |
| + |
| +type Request struct { |
| + Auth, Model string |
| + Tools []string |
| + System string |
| + Messages int |
| + // ToolText is the tool result the request answers, if any. |
| + ToolText string |
| +} |
| + |
| +// Seen is every request so far. |
| +func (f *TensorX) Seen() []Request { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return append([]Request(nil), f.requests...) |
| +} |
| + |
| +func StartTensorX(t testing.TB) *TensorX { |
| + t.Helper() |
| + caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + caTmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "equipo test authority"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign} |
| + caDER, err := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ca, _ := x509.ParseCertificate(caDER) |
| + key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + leaf := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "api.tensorx.ai"}, DNSNames: []string{"api.tensorx.ai"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| + leafDER, err := x509.CreateCertificate(rand.Reader, leaf, ca, &key.PublicKey, caKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + caFile := filepath.Join(t.TempDir(), "ca.pem") |
| + if err := os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + f := &TensorX{CA: caFile} |
| + srv := &http.Server{Handler: http.HandlerFunc(f.serve), TLSConfig: &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{leafDER}, PrivateKey: key}}}} |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.Addr = ln.Addr().String() |
| + go srv.ServeTLS(ln, "", "") |
| + t.Cleanup(func() { srv.Close() }) |
| + t.Setenv("EQUIPO_TEST_EGRESS_UPSTREAM", "api.tensorx.ai="+f.Addr) |
| + return f |
| +} |
| + |
| +func (f *TensorX) serve(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/v1/chat/completions" { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + var req struct { |
| + Model string `json:"model"` |
| + Messages []struct { |
| + Role string `json:"role"` |
| + Content json.RawMessage `json:"content"` |
| + } `json:"messages"` |
| + Tools []struct { |
| + Function struct{ Name string } `json:"function"` |
| + } `json:"tools"` |
| + } |
| + if json.NewDecoder(io.LimitReader(r.Body, 8<<20)).Decode(&req) != nil { |
| + http.Error(w, "bad", 400) |
| + return |
| + } |
| + rec := Request{Auth: r.Header.Get("Authorization"), Model: req.Model, Messages: len(req.Messages)} |
| + for _, tool := range req.Tools { |
| + rec.Tools = append(rec.Tools, tool.Function.Name) |
| + } |
| + for _, m := range req.Messages { |
| + if m.Role == "system" || m.Role == "developer" { |
| + rec.System += string(m.Content) |
| + } |
| + } |
| + f.mu.Lock() |
| + f.requests = append(f.requests, rec) |
| + f.mu.Unlock() |
| + if rec.Auth != "Bearer "+TestKey { |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(401) |
| + io.WriteString(w, `{"error":{"message":"Invalid API key"}}`) |
| + return |
| + } |
| + text := "" |
| + role := "" |
| + if n := len(req.Messages); n > 0 { |
| + role = req.Messages[n-1].Role |
| + var s string |
| + if json.Unmarshal(req.Messages[n-1].Content, &s) != nil { |
| + var parts []struct{ Text string } |
| + json.Unmarshal(req.Messages[n-1].Content, &parts) |
| + for _, p := range parts { |
| + s += p.Text |
| + } |
| + } |
| + text = s |
| + } |
| + w.Header().Set("Content-Type", "text/event-stream") |
| + chunk := func(v any) { |
| + raw, _ := json.Marshal(v) |
| + fmt.Fprintf(w, "data: %s\n\n", raw) |
| + if fl, ok := w.(http.Flusher); ok { |
| + fl.Flush() |
| + } |
| + } |
| + base := map[string]any{"id": "c1", "object": "chat.completion.chunk", "created": 1, "model": req.Model} |
| + with := func(k string, v any) map[string]any { |
| + out := map[string]any{} |
| + for a, b := range base { |
| + out[a] = b |
| + } |
| + out[k] = v |
| + return out |
| + } |
| + if role == "tool" { |
| + f.mu.Lock() |
| + f.requests[len(f.requests)-1].ToolText = text |
| + f.mu.Unlock() |
| + } |
| + if role == "user" { |
| + text = steps(text) |
| + } |
| + if role == "user" && strings.HasPrefix(text, "CALL ") { |
| + parts := strings.SplitN(text, " ", 3) |
| + chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "tool_calls": []any{map[string]any{"index": 0, "id": "call_1", "type": "function", "function": map[string]any{"name": parts[1], "arguments": parts[2]}}}}}})) |
| + chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": "tool_calls"}})) |
| + } else { |
| + reply := "ok done" |
| + if role == "tool" { |
| + reply = "done after the tool: " + strings.ReplaceAll(text, "\n", " ") |
| + } |
| + chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "content": reply}}})) |
| + chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": "stop"}})) |
| + } |
| + chunk(with("choices", []any{})) |
| + usage := with("choices", []any{}) |
| + usage["usage"] = map[string]any{"prompt_tokens": 100, "completion_tokens": 7, "total_tokens": 107, "prompt_tokens_details": map[string]any{"cached_tokens": 40}} |
| + chunk(usage) |
| + io.WriteString(w, "data: [DONE]\n\n") |
| +} |
diff --git a/internal/runner/config.go b/internal/runner/config.go| index 707ab9e7..c722de00 100644 |
| --- a/internal/runner/config.go |
| +++ b/internal/runner/config.go |
| @@ -21,7 +21,11 @@ type Config struct { |
| Origin, StateDir, AmadanCredentialPath, AccountBindingsPath, CodexPath string |
| GoRoot, GoBinary, WorkspaceRoot, ScratchRoot, GitPath, AmadanPath, Executable string |
| InstanceID string |
| - Copy ToolCopy |
| + // PiRoot is where the pinned Pi is installed (EQUIPO_PI_ROOT, laid |
| + // out as provider/pi.Paths says); empty, this runner has no Pi and |
| + // runs no step on a metered connection. |
| + PiRoot string |
| + Copy ToolCopy |
| // WorkerOnly: a runner that can only be a worker (a Mac, or the test |
| // build's fake Mac). It refuses an instance without workers. |
| WorkerOnly bool |
| @@ -31,7 +35,7 @@ type Config struct { |
| } |
| func LoadConfig(getenv func(string) string) (Config, error) { |
| - c := Config{WorkerOnly: runtime.GOOS == "darwin" || getenv("EQUIPO_FAKE_PLATFORM") != "", ClaudeModel: getenv("EQUIPO_CLAUDE_MODEL"), CodexModel: getenv("EQUIPO_CODEX_MODEL"), MachineLabel: getenv("EQUIPO_MACHINE_LABEL"), ToolProxyPath: getenv("EQUIPO_TOOL_PROXY_PATH"), CodexCodeModeHostPath: getenv("EQUIPO_CODEX_CODE_MODE_HOST_PATH"), BwrapPath: getenv("EQUIPO_BWRAP_PATH"), ModuleCache: getenv("EQUIPO_GO_MODULE_CACHE"), PreviewCredentialPath: getenv("EQUIPO_PREVIEW_CREDENTIAL_PATH"), CarlosPath: getenv("EQUIPO_CARLOS_PATH"), PreviewHost: getenv("EQUIPO_PREVIEW_HOST"), ClaudePath: getenv("EQUIPO_CLAUDE_PATH"), Origin: getenv("EQUIPO_ORIGIN"), StateDir: getenv("EQUIPO_RUNNER_STATE_DIR"), AmadanCredentialPath: getenv("EQUIPO_AMADAN_CREDENTIAL_PATH"), AccountBindingsPath: getenv("EQUIPO_ACCOUNT_BINDINGS_PATH"), CodexPath: getenv("EQUIPO_CODEX_PATH"), GoRoot: getenv("EQUIPO_GO_ROOT"), GoBinary: getenv("EQUIPO_GO_BINARY"), WorkspaceRoot: getenv("EQUIPO_WORKSPACE_ROOT"), ScratchRoot: getenv("EQUIPO_SCRATCH_ROOT"), GitPath: getenv("EQUIPO_GIT_PATH"), AmadanPath: getenv("EQUIPO_AMADAN_PATH"), InstanceID: getenv("EQUIPO_INSTANCE_ID")} |
| + c := Config{WorkerOnly: runtime.GOOS == "darwin" || getenv("EQUIPO_FAKE_PLATFORM") != "", ClaudeModel: getenv("EQUIPO_CLAUDE_MODEL"), CodexModel: getenv("EQUIPO_CODEX_MODEL"), MachineLabel: getenv("EQUIPO_MACHINE_LABEL"), ToolProxyPath: getenv("EQUIPO_TOOL_PROXY_PATH"), CodexCodeModeHostPath: getenv("EQUIPO_CODEX_CODE_MODE_HOST_PATH"), BwrapPath: getenv("EQUIPO_BWRAP_PATH"), ModuleCache: getenv("EQUIPO_GO_MODULE_CACHE"), PreviewCredentialPath: getenv("EQUIPO_PREVIEW_CREDENTIAL_PATH"), CarlosPath: getenv("EQUIPO_CARLOS_PATH"), PreviewHost: getenv("EQUIPO_PREVIEW_HOST"), ClaudePath: getenv("EQUIPO_CLAUDE_PATH"), Origin: getenv("EQUIPO_ORIGIN"), StateDir: getenv("EQUIPO_RUNNER_STATE_DIR"), AmadanCredentialPath: getenv("EQUIPO_AMADAN_CREDENTIAL_PATH"), AccountBindingsPath: getenv("EQUIPO_ACCOUNT_BINDINGS_PATH"), CodexPath: getenv("EQUIPO_CODEX_PATH"), GoRoot: getenv("EQUIPO_GO_ROOT"), GoBinary: getenv("EQUIPO_GO_BINARY"), WorkspaceRoot: getenv("EQUIPO_WORKSPACE_ROOT"), ScratchRoot: getenv("EQUIPO_SCRATCH_ROOT"), GitPath: getenv("EQUIPO_GIT_PATH"), AmadanPath: getenv("EQUIPO_AMADAN_PATH"), InstanceID: getenv("EQUIPO_INSTANCE_ID"), PiRoot: getenv("EQUIPO_PI_ROOT")} |
| var err error |
| c.Executable, err = os.Executable() |
| if err != nil { |
| @@ -67,6 +71,9 @@ func (c Config) validateFor(goos string) error { |
| return configIssue("runner.config.path", v.name, provider.ErrContract) |
| } |
| } |
| + if c.PiRoot != "" && (!filepath.IsAbs(c.PiRoot) || filepath.Clean(c.PiRoot) != c.PiRoot || c.PiRoot == "/") { |
| + return configIssue("runner.config.path", "EQUIPO_PI_ROOT", provider.ErrContract) |
| + } |
| info, err := os.Stat(c.AmadanPath) |
| if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0111 == 0 { |
| return configIssue("runner.config.path", "EQUIPO_AMADAN_PATH", provider.ErrContract) |
diff --git a/internal/runner/connect/choose.go b/internal/runner/connect/choose.go| index 637a3fc5..27b38f34 100644 |
| --- a/internal/runner/connect/choose.go |
| +++ b/internal/runner/connect/choose.go |
| @@ -32,28 +32,42 @@ const ( |
| coolOffLonger = time.Hour |
| ) |
| -// capable is the slice 1 capability matrix (spec §5): which harness can |
| -// run which role here. Codex runs Engineering and Review through the |
| -// thin runner's Codex step path (the app-server in the implement or |
| -// inspect containment). |
| +// capable is the capability matrix (connections spec §5, connectors |
| +// spec §4.4): which harness can run which role here. Codex runs |
| +// Engineering and Review through the thin runner's Codex step path (the |
| +// app-server in the implement or inspect containment). Pi runs them for |
| +// a metered provider (TensorX), never the coordinator. |
| var capable = map[string][]string{ |
| RoleCoordinator: {"claude", "codex"}, |
| - RoleEngineering: {"claude", "codex"}, |
| - RoleReview: {"claude", "codex"}, |
| + RoleEngineering: {"claude", "codex", "pi"}, |
| + RoleReview: {"claude", "codex", "pi"}, |
| } |
| -// Capable reports whether a provider's harness can run role here. |
| -func Capable(provider, role string) bool { return slices.Contains(capable[role], provider) } |
| +// Capable reports whether a harness can run role here. A provider's own |
| +// CLI is its harness (claude, codex). |
| +func Capable(harness, role string) bool { return slices.Contains(capable[role], harness) } |
| // Candidate is one of the person's connections on the runner, as the |
| // runner knows it now. Used is the provider's reported utilization (0 to |
| // 1) when Known. |
| type Candidate struct { |
| ID, Provider string |
| - State string |
| - ResetsAt time.Time |
| - Used float64 |
| - Known bool |
| + // Harness runs the connection when it is not the provider's own CLI |
| + // (Pi for TensorX). Metered: billed per token (connectors spec §2.1). |
| + Harness string |
| + Metered bool |
| + State string |
| + ResetsAt time.Time |
| + Used float64 |
| + Known bool |
| +} |
| + |
| +// harness is the candidate's harness: its own, or its provider's CLI. |
| +func (c Candidate) harness() string { |
| + if c.Harness != "" { |
| + return c.Harness |
| + } |
| + return c.Provider |
| } |
| // Usable reports whether a connection may be chosen at now: healthy, or |
| @@ -86,13 +100,27 @@ type Choice struct { |
| // connection first, then the one with the most reported headroom, a |
| // connection whose provider reported nothing ranking below any with a |
| // figure, then the configured order. ok is false when nothing can run it. |
| -func Choose(cs []Candidate, role, current, prefer string, avoid []string, now time.Time) (Choice, bool) { |
| - var usable []Candidate |
| +// |
| +// spend is the run's leave to spend metered money (connectors spec §0 |
| +// decision 5 and §7: an urgent task or a released step). Without it a |
| +// metered connection is never a candidate; with it, one is chosen only |
| +// when no subscription connection can run the role. |
| +func Choose(cs []Candidate, role, current, prefer string, avoid []string, now time.Time, spend bool) (Choice, bool) { |
| + var usable, metered []Candidate |
| for _, c := range cs { |
| - if Capable(c.Provider, role) && c.Usable(now) && !slices.Contains(avoid, c.ID) { |
| + if !Capable(c.harness(), role) || !c.Usable(now) || slices.Contains(avoid, c.ID) { |
| + continue |
| + } |
| + switch { |
| + case !c.Metered: |
| usable = append(usable, c) |
| + case spend: |
| + metered = append(metered, c) |
| } |
| } |
| + if len(usable) == 0 { |
| + usable = metered |
| + } |
| if len(usable) == 0 { |
| return Choice{}, false |
| } |
diff --git a/internal/runner/connect/choose_test.go b/internal/runner/connect/choose_test.go| index dfcbaea0..0f3b140b 100644 |
| --- a/internal/runner/connect/choose_test.go |
| +++ b/internal/runner/connect/choose_test.go |
| @@ -52,7 +52,7 @@ func TestChoose(t *testing.T) { |
| {"connecting is never chosen", []Candidate{{ID: "codex-1", Provider: "codex", State: "connecting"}}, RoleCoordinator, "", nil, "", "", ""}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| - got, ok := Choose(tc.cs, tc.role, tc.current, tc.prefer, tc.avoid, now) |
| + got, ok := Choose(tc.cs, tc.role, tc.current, tc.prefer, tc.avoid, now, false) |
| if ok != (tc.want != "") || got.ID != tc.want || got.Reason != tc.reason { |
| t.Fatalf("Choose = %+v %v, want %s %s", got, ok, tc.want, tc.reason) |
| } |
| @@ -127,3 +127,40 @@ func TestCodexRateLimits(t *testing.T) { |
| t.Fatal("quota error") |
| } |
| } |
| + |
| +// Pi on TensorX (connectors spec §4.4): Engineering and Review, never |
| +// the coordinator; and, metered, only for a step with leave to spend |
| +// (§0 decision 5: an urgent task or a released step, S3), and then only |
| +// when no subscription connection can run it (§7, rules 3 and 4). |
| +func TestChooseMetered(t *testing.T) { |
| + now := time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC) |
| + pi := Candidate{ID: "tensorx-a", Provider: "tensorx", Harness: "pi", Metered: true, State: StateHealthy} |
| + claude := Candidate{ID: "c1", Provider: "claude", State: StateHealthy} |
| + for _, tc := range []struct { |
| + name, role string |
| + cs []Candidate |
| + spend bool |
| + avoid []string |
| + want string |
| + }{ |
| + {"no leave: never chosen", RoleReview, []Candidate{pi}, false, nil, ""}, |
| + {"no leave, alongside a subscription", RoleReview, []Candidate{pi, claude}, false, nil, "c1"}, |
| + {"leave, only option", RoleReview, []Candidate{pi}, true, nil, "tensorx-a"}, |
| + {"leave, Engineering", RoleEngineering, []Candidate{pi}, true, nil, "tensorx-a"}, |
| + {"leave, never the coordinator", RoleCoordinator, []Candidate{pi}, true, nil, ""}, |
| + {"leave, a subscription first", RoleReview, []Candidate{pi, claude}, true, nil, "c1"}, |
| + {"leave, a subscription first even with less room", RoleReview, []Candidate{{ID: "tensorx-a", Provider: "tensorx", Harness: "pi", Metered: true, State: StateHealthy, Known: true}, claude}, true, nil, "c1"}, |
| + {"leave, the subscription avoided", RoleReview, []Candidate{claude, pi}, true, []string{"c1"}, "tensorx-a"}, |
| + {"capability is the harness's, not the provider's", RoleReview, []Candidate{{ID: "x", Provider: "tensorx", Metered: true, State: StateHealthy}}, true, nil, ""}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + got, ok := Choose(tc.cs, tc.role, "", "", tc.avoid, now, tc.spend) |
| + if got.ID != tc.want || ok != (tc.want != "") { |
| + t.Fatalf("chose %+v %v, want %q", got, ok, tc.want) |
| + } |
| + }) |
| + } |
| + if !Capable("pi", RoleReview) || !Capable("pi", RoleEngineering) || Capable("pi", RoleCoordinator) { |
| + t.Fatal("the matrix row for Pi") |
| + } |
| +} |
diff --git a/internal/runner/provider/pi/harness_test.go b/internal/runner/provider/pi/harness_test.go| index 35b84706..e93e7e46 100644 |
| --- a/internal/runner/provider/pi/harness_test.go |
| +++ b/internal/runner/provider/pi/harness_test.go |
| @@ -1,27 +1,17 @@ |
| package pi |
| import ( |
| + "amadan.net/oficina/equipo/internal/fakepi" |
| "bufio" |
| "context" |
| - "crypto/ecdsa" |
| - "crypto/elliptic" |
| - "crypto/rand" |
| "crypto/sha256" |
| - "crypto/tls" |
| - "crypto/x509" |
| - "crypto/x509/pkix" |
| "encoding/hex" |
| "encoding/json" |
| - "encoding/pem" |
| "fmt" |
| - "io" |
| - "math/big" |
| "net" |
| - "net/http" |
| "os" |
| "path/filepath" |
| "slices" |
| - "strings" |
| "sync" |
| "testing" |
| "time" |
| @@ -32,158 +22,8 @@ import ( |
| "amadan.net/oficina/equipo/internal/testci" |
| ) |
| -// fakeTensorX is an OpenAI-compatible provider on 127.0.0.1, serving TLS |
| -// as api.tensorx.ai under a test authority. It answers a user message |
| -// "CALL <tool> <json>" with that tool call, a tool result with "done", |
| -// and anything else with "ok done", each with usage; it records what it |
| -// was sent. |
| -type fakeTensorX struct { |
| - addr, ca string |
| - mu sync.Mutex |
| - requests []fakeRequest |
| -} |
| - |
| -type fakeRequest struct { |
| - Auth, Model string |
| - Tools []string |
| - System string |
| - Messages int |
| - // ToolText is the tool result the request answers, if any. |
| - ToolText string |
| -} |
| - |
| -func (f *fakeTensorX) seen() []fakeRequest { |
| - f.mu.Lock() |
| - defer f.mu.Unlock() |
| - return append([]fakeRequest(nil), f.requests...) |
| -} |
| - |
| -func startFakeTensorX(t *testing.T) *fakeTensorX { |
| - t.Helper() |
| - caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| - caTmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "equipo test authority"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign} |
| - caDER, err := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - ca, _ := x509.ParseCertificate(caDER) |
| - key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| - leaf := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "api.tensorx.ai"}, DNSNames: []string{"api.tensorx.ai"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| - leafDER, err := x509.CreateCertificate(rand.Reader, leaf, ca, &key.PublicKey, caKey) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - caFile := filepath.Join(t.TempDir(), "ca.pem") |
| - if err := os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0600); err != nil { |
| - t.Fatal(err) |
| - } |
| - f := &fakeTensorX{ca: caFile} |
| - srv := &http.Server{Handler: http.HandlerFunc(f.serve), TLSConfig: &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{leafDER}, PrivateKey: key}}}} |
| - ln, err := net.Listen("tcp", "127.0.0.1:0") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - f.addr = ln.Addr().String() |
| - go srv.ServeTLS(ln, "", "") |
| - t.Cleanup(func() { srv.Close() }) |
| - t.Setenv("EQUIPO_TEST_EGRESS_UPSTREAM", "api.tensorx.ai="+f.addr) |
| - return f |
| -} |
| - |
| -func (f *fakeTensorX) serve(w http.ResponseWriter, r *http.Request) { |
| - if r.URL.Path != "/v1/chat/completions" { |
| - http.NotFound(w, r) |
| - return |
| - } |
| - var req struct { |
| - Model string `json:"model"` |
| - Messages []struct { |
| - Role string `json:"role"` |
| - Content json.RawMessage `json:"content"` |
| - } `json:"messages"` |
| - Tools []struct { |
| - Function struct{ Name string } `json:"function"` |
| - } `json:"tools"` |
| - } |
| - if json.NewDecoder(io.LimitReader(r.Body, 8<<20)).Decode(&req) != nil { |
| - http.Error(w, "bad", 400) |
| - return |
| - } |
| - rec := fakeRequest{Auth: r.Header.Get("Authorization"), Model: req.Model, Messages: len(req.Messages)} |
| - for _, tool := range req.Tools { |
| - rec.Tools = append(rec.Tools, tool.Function.Name) |
| - } |
| - for _, m := range req.Messages { |
| - if m.Role == "system" || m.Role == "developer" { |
| - rec.System += string(m.Content) |
| - } |
| - } |
| - f.mu.Lock() |
| - f.requests = append(f.requests, rec) |
| - f.mu.Unlock() |
| - if rec.Auth != "Bearer "+testKey { |
| - w.Header().Set("Content-Type", "application/json") |
| - w.WriteHeader(401) |
| - io.WriteString(w, `{"error":{"message":"Invalid API key"}}`) |
| - return |
| - } |
| - text := "" |
| - role := "" |
| - if n := len(req.Messages); n > 0 { |
| - role = req.Messages[n-1].Role |
| - var s string |
| - if json.Unmarshal(req.Messages[n-1].Content, &s) != nil { |
| - var parts []struct{ Text string } |
| - json.Unmarshal(req.Messages[n-1].Content, &parts) |
| - for _, p := range parts { |
| - s += p.Text |
| - } |
| - } |
| - text = s |
| - } |
| - w.Header().Set("Content-Type", "text/event-stream") |
| - chunk := func(v any) { |
| - raw, _ := json.Marshal(v) |
| - fmt.Fprintf(w, "data: %s\n\n", raw) |
| - if fl, ok := w.(http.Flusher); ok { |
| - fl.Flush() |
| - } |
| - } |
| - base := map[string]any{"id": "c1", "object": "chat.completion.chunk", "created": 1, "model": req.Model} |
| - with := func(k string, v any) map[string]any { |
| - out := map[string]any{} |
| - for a, b := range base { |
| - out[a] = b |
| - } |
| - out[k] = v |
| - return out |
| - } |
| - if role == "tool" { |
| - f.mu.Lock() |
| - f.requests[len(f.requests)-1].ToolText = text |
| - f.mu.Unlock() |
| - } |
| - if role == "user" && strings.HasPrefix(text, "CALL ") { |
| - parts := strings.SplitN(text, " ", 3) |
| - chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "tool_calls": []any{map[string]any{"index": 0, "id": "call_1", "type": "function", "function": map[string]any{"name": parts[1], "arguments": parts[2]}}}}}})) |
| - chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": "tool_calls"}})) |
| - } else { |
| - reply := "ok done" |
| - if role == "tool" { |
| - reply = "done after the tool: " + strings.ReplaceAll(text, "\n", " ") |
| - } |
| - chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "content": reply}}})) |
| - chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": "stop"}})) |
| - } |
| - chunk(with("choices", []any{})) |
| - usage := with("choices", []any{}) |
| - usage["usage"] = map[string]any{"prompt_tokens": 100, "completion_tokens": 7, "total_tokens": 107, "prompt_tokens_details": map[string]any{"cached_tokens": 40}} |
| - chunk(usage) |
| - io.WriteString(w, "data: [DONE]\n\n") |
| -} |
| - |
| // testKey is the key the tests deliver; the fake refuses any other. |
| -const testKey = "tx-equipo-test-key-0123456789" |
| +const testKey = fakepi.TestKey |
| // toolServer is the runner's end of the attempt's tool socket: Equipo's |
| // step tools over MCP, recording each call. |
| @@ -281,7 +121,7 @@ type harness struct { |
| install Install |
| proxy string |
| keyHome string |
| - tensorx *fakeTensorX |
| + tensorx *fakepi.TensorX |
| } |
| func copyTestBinary(t *testing.T, dir, name string) string { |
| @@ -380,7 +220,7 @@ func newHarness(t *testing.T, inst Install) *harness { |
| t.Fatal(err) |
| } |
| h := &harness{t: t, manager: m, scratch: scratch, install: inst, proxy: copyTestBinary(t, bin, "equipo-tool-proxy"), keyHome: keyHome} |
| - h.tensorx = startFakeTensorX(t) |
| + h.tensorx = fakepi.StartTensorX(t) |
| return h |
| } |
| @@ -461,7 +301,7 @@ func (h *harness) openWith(work, action string, equipo []string, session, kept s |
| if session == "" { |
| session = NewSessionID() |
| } |
| - in, cleanup, err := Prepare(h.scratch, Run{Install: h.install, Bwrap: "/usr/bin/bwrap", ToolProxy: h.proxy, Scratch: scratch, Workspace: work, Action: action, Provider: "tensorx", BaseURL: "https://api.tensorx.ai/v1", Model: "z-ai/glm-5.3", Equipo: equipo, Resume: session, EgressHosts: egressHosts(t), ExtraCA: h.tensorx.ca}) |
| + in, cleanup, err := Prepare(h.scratch, Run{Install: h.install, Bwrap: "/usr/bin/bwrap", ToolProxy: h.proxy, Scratch: scratch, Workspace: work, Action: action, Provider: "tensorx", BaseURL: "https://api.tensorx.ai/v1", Model: "z-ai/glm-5.3", Equipo: equipo, Resume: session, EgressHosts: egressHosts(t), ExtraCA: h.tensorx.CA}) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/runner/provider/pi/real_test.go b/internal/runner/provider/pi/real_test.go| index 4edb6597..eec26c76 100644 |
| --- a/internal/runner/provider/pi/real_test.go |
| +++ b/internal/runner/provider/pi/real_test.go |
| @@ -21,7 +21,7 @@ import ( |
| var reviewEquipo = []string{"submit_review", "ask_person"} |
| func lastTool(h *harness) string { |
| - seen := h.tensorx.seen() |
| + seen := h.tensorx.Seen() |
| for i := len(seen) - 1; i >= 0; i-- { |
| if seen[i].ToolText != "" { |
| return seen[i].ToolText |
| @@ -58,7 +58,7 @@ func TestPiP1SessionAcrossTurns(t *testing.T) { |
| t.Fatalf("turn %d: %v", i, kinds(evs)) |
| } |
| } |
| - seen := h.tensorx.seen() |
| + seen := h.tensorx.Seen() |
| if len(seen) != 100 || seen[99].Messages < 200 { |
| t.Fatalf("requests %d, last with %d messages", len(seen), seen[len(seen)-1].Messages) |
| } |
| @@ -71,7 +71,7 @@ func TestPiP1SessionAcrossTurns(t *testing.T) { |
| } |
| again := h.openKept(t.TempDir(), "answer", reviewEquipo, r.session.ID, kept) |
| again.prompt(t, "and now?", "deny") |
| - if last := h.tensorx.seen(); last[len(last)-1].Messages < 201 { |
| + if last := h.tensorx.Seen(); last[len(last)-1].Messages < 201 { |
| t.Fatalf("the resumed session lost its history: %d messages", last[len(last)-1].Messages) |
| } |
| } |
| @@ -137,7 +137,7 @@ func TestPiP3MCPPinning(t *testing.T) { |
| if calls := r.tools.called(); len(calls) != 1 || !strings.HasPrefix(calls[0], "submit_review ") { |
| t.Fatalf("tool socket calls %v", calls) |
| } |
| - for _, req := range h.tensorx.seen() { |
| + for _, req := range h.tensorx.Seen() { |
| if !slices.Equal(req.Tools, []string{"read", "grep", "find", "ls", "mcp__equipo__submit_review", "mcp__equipo__ask_person"}) { |
| t.Fatalf("declared %v", req.Tools) |
| } |
| @@ -210,7 +210,7 @@ func TestPiAcceptanceHostileRepository(t *testing.T) { |
| t.Fatalf("the repository's %s loaded", marker) |
| } |
| } |
| - for _, req := range h.tensorx.seen() { |
| + for _, req := range h.tensorx.Seen() { |
| if strings.Contains(req.System, "HOSTILE") || slices.Contains(req.Tools, "exfiltrate") || slices.Contains(req.Tools, "codemode") { |
| t.Fatalf("the repository reached the model: tools %v system %q", req.Tools, req.System) |
| } |
| @@ -236,7 +236,7 @@ func TestPiAcceptanceHostileRepository(t *testing.T) { |
| if _, err := os.Stat(filepath.Join(work, "x")); err == nil { |
| t.Fatal("Review wrote a file") |
| } |
| - last := h.tensorx.seen() |
| + last := h.tensorx.Seen() |
| if tools := last[len(last)-1].Tools; slices.ContainsFunc(tools, func(s string) bool { return s == "bash" || s == "write" || s == "edit" }) { |
| t.Fatalf("Review declared %v", tools) |
| } |
diff --git a/internal/runner/thin/conns.go b/internal/runner/thin/conns.go| index 730440ee..bcea9200 100644 |
| --- a/internal/runner/thin/conns.go |
| +++ b/internal/runner/thin/conns.go |
| @@ -13,6 +13,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/runner/connect" |
| "amadan.net/oficina/equipo/internal/runner/metered" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runner/provider/pi" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -183,13 +184,71 @@ func (c *Conns) candidate(b runner.AccountBinding) connect.Candidate { |
| return cand |
| } |
| -// Choose picks the person's connection for role (connect.Choose). It |
| -// returns ErrNoConnection when none can run it now. |
| +// MeteredMine are the person's metered connections (connectors spec |
| +// S1), as bindings a step can be chosen onto: provider TensorX, run by |
| +// Pi, the family of the connection's one model. Only validated ones, |
| +// not being signed out. |
| +func (c *Conns) MeteredMine(ctx context.Context, person string) []runner.AccountBinding { |
| + if c.Meter == nil { |
| + return nil |
| + } |
| + conns, err := metered.List(ctx, c.State.db) |
| + if err != nil { |
| + c.warn("metered connections", err) |
| + return nil |
| + } |
| + var out []runner.AccountBinding |
| + for _, m := range conns { |
| + if m.Person == person && m.Validated && !m.Retiring && m.Harness == wire.HarnessPi { |
| + out = append(out, meteredBinding(m)) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// meteredBinding is a metered connection as a binding: its id is its |
| +// local id (the usage rows' connection, as the ledger keys them). |
| +func meteredBinding(m metered.Conn) runner.AccountBinding { |
| + return runner.AccountBinding{ID: m.LocalID, LocalID: m.LocalID, PersonID: m.Person, Provider: m.Provider, Family: pi.Family(m.Model), Model: m.Model, AccountID: m.LocalID, CredentialHome: m.Home, Kind: wire.KindAPIKey} |
| +} |
| + |
| +// Metered reports whether a binding is a metered connection's. |
| +func Metered(b runner.AccountBinding) bool { return b.Kind == wire.KindAPIKey } |
| + |
| +// meteredCandidate is a metered connection as Choose sees it: usable |
| +// while its key was not refused (the guard looks at the slot, the |
| +// budget and the spend at admission), unless limited. |
| +func (c *Conns) meteredCandidate(ctx context.Context, b runner.AccountBinding) connect.Candidate { |
| + cand := connect.Candidate{ID: b.ID, Provider: b.Provider, Harness: wire.HarnessPi, Metered: true, State: connect.StateHealthy} |
| + if m, ok, err := metered.Get(ctx, c.State.db, b.LocalID); err != nil || !ok || m.Refused { |
| + cand.State = wire.ConnSignInAgain |
| + } |
| + if cs := c.live[b.ID]; cs.State == wire.ConnLimited || cs.State == wire.ConnSignInAgain { |
| + cand.State, cand.ResetsAt = cs.State, cs.ResetsAt |
| + } |
| + return cand |
| +} |
| + |
| +// Choose picks the person's connection for role (connect.Choose), with |
| +// no leave to spend: never a metered connection (the coordinator's |
| +// turns, and any run that carries no leave). It returns |
| +// ErrNoConnection when none can run it now. |
| func (c *Conns) Choose(ctx context.Context, person, role, current string, avoid []string) (runner.AccountBinding, connect.Choice, error) { |
| + return c.ChooseFor(ctx, person, role, current, avoid, false) |
| +} |
| + |
| +// ChooseFor is Choose for a run that says whether it has leave to spend |
| +// metered money (connectors spec §0 decision 5: an urgent task or a |
| +// released step); without it no metered connection is a candidate. |
| +func (c *Conns) ChooseFor(ctx context.Context, person, role, current string, avoid []string, spend bool) (runner.AccountBinding, connect.Choice, error) { |
| if err := c.load(ctx); err != nil { |
| return runner.AccountBinding{}, connect.Choice{}, err |
| } |
| mine := c.Mine(person) |
| + var metered []runner.AccountBinding |
| + if spend { |
| + metered = c.MeteredMine(ctx, person) |
| + } |
| // Only a checked connection is chosen: one never checked (just added |
| // by the terminal login, or first seen after a restage) is checked now. |
| for _, b := range mine { |
| @@ -205,16 +264,19 @@ func (c *Conns) Choose(ctx context.Context, person, role, current string, avoid |
| for _, b := range mine { |
| cs = append(cs, c.candidate(b)) |
| } |
| + for _, b := range metered { |
| + cs = append(cs, c.meteredCandidate(ctx, b)) |
| + } |
| c.mu.Unlock() |
| prefer, err := c.Preference(ctx, person) |
| if err != nil { |
| return runner.AccountBinding{}, connect.Choice{}, err |
| } |
| - choice, ok := connect.Choose(cs, role, current, prefer.Provider, avoid, c.clock()) |
| + choice, ok := connect.Choose(cs, role, current, prefer.Provider, avoid, c.clock(), spend) |
| if !ok { |
| return runner.AccountBinding{}, connect.Choice{}, ErrNoConnection |
| } |
| - for _, b := range mine { |
| + for _, b := range append(mine, metered...) { |
| if b.ID == choice.ID { |
| return b, choice, nil |
| } |
diff --git a/internal/runner/thin/contract_test.go b/internal/runner/thin/contract_test.go| index 3ab508a8..200839c3 100644 |
| --- a/internal/runner/thin/contract_test.go |
| +++ b/internal/runner/thin/contract_test.go |
| @@ -15,9 +15,12 @@ import ( |
| "time" |
| "amadan.net/oficina/equipo/internal/fakeclaude" |
| + "amadan.net/oficina/equipo/internal/fakepi" |
| "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "amadan.net/oficina/equipo/internal/testci" |
| + "amadan.net/oficina/equipo/internal/toolproxy" |
| "amadan.net/oficina/equipo/internal/wire" |
| "amadan.net/oficina/equipo/internal/wire/wiretest" |
| "amadan.net/rastrillo/rastrillo/budget" |
| @@ -25,8 +28,20 @@ import ( |
| ) |
| func TestMain(m *testing.M) { |
| - if filepath.Base(os.Args[0]) == "claude" { |
| + switch filepath.Base(os.Args[0]) { |
| + case "claude": |
| os.Exit(fakeclaude.Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) |
| + case "node": |
| + // fakepi, started as Node with the Pi CLI's path first. |
| + os.Exit(fakepi.Main(os.Args[2:], os.Stdin, os.Stdout, os.Stderr)) |
| + case "equipo-tool-proxy": |
| + if len(os.Args) != 3 || os.Args[1] != "--socket" || toolproxy.Serve(context.Background(), os.Stdin, os.Stdout, os.Args[2]) != nil { |
| + os.Exit(1) |
| + } |
| + os.Exit(0) |
| + } |
| + if len(os.Args) > 1 && os.Args[1] == "__namespace" { |
| + os.Exit(containment.NamespaceMain(os.Args[2:])) |
| } |
| os.Exit(budget.Main(m)) |
| } |
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go| index 73ce08dc..834bdb26 100644 |
| --- a/internal/runner/thin/engineer.go |
| +++ b/internal/runner/thin/engineer.go |
| @@ -59,7 +59,9 @@ type Engineer struct { |
| O ClaudeOptions |
| // Codex pins the Codex binaries a step may run on a Codex connection. |
| - Codex CodexOptions |
| + Codex CodexOptions |
| + // Pi is the runner's Pi, for a step on a metered connection. |
| + Pi PiOptions |
| Clones *Clones |
| Forge Forge |
| // CI is the hub's hosted CI for checks the instance offers it for |
| @@ -155,7 +157,7 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR |
| } |
| // Nothing can run Engineering now: the step waits, queued, and goes on |
| // its own when a connection returns (spec §3); the queue moves on. |
| - if _, err := e.engineerOn(ctx, r.Person, nil, ""); errors.Is(err, ErrNoConnection) && !r.Republish { |
| + if _, err := e.engineerOn(ctx, r, nil, ""); errors.Is(err, ErrNoConnection) && !r.Republish { |
| rep.State = stepDeferred |
| return rep |
| } |
| @@ -238,7 +240,7 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR |
| for { |
| var err error |
| var resume bool |
| - if b, resume, err = e.fixPlan(ctx, r.Person, avoid, prior, resumable); err != nil { |
| + if b, resume, err = e.fixPlan(ctx, r, avoid, prior, resumable); err != nil { |
| if errors.Is(err, ErrNoConnection) { |
| // Nothing can take it (every connection that could is |
| // refused now): the attempt waits, queued, and goes on its |
| @@ -254,6 +256,13 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR |
| spec.prompt, spec.resume, spec.from = e.fixPrompt(r), prior.SessionID, prior.Dir |
| } |
| res = e.run(ctx, r, tree, spec) |
| + if res.reason == reasonHeld { |
| + // The metered guard holds it (its slot, budget or spend): the |
| + // attempt waits and goes again when the connection's standing |
| + // changes. |
| + rep.State = stepDeferred |
| + return rep |
| + } |
| if resume && res.reason == "session_gone" && res.terminated { |
| // The kept transcript could not be put in place (nothing was |
| // launched): the round starts afresh, as without one. |
| @@ -651,6 +660,9 @@ type stepResult struct { |
| // auth: the provider refused the credential (the connection needs |
| // signing in again); the step moves like a quota refusal. |
| auth bool |
| + // family is the family of the model that ran, where the harness |
| + // reports it (Pi); Review's independence is judged on it. |
| + family string |
| } |
| // usage is the run's usage rows for the step attempt. |
| @@ -668,11 +680,11 @@ func (res stepResult) usage(b runner.AccountBinding, attempt int64) []wire.Usage |
| // engineerOn is the connection an Engineering attempt runs on; current |
| // is a connection to keep when it can still run it ("" for none). |
| -func (e *Engineer) engineerOn(ctx context.Context, person string, avoid []string, current string) (runner.AccountBinding, error) { |
| +func (e *Engineer) engineerOn(ctx context.Context, r stepRow, avoid []string, current string) (runner.AccountBinding, error) { |
| if e.Conns == nil { |
| - return SelectAccount(e.O.Runner, person) |
| + return SelectAccount(e.O.Runner, r.Person) |
| } |
| - b, _, err := e.Conns.Choose(ctx, person, connect.RoleEngineering, current, avoid) |
| + b, _, err := e.Conns.ChooseFor(ctx, r.Person, connect.RoleEngineering, current, avoid, leaveToSpend(r)) |
| return b, err |
| } |
| @@ -700,25 +712,30 @@ func (e *Engineer) fixSession(ctx context.Context, r stepRow, base string) (kept |
| // fixPlan is the connection an Engineering attempt runs on, and whether |
| // it resumes the kept session: only on the connection that session ran |
| -// on, a Claude one, while it can run the attempt (healthy, not limited, |
| -// not refused in this attempt, and as the person's provider preference |
| -// allows; connect.Choose keeps it then). Anything else, the attempt |
| -// starts fresh wherever Choose puts it: failover always wins over the |
| -// warm cache. |
| -func (e *Engineer) fixPlan(ctx context.Context, person string, avoid []string, kept keptSession, resumable bool) (runner.AccountBinding, bool, error) { |
| +// on (a Claude one, or a metered one Pi ran), while it can run the |
| +// attempt (healthy, not limited, not refused in this attempt, and as |
| +// the person's provider preference allows; connect.Choose keeps it |
| +// then). Anything else, the attempt starts fresh wherever Choose puts |
| +// it: failover always wins over the warm cache. |
| +func (e *Engineer) fixPlan(ctx context.Context, r stepRow, avoid []string, kept keptSession, resumable bool) (runner.AccountBinding, bool, error) { |
| current := "" |
| if resumable && e.Conns != nil { |
| - for _, c := range e.Conns.Mine(person) { |
| + for _, c := range e.Conns.Mine(r.Person) { |
| if c.Provider == "claude" && c.LocalID == kept.Account { |
| current = c.ID |
| } |
| } |
| + for _, c := range e.Conns.MeteredMine(ctx, r.Person) { |
| + if c.LocalID == kept.Account { |
| + current = c.ID |
| + } |
| + } |
| } |
| - b, err := e.engineerOn(ctx, person, avoid, current) |
| + b, err := e.engineerOn(ctx, r, avoid, current) |
| if err != nil { |
| return b, false, err |
| } |
| - resume := resumable && b.Provider == "claude" && b.LocalID == kept.Account && (e.Healthy == nil || e.Healthy(b.ID)) |
| + resume := resumable && (b.Provider == "claude" || Metered(b)) && b.LocalID == kept.Account && (e.Healthy == nil || Metered(b) || e.Healthy(b.ID)) |
| return b, resume, nil |
| } |
| @@ -739,6 +756,9 @@ func (e *Engineer) run(ctx context.Context, r stepRow, tree workspace.TaskTree, |
| if spec.binding.Provider == "codex" { |
| return e.runCodex(ctx, r, tree, spec) |
| } |
| + if Metered(spec.binding) { |
| + return e.runPi(ctx, r, tree, spec) |
| + } |
| o := e.O |
| b := spec.binding |
| direct, err := o.Runner.DirectBinding(b) |
diff --git a/internal/runner/thin/fixround_test.go b/internal/runner/thin/fixround_test.go| index 423be241..b3b0379b 100644 |
| --- a/internal/runner/thin/fixround_test.go |
| +++ b/internal/runner/thin/fixround_test.go |
| @@ -82,7 +82,7 @@ func fixRound() stepRow { |
| func (r *fixRig) plan(row stepRow, avoid []string) (string, bool) { |
| r.t.Helper() |
| kept, ok := r.e.fixSession(context.Background(), row, row.Base) |
| - b, resume, err := r.e.fixPlan(context.Background(), row.Person, avoid, kept, ok) |
| + b, resume, err := r.e.fixPlan(context.Background(), row, avoid, kept, ok) |
| if err != nil { |
| r.t.Fatal(err) |
| } |
diff --git a/internal/runner/thin/judge.go b/internal/runner/thin/judge.go| index aad97eb3..c27f6959 100644 |
| --- a/internal/runner/thin/judge.go |
| +++ b/internal/runner/thin/judge.go |
| @@ -624,9 +624,10 @@ func verdictOf(args json.RawMessage) (verdict, headline, summary string, finding |
| // (with connections; without them, Claude accounts only), else another |
| // account of the same family, else a fresh session on the same account |
| // (same family, same account). |
| -func (e *Engineer) reviewer(ctx context.Context, person, avoid string) (runner.AccountBinding, string, error) { |
| +func (e *Engineer) reviewer(ctx context.Context, r stepRow) (runner.AccountBinding, string, error) { |
| + person, avoid := r.Person, r.AvoidAccount |
| if e.Conns != nil { |
| - return e.reviewOn(ctx, person, avoid) |
| + return e.reviewOn(ctx, person, avoid, leaveToSpend(r)) |
| } |
| bs, err := runner.LoadBindings(e.O.Runner.AccountBindingsPath) |
| if err != nil { |
| @@ -664,39 +665,53 @@ func pickReviewer(bs []runner.AccountBinding, person, avoid string, healthy func |
| // family, else another account of the same family), else a fresh session |
| // on Engineering's own (same account). A limited connection is never |
| // chosen. |
| -func (e *Engineer) reviewOn(ctx context.Context, person, avoid string) (runner.AccountBinding, string, error) { |
| - var engineer runner.AccountBinding |
| - for i, b := range e.Conns.Mine(person) { |
| - if i == 0 || b.ID == avoid || b.LocalID == avoid { |
| - engineer = b |
| - } |
| - } |
| +func (e *Engineer) reviewOn(ctx context.Context, person, avoid string, spend bool) (runner.AccountBinding, string, error) { |
| + engineer := e.engineerOf(ctx, person, avoid) |
| // The family first: only when no connection of another family can |
| // review does the choice (preference, headroom, order) look at the |
| // engineer's family, then at its own account. |
| var same []string |
| - for _, c := range e.Conns.Mine(person) { |
| + for _, c := range append(e.Conns.Mine(person), e.Conns.MeteredMine(ctx, person)...) { |
| if c.Family == engineer.Family { |
| same = append(same, c.ID) |
| } |
| } |
| - b, _, err := e.Conns.Choose(ctx, person, connect.RoleReview, "", same) |
| + b, _, err := e.Conns.ChooseFor(ctx, person, connect.RoleReview, "", same, spend) |
| if errors.Is(err, ErrNoConnection) { |
| - b, _, err = e.Conns.Choose(ctx, person, connect.RoleReview, "", []string{engineer.ID}) |
| + b, _, err = e.Conns.ChooseFor(ctx, person, connect.RoleReview, "", []string{engineer.ID}, spend) |
| } |
| if errors.Is(err, ErrNoConnection) { |
| - b, _, err = e.Conns.Choose(ctx, person, connect.RoleReview, "", nil) |
| + b, _, err = e.Conns.ChooseFor(ctx, person, connect.RoleReview, "", nil, spend) |
| } |
| if err != nil { |
| return b, "", err |
| } |
| + return b, reviewLabel(engineer, b, b.Family), nil |
| +} |
| + |
| +// engineerOf is the connection Engineering ran on (avoid names it), else |
| +// the person's first. |
| +func (e *Engineer) engineerOf(ctx context.Context, person, avoid string) runner.AccountBinding { |
| + var engineer runner.AccountBinding |
| + for i, b := range append(e.Conns.Mine(person), e.Conns.MeteredMine(ctx, person)...) { |
| + if i == 0 || b.ID == avoid || b.LocalID == avoid { |
| + engineer = b |
| + } |
| + } |
| + return engineer |
| +} |
| + |
| +// reviewLabel is Review's independence from Engineering (connectors spec |
| +// §3, "Families": judged on the model that ran): another family, else |
| +// another account of the same family, else the same account. |
| +func reviewLabel(engineer, reviewer runner.AccountBinding, family string) string { |
| switch { |
| - case b.Family != engineer.Family: |
| - return b, wire.ReviewOtherFamily, nil |
| - case b.AccountID != engineer.AccountID: |
| - return b, wire.ReviewSameFamily, nil |
| + case family != engineer.Family: |
| + return wire.ReviewOtherFamily |
| + case reviewer.AccountID != engineer.AccountID: |
| + return wire.ReviewSameFamily |
| } |
| - return b, wire.ReviewSameAccount, nil |
| + return wire.ReviewSameAccount |
| } |
| // review reads the candidate and records the verdict. |
| @@ -715,7 +730,7 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste |
| } |
| defer os.RemoveAll(tree.GitDir) |
| defer os.RemoveAll(tree.Dir) |
| - b, label, err := e.reviewer(ctx, r.Person, r.AvoidAccount) |
| + b, label, err := e.reviewer(ctx, r) |
| if errors.Is(err, ErrNoConnection) { |
| // Nothing can review now: the step waits, queued, and goes on its |
| // own when a connection returns (spec §3); the queue moves on. |
| @@ -746,6 +761,11 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste |
| return "Recorded. End with your summary.", false |
| } |
| res := e.run(ctx, r, tree, specialistRun{action: "inspect", binding: b, tools: reviewTools, names: []string{"submit_review", "ask_person"}, permission: claude.ReadPermission, call: call, prompt: e.reviewPrompt(r, diff), keep: e.keepDir(r), activity: e.stepActivity(r)}) |
| + if res.reason == reasonHeld { |
| + // The metered guard holds it: Review waits, deferred. |
| + rep.State = stepDeferred |
| + return rep |
| + } |
| e.observe(b.ID, res) |
| // Refused on quota or the credential before a verdict: once the exit |
| // is proven, Review runs again as a new attempt, advanced durably, on |
| @@ -757,7 +777,7 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste |
| rep.State, rep.Reason, rep.Termination = wire.StepFailed, "provider_failed", true |
| return rep |
| } |
| - next, nextLabel, err := e.reviewer(ctx, r.Person, r.AvoidAccount) |
| + next, nextLabel, err := e.reviewer(ctx, r) |
| if errors.Is(err, ErrNoConnection) { |
| rep.State = stepDeferred |
| return rep |
| @@ -772,6 +792,14 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste |
| res = e.run(ctx, r, tree, specialistRun{action: "inspect", binding: b, tools: reviewTools, names: []string{"submit_review", "ask_person"}, permission: claude.ReadPermission, call: call, prompt: e.reviewPrompt(r, diff), keep: e.keepDir(r), activity: e.stepActivity(r)}) |
| e.observe(b.ID, res) |
| } |
| + if res.family != "" && res.family != b.Family { |
| + // Independence is judged on the model that ran (connectors spec |
| + // §3, "Families"). |
| + rep.Family = res.family |
| + if e.Conns != nil { |
| + label = reviewLabel(e.engineerOf(ctx, r.Person, r.AvoidAccount), b, res.family) |
| + } |
| + } |
| rep.Usage = append(rep.Usage, res.usage(b, r.Attempt)...) |
| rep.LogTail = res.tail |
| kept := e.recordKept(ctx, r, b.LocalID, res, r.CandidateSHA) |
diff --git a/internal/runner/thin/pistep.go b/internal/runner/thin/pistep.go| new file mode 100644 |
| index 00000000..cf5e7750 |
| --- /dev/null |
| +++ b/internal/runner/thin/pistep.go |
| @@ -0,0 +1,528 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "os" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "amadan.net/oficina/equipo/internal/runner/egress" |
| + "amadan.net/oficina/equipo/internal/runner/metered" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runner/provider/pi" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// PiOptions is where this runner's Pi is (EQUIPO_PI_ROOT, laid out as |
| +// pi.Paths says) and the pins a launch requires: this platform's |
| +// committed ones in production, a test's fake's in tests. |
| +type PiOptions struct { |
| + Install pi.Install |
| +} |
| + |
| +// reasonHeld is a step's run held by the metered guard: the slot is |
| +// taken, the budget reached or the spend unknown (connectors spec §2.3). |
| +// The step waits, deferred, and is looked at again when the |
| +// connection's standing changes. |
| +const reasonHeld = "metered_held" |
| + |
| +// meteredRole is the guard's role for a step's action. |
| +func meteredRole(action string) string { |
| + switch action { |
| + case "implement": |
| + return metered.RoleEngineering |
| + case "answer": |
| + return metered.RoleAsk |
| + } |
| + return metered.RoleReview |
| +} |
| + |
| +// runPi runs a step's specialist on a metered connection through Pi |
| +// (connectors spec §4.1, slice S2), through the metered guard: admitted |
| +// with the slot claimed, the attempt's usage priced and charged once, |
| +// the slot released only after the namespace's exit is proven. |
| +func (e *Engineer) runPi(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun) stepResult { |
| + b := spec.binding |
| + if e.Conns == nil || e.Conns.Meter == nil { |
| + return stepResult{reason: "account_unavailable", terminated: true} |
| + } |
| + h := metered.Holder{Step: r.StepID, Attempt: r.Attempt, Role: meteredRole(spec.action)} |
| + var res stepResult |
| + var priced []wire.Usage |
| + adm, _, err := e.Conns.Meter.Run(ctx, b.LocalID, h, func(ctx context.Context, l metered.Launch) metered.Result { |
| + var ending metered.Ending |
| + res, ending = e.piAttempt(ctx, r, tree, spec, l) |
| + return metered.Result{Usage: usageRows(res.tokens, b, r.Attempt, outcomeOf(res, ctx)), Ending: ending} |
| + }, func(_ *sql.Tx, rows []wire.Usage) error { |
| + priced = rows |
| + return nil |
| + }) |
| + if err != nil { |
| + e.log("step metered", err) |
| + if !adm.Admitted { |
| + return stepResult{reason: "account_unavailable", terminated: true} |
| + } |
| + } |
| + if !adm.Admitted { |
| + return stepResult{reason: reasonHeld, terminated: true} |
| + } |
| + if priced != nil { |
| + res.tokens = priced |
| + } |
| + if res.auth { |
| + e.Conns.KeyRefused(context.WithoutCancel(ctx), b.LocalID) |
| + } |
| + return res |
| +} |
| + |
| +// outcomeOf is a run's usage outcome. |
| +func outcomeOf(res stepResult, ctx context.Context) string { |
| + switch { |
| + case res.reason == "": |
| + return wire.OutcomeReplied |
| + case res.reason == "cancelled" || ctx.Err() != nil: |
| + return wire.OutcomeCancelled |
| + } |
| + return wire.OutcomeFailed |
| +} |
| + |
| +// piHost starts a Pi launch through the containment, recording its |
| +// namespace for the step (or question) and in the metered slot before |
| +// it starts, and keeps the process so its exit can be proven. |
| +type piHost struct { |
| + m *containment.Manager |
| + record func(context.Context, string) error |
| + mu sync.Mutex |
| + proc provider.Process |
| +} |
| + |
| +func (h *piHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { |
| + p, err := recordedStart(ctx, h.m, l, argv, h.record) |
| + if err == nil { |
| + h.mu.Lock() |
| + h.proc = p |
| + h.mu.Unlock() |
| + } |
| + return p, err |
| +} |
| + |
| +func (h *piHost) started() provider.Process { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + return h.proc |
| +} |
| + |
| +// piBaseURL is a provider's OpenAI-compatible base URL behind Pi. |
| +func piBaseURL(providerName string) string { |
| + p := wire.APIKeyProviders[providerName] |
| + return p.Upstream + p.APIPath |
| +} |
| + |
| +// piAttempt is one admitted Pi run: Pi prepared and certified, started |
| +// in the action's containment, one prompt read to its end, the |
| +// namespace stopped and its exit proven. |
| +func (e *Engineer) piAttempt(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun, l metered.Launch) (stepResult, metered.Ending) { |
| + o, b := e.O, spec.binding |
| + notStarted := metered.Ending{Proven: true, NotStarted: true} |
| + inst, ok := e.Pi.Install.Pinned() |
| + if !ok { |
| + return stepResult{reason: "account_unavailable", terminated: true}, notStarted |
| + } |
| + scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-") |
| + if err != nil { |
| + return stepResult{reason: "provider_failed", terminated: true}, notStarted |
| + } |
| + defer os.RemoveAll(scratch) |
| + tool, err := openToolSet(context.Background(), o.Runner.StateDir, toolSet{list: spec.tools, names: spec.names}, spec.call) |
| + if err != nil { |
| + return stepResult{reason: "provider_failed", terminated: true}, notStarted |
| + } |
| + defer tool.Close() |
| + network, err := egress.ProviderPolicy(provider.NetworkContract{Provider: b.Provider, Harness: wire.HarnessPi}, false) |
| + if err != nil { |
| + return stepResult{reason: "policy_rejected", terminated: true}, notStarted |
| + } |
| + session := spec.resume |
| + if session == "" { |
| + session = pi.NewSessionID() |
| + } |
| + in, cleanup, err := pi.Prepare(o.Runner.ScratchRoot, pi.Run{Install: inst, Bwrap: o.Runner.Bwrap(), ToolProxy: o.Runner.ToolProxy(), Scratch: scratch, Workspace: tree.Dir, Action: spec.action, Provider: b.Provider, BaseURL: piBaseURL(b.Provider), Model: b.Model, Equipo: spec.names, Resume: session, EgressHosts: network.Hosts, ExtraCA: piTestCA()}) |
| + if err != nil { |
| + e.log("step pi", err) |
| + return stepResult{reason: "policy_rejected", terminated: true}, notStarted |
| + } |
| + defer cleanup() |
| + if spec.resume != "" { |
| + if err := pi.RestoreSession(firstNonEmpty(spec.from, spec.keep), session, in.Home); err != nil { |
| + return stepResult{reason: "session_gone", terminated: true}, notStarted |
| + } |
| + } |
| + policy, err := provider.BuildPiPolicy(in) |
| + if err != nil { |
| + e.log("step policy", err) |
| + return stepResult{reason: "policy_rejected", terminated: true}, notStarted |
| + } |
| + limit := e.MaxStep |
| + if spec.limit > 0 { |
| + limit = spec.limit |
| + } |
| + record := spec.record |
| + if record == nil { |
| + record = func(ctx context.Context, id string) error { return e.O.State.setStepNamespace(ctx, r, id) } |
| + } |
| + host := &piHost{m: o.Manager, record: func(ctx context.Context, id string) error { |
| + if err := record(ctx, id); err != nil { |
| + return err |
| + } |
| + return l.Namespace(id) |
| + }} |
| + launcher, _ := pi.New(host) |
| + launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "step/" + stepKey(r) + "/" + uuid(), Workspace: tree.Dir, Selection: provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID}, Binding: provider.PiBinding(b.LocalID, in.Home, b.CredentialHome), Policy: policy} |
| + // pctx is the attempt's lifetime: cancelling it kills the namespace. |
| + pctx, kill := context.WithCancel(context.Background()) |
| + defer kill() |
| + sess, err := launcher.Open(pctx, launch) |
| + proc := host.started() |
| + if proc == nil { |
| + e.log("step start", err) |
| + return stepResult{reason: "policy_rejected", terminated: true}, notStarted |
| + } |
| + exited := make(chan error, 1) |
| + go func() { |
| + _, err := proc.Wait(context.Background()) |
| + exited <- err |
| + }() |
| + go func() { _, _ = io.Copy(io.Discard, io.LimitReader(proc.Stderr(), 1<<20)) }() |
| + var res stepResult |
| + if err != nil { |
| + e.log("step pi", err) |
| + res = stepResult{reason: "policy_rejected"} |
| + if errors.Is(err, provider.ErrIdentity) { |
| + res.reason = "provider_failed" |
| + } |
| + } else { |
| + var logFile io.WriteCloser = nopWriteCloser{} |
| + if !spec.noLog { |
| + logFile = e.openLog(r) |
| + } |
| + res = e.piRun(ctx, launcher, sess, limit, spec, logFile) |
| + logFile.Close() |
| + } |
| + res.session = session |
| + res.terminated = stopStep(func() { |
| + if err == nil { |
| + launcher.Close(context.Background(), sess) |
| + } else { |
| + proc.Stdin().Close() |
| + } |
| + }, exited, kill, ctx.Err() == nil && res.reason == "", 10*time.Second, 30*time.Second) |
| + if !res.terminated { |
| + // The namespace record stays: a restarted runner verifies it, and |
| + // the metered slot stays held until it is proven (Recover). |
| + e.log("step stop", errors.New("exit not verified")) |
| + return res, metered.Ending{} |
| + } |
| + e.forget(proc.ID()) |
| + if spec.keep != "" && err == nil { |
| + n, err := pi.KeepSession(in.Home, session, spec.keep) |
| + e.log("kept sessions", err) |
| + res.kept = n |
| + } |
| + return res, metered.Ending{Proven: true} |
| +} |
| + |
| +// piRun sends the prompt and reads Pi's events to the run's end. Every |
| +// question Equipo's extension asks is refused: in a step nobody can |
| +// answer, and the namespace is the containment (connectors spec §3). |
| +func (e *Engineer) piRun(ctx context.Context, l *pi.Launcher, sess provider.Session, limit time.Duration, spec specialistRun, logFile io.Writer) stepResult { |
| + tail := &stepTail{} |
| + tally := &pi.Tally{} |
| + tctx, cancel := context.WithTimeout(ctx, limit) |
| + defer cancel() |
| + finish := func(res stepResult) stepResult { |
| + res.tail = tail.String() |
| + row := tally.Row() |
| + res.tokens = []wire.Usage{row} |
| + res.family = pi.Family(tally.Model()) |
| + return res |
| + } |
| + events, err := l.Events(tctx, sess) |
| + if err == nil { |
| + err = l.StartTurn(tctx, sess, provider.Turn{ID: uuid(), Prompt: spec.prompt}) |
| + } |
| + if spec.stream != nil { |
| + spec.stream.stdin = time.Now() |
| + } |
| + if err != nil { |
| + if tctx.Err() != nil { |
| + return finish(piCancelled(ctx)) |
| + } |
| + return finish(stepResult{reason: "provider_failed"}) |
| + } |
| + written := 0 |
| + text := &strings.Builder{} |
| + lastActivity := "" |
| + for { |
| + select { |
| + case <-tctx.Done(): |
| + ictx, stop := context.WithTimeout(context.Background(), 2*time.Second) |
| + _ = l.Interrupt(ictx, sess) |
| + stop() |
| + return finish(piCancelled(ctx)) |
| + case ev, ok := <-events: |
| + if !ok { |
| + return finish(stepResult{reason: "provider_failed", summary: text.String()}) |
| + } |
| + if line, err := json.Marshal(map[string]any{"kind": ev.Kind, "payload": ev.Payload}); err == nil && written+len(line) < stepLogLimit { |
| + n, _ := logFile.Write(append(line, '\n')) |
| + written += n |
| + } |
| + tally.Add(ev) |
| + switch ev.Kind { |
| + case pi.KindDelta: |
| + var d pi.Delta |
| + _ = json.Unmarshal(ev.Payload, &d) |
| + text.WriteString(d.Text) |
| + if s := spec.stream; s != nil { |
| + s.mark(&s.timing.FirstEventMs) |
| + s.mark(&s.timing.FirstTextMs) |
| + s.timing.LastTextMs = max(time.Since(s.stdin).Milliseconds(), 1) |
| + if s.delta != nil { |
| + s.delta(s.offset, d.Text) |
| + } |
| + s.offset += int64(len(d.Text)) |
| + } |
| + case pi.KindToolCall: |
| + // The final answer is what follows the last tool. |
| + text.Reset() |
| + var c pi.ToolCall |
| + _ = json.Unmarshal(ev.Payload, &c) |
| + kind, subject, line := piActivity(c) |
| + if line != "" { |
| + tail.add(line) |
| + } |
| + if kind != "" && spec.activity != nil && kind+"\x00"+subject != lastActivity { |
| + lastActivity = kind + "\x00" + subject |
| + spec.activity(kind, subject) |
| + } |
| + if s := spec.stream; s != nil && s.activity != nil { |
| + s.mark(&s.timing.FirstToolMs) |
| + s.activity(wire.ActivityTool, piAnswerTool(c.Tool)) |
| + } |
| + case pi.KindAsk: |
| + tail.add("Refused a call Equipo does not allow") |
| + _ = l.Respond(tctx, sess, provider.Answer{RequestID: ev.RequestID, Behavior: "deny"}) |
| + case pi.KindDone: |
| + var d pi.Done |
| + _ = json.Unmarshal(ev.Payload, &d) |
| + final := strings.TrimSpace(text.String()) |
| + if final != "" { |
| + tail.add(final) |
| + } |
| + switch d.Status { |
| + case pi.StatusCompleted: |
| + return finish(stepResult{summary: final}) |
| + case pi.StatusInterrupted: |
| + return finish(piCancelled(ctx)) |
| + } |
| + if d.Error != "" { |
| + tail.add(d.Error) |
| + } |
| + switch d.Failure { |
| + case pi.FailAuth: |
| + return finish(stepResult{reason: "sign_in_again", auth: true}) |
| + case pi.FailQuota: |
| + return finish(stepResult{reason: "limited", limit: &connect.Limit{Limited: true}}) |
| + } |
| + return finish(stepResult{reason: "provider_failed", summary: final}) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func piCancelled(ctx context.Context) stepResult { |
| + if ctx.Err() != nil { |
| + return stepResult{reason: "cancelled"} |
| + } |
| + return stepResult{reason: "step_timeout"} |
| +} |
| + |
| +// piActivity is what a Pi tool call shows: the activity kind and its |
| +// subject (clipped), and the line it adds to the step's tail. |
| +func piActivity(c pi.ToolCall) (kind, subject, line string) { |
| + var args struct{ Command, Path string } |
| + _ = json.Unmarshal(c.Args, &args) |
| + switch c.Tool { |
| + case "bash": |
| + kind, subject = wire.ActivityRun, args.Command |
| + case "edit", "write": |
| + kind, subject = wire.ActivityEdit, args.Path |
| + default: |
| + if t := pi.EquipoTool(c.Tool); t != "" { |
| + return wire.ActivityOther, "", t |
| + } |
| + return "", "", "" |
| + } |
| + subject = strings.TrimPrefix(strings.TrimSpace(strings.SplitN(strings.TrimSpace(subject), "\n", 2)[0]), "/workspace/") |
| + line = map[string]string{wire.ActivityRun: "Bash ", wire.ActivityEdit: "Edit "}[kind] + subject |
| + return kind, clip(subject, wire.MaxActivitySubject), line |
| +} |
| + |
| +// piAnswerTool is what an answering session shows for a tool. |
| +func piAnswerTool(tool string) string { |
| + switch tool { |
| + case "read": |
| + return wire.ToolReadFile |
| + case "grep", "find", "ls": |
| + return wire.ToolSearchCode |
| + } |
| + switch pi.EquipoTool(tool) { |
| + case "git_log", "git_diff", "git_show": |
| + return "read_change" |
| + } |
| + return "other" |
| +} |
| + |
| +// KeyRefused records that the provider refused a metered connection's |
| +// key in a run: the connection is refused (hello says sign in again) |
| +// until a Check again proves the key. |
| +func (c *Conns) KeyRefused(ctx context.Context, local string) { |
| + if c.Meter == nil { |
| + return |
| + } |
| + tx, err := c.State.db.BeginTx(ctx, nil) |
| + if err == nil { |
| + err = metered.Checked(ctx, tx, local, false) |
| + if err == nil { |
| + err = tx.Commit() |
| + } else { |
| + tx.Rollback() |
| + } |
| + } |
| + if err != nil { |
| + c.warn("metered key refused", err) |
| + } |
| + c.SignInAgain(local) |
| + c.changed() |
| +} |
| + |
| +// askBinding is the metered binding a kept session ran on. |
| +func (e *Engineer) askBinding(ctx context.Context, person, account string) (runner.AccountBinding, bool) { |
| + if e.Conns == nil { |
| + return runner.AccountBinding{}, false |
| + } |
| + for _, b := range e.Conns.MeteredMine(ctx, person) { |
| + if b.LocalID == account { |
| + return b, true |
| + } |
| + } |
| + return runner.AccountBinding{}, false |
| +} |
| + |
| +// askPi answers a question from a step's kept Pi session, on the |
| +// session's own metered connection, after the guard admitted it |
| +// (askMetered, connectors spec §7): the exact commit read-only, the |
| +// session resumed, the answer's usage charged. |
| +func (e *Engineer) askPi(ctx context.Context, a askRow, l metered.Launch, progress func(wire.AnswerReport)) (wire.AnswerReport, metered.Ending) { |
| + notStarted := metered.Ending{Proven: true, NotStarted: true} |
| + rep := wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt} |
| + fail := func(reason string) (wire.AnswerReport, metered.Ending) { |
| + rep.State, rep.Reason = wire.QuestionFailed, reason |
| + if ctx.Err() != nil { |
| + rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" |
| + } |
| + return rep, notStarted |
| + } |
| + if !slices.Contains(e.Owners, a.Person) || !repoKey.MatchString(a.Repo) || !wire.ValidTaskBranch(a.Branch) || !shaPattern.MatchString(a.CandidateSHA) || a.BaseSHA != "" && !shaPattern.MatchString(a.BaseSHA) { |
| + return fail("policy_rejected") |
| + } |
| + kept, found, err := e.O.State.keptSessionFor(ctx, a.StepID) |
| + if err != nil { |
| + return fail("provider_failed") |
| + } |
| + if !found || kept.TaskID != a.TaskID || kept.Person != a.Person || kept.Specialist != a.Specialist || !pi.HasSession(kept.Dir, kept.SessionID) { |
| + return fail("session_gone") |
| + } |
| + if kept.Candidate != a.CandidateSHA { |
| + return fail("policy_rejected") |
| + } |
| + b, ok := e.askBinding(ctx, a.Person, kept.Account) |
| + if !ok || b.LocalID != l.Conn.LocalID { |
| + return fail("account_unavailable") |
| + } |
| + r := stepRow{DispatchCommand: wire.DispatchCommand{Person: a.Person, TaskID: a.TaskID, StepID: a.QuestionID, Attempt: a.Attempt, Repo: a.Repo, Branch: a.Branch, BaseSHA: a.BaseSHA, CandidateSHA: a.CandidateSHA}, Question: true} |
| + tree, reason, err := e.judgeTree(ctx, r) |
| + if err != nil { |
| + return fail(reason) |
| + } |
| + defer os.RemoveAll(tree.GitDir) |
| + defer os.RemoveAll(tree.Dir) |
| + rep.State = wire.QuestionRunning |
| + progress(rep) |
| + stream := &answerStream{} |
| + if e.Delta != nil { |
| + stream.delta = func(offset int64, text string) { |
| + e.Delta(wire.DeltaReport{TurnID: a.QuestionID, Attempt: a.Attempt, Offset: offset, Text: text}) |
| + } |
| + } |
| + if e.Activity != nil { |
| + stream.activity = func(kind, tool string) { |
| + e.Activity(wire.ActivityReport{TurnID: a.QuestionID, Attempt: a.Attempt, Kind: kind, Tool: tool}) |
| + } |
| + } |
| + var mu sync.Mutex |
| + call := func(cctx context.Context, name, _ string, args json.RawMessage) (string, bool) { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + return answerGit(cctx, tree.Git, tree.GitDir, a.BaseSHA, a.CandidateSHA, name, args) |
| + } |
| + limit := e.MaxAnswer |
| + if limit <= 0 { |
| + limit = maxAnswer |
| + } |
| + res, ending := e.piAttempt(ctx, r, tree, specialistRun{action: "answer", binding: b, tools: answerTools, names: []string{"git_log", "git_diff", "git_show"}, call: call, prompt: e.askPrompt(a), resume: kept.SessionID, keep: kept.Dir, stream: stream, limit: limit, noLog: true, |
| + record: func(ctx context.Context, id string) error { return e.O.State.setAskNamespace(ctx, a, id) }}, l) |
| + if res.kept > 0 { |
| + e.log("kept sessions", e.O.State.touchKept(context.WithoutCancel(ctx), kept, res.kept)) |
| + } |
| + switch { |
| + case ctx.Err() != nil: |
| + rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" |
| + case res.reason == "step_timeout": |
| + rep.State, rep.Reason = wire.QuestionFailed, "turn_timeout" |
| + case res.reason != "": |
| + if !wire.AnswerReasons[res.reason] { |
| + res.reason = "provider_failed" |
| + } |
| + rep.State, rep.Reason = wire.QuestionFailed, res.reason |
| + case strings.TrimSpace(res.summary) == "": |
| + rep.State, rep.Reason = wire.QuestionFailed, "provider_failed" |
| + default: |
| + rep.State, rep.Text = wire.QuestionAnswered, clip(strings.TrimSpace(res.summary), wire.MaxAnswerText) |
| + t := stream.timing |
| + t.Cold = true |
| + rep.Timing = &t |
| + } |
| + outcome := wire.OutcomeFailed |
| + switch rep.State { |
| + case wire.QuestionAnswered: |
| + outcome = wire.OutcomeReplied |
| + case wire.QuestionCancelled: |
| + outcome = wire.OutcomeCancelled |
| + } |
| + rep.Usage = usageRows(res.tokens, b, a.Attempt, outcome) |
| + if res.auth { |
| + e.Conns.KeyRefused(context.WithoutCancel(ctx), b.LocalID) |
| + } |
| + return rep, ending |
| +} |
diff --git a/internal/runner/thin/pistep_test.go b/internal/runner/thin/pistep_test.go| new file mode 100644 |
| index 00000000..a4ef4536 |
| --- /dev/null |
| +++ b/internal/runner/thin/pistep_test.go |
| @@ -0,0 +1,472 @@ |
| +package thin |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/hex" |
| + "encoding/json" |
| + "log/slog" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/fakepi" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "amadan.net/oficina/equipo/internal/runner/metered" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runner/provider/pi" |
| + "amadan.net/oficina/equipo/internal/testci" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +const piLocal = "tensorx-abcdef012345" |
| + |
| +// piRig is a runner with one Claude connection, Engineering's (limited |
| +// now), and one metered TensorX connection run by Pi, in the real |
| +// containment; a task branch with one change for Review to judge. |
| +type piRig struct { |
| + t *testing.T |
| + ctx context.Context |
| + e *Engineer |
| + state *State |
| + conns *Conns |
| + review stepRow |
| +} |
| + |
| +func copySelf(t *testing.T, dir, name string) string { |
| + t.Helper() |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, err := os.ReadFile(self) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p := filepath.Join(dir, name) |
| + if err := os.WriteFile(p, raw, 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + return p |
| +} |
| + |
| +// fakePiInstall is fakepi as the Pi CLI, run by a copy of this binary as |
| +// Node, with its own digests as the pins. |
| +func fakePiInstall(t *testing.T) pi.Install { |
| + t.Helper() |
| + dir := t.TempDir() |
| + node := copySelf(t, dir, "node") |
| + tree := filepath.Join(dir, "pi", "node_modules") |
| + cli := filepath.Join(tree, "@earendil-works/pi-coding-agent/dist/bundle/cli.js") |
| + os.MkdirAll(filepath.Dir(cli), 0755) |
| + if err := os.WriteFile(cli, []byte("// fakepi\n"), 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := pi.Seal(tree); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { |
| + filepath.Walk(tree, func(p string, info os.FileInfo, err error) error { |
| + if err == nil && info.IsDir() { |
| + os.Chmod(p, 0755) |
| + } |
| + return nil |
| + }) |
| + }) |
| + sum, err := pi.TreeSHA256(tree) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _ := os.ReadFile(node) |
| + return pi.Install{Node: node, Tree: tree, NodeSHA256: sha256Hex(raw), TreeSHA256: sum} |
| +} |
| + |
| +// realPiInstall is the pinned Pi this machine has (EQUIPO_PI_ROOT). |
| +func realPiInstall(t *testing.T) pi.Install { |
| + t.Helper() |
| + root := os.Getenv("EQUIPO_PI_ROOT") |
| + if root == "" { |
| + testci.Absent(t, "the pinned Pi (EQUIPO_PI_ROOT) is absent") |
| + } |
| + testci.Tools(t, "pi") |
| + node, tree := pi.Paths(root) |
| + inst, ok := pi.Install{Node: node, Tree: tree}.Pinned() |
| + if !ok { |
| + t.Skip("no Pi pins for this platform") |
| + } |
| + return inst |
| +} |
| + |
| +func newPiRig(t *testing.T, inst pi.Install, budget wire.Budget) *piRig { |
| + t.Helper() |
| + testci.Tools(t, "bwrap", "git") |
| + if _, err := os.Stat("/usr/bin/bwrap"); err != nil { |
| + testci.Absent(t, "bubblewrap is absent") |
| + } |
| + // A short root: the tool socket's path must fit a socket address. |
| + root, err := os.MkdirTemp("", "pi-") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(root) }) |
| + for _, d := range []string{"state", "work", "scratch", "sessions", "bin", "clones"} { |
| + if err := os.MkdirAll(filepath.Join(root, d), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // The repository: main at base, the task branch one change on. |
| + seed := filepath.Join(root, "seed") |
| + gitOut(t, root, "init", "-q", "-b", "main", seed) |
| + os.WriteFile(filepath.Join(seed, "README.md"), []byte("teh panes\n"), 0644) |
| + gitOut(t, seed, "add", "-A") |
| + gitOut(t, seed, "commit", "-q", "-m", "base") |
| + base := gitOut(t, seed, "rev-parse", "HEAD") |
| + gitOut(t, seed, "checkout", "-q", "-b", "equipo/tk1-fix-typo") |
| + os.WriteFile(filepath.Join(seed, "README.md"), []byte("the panes\n"), 0644) |
| + gitOut(t, seed, "commit", "-q", "-am", "fix") |
| + cand := gitOut(t, seed, "rev-parse", "HEAD") |
| + remote := filepath.Join(root, "remote.git") |
| + gitOut(t, root, "clone", "-q", "--bare", seed, remote) |
| + state, err := OpenState(context.Background(), filepath.Join(root, "state")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { state.Close() }) |
| + // Engineering's connection: Claude, limited now. |
| + home := filepath.Join(root, "accounts", "claude-a") |
| + os.MkdirAll(home, 0700) |
| + identity := map[string]string{"account_id": "a@example.com", "home_id": "h-a", "provider_version": "1"} |
| + raw, _ := json.Marshal([]map[string]any{{"id": "claude-a", "local_id": "claude-a", "label": "claude-a", "person_id": connPerson, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": "a@example.com", "provider_home": home, "kind": "subscription", "expected_identity": identity}}) |
| + bindings := filepath.Join(root, "bindings.json") |
| + os.WriteFile(bindings, raw, 0600) |
| + self, _ := os.Executable() |
| + cfg := runner.Config{AccountBindingsPath: bindings, ClaudePath: "/bin/true", CodexPath: "/bin/true", StateDir: filepath.Join(root, "state"), WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", BwrapPath: "/usr/bin/bwrap", ToolProxyPath: copySelf(t, filepath.Join(root, "bin"), "equipo-tool-proxy")} |
| + m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: cfg.ScratchRoot}) |
| + if err != nil { |
| + testci.Absent(t, "namespaces are unavailable: "+err.Error()) |
| + } |
| + conns := &Conns{Runner: cfg, State: state} |
| + conns.Meter = &metered.Meter{DB: state.db} |
| + conns.Validated("claude-a") |
| + conns.Limit("claude-a", connect.Limit{Limited: true, ResetsAt: time.Now().Add(time.Hour)}) |
| + // The metered connection, its key 0600 in its home. |
| + keyHome := filepath.Join(root, "accounts", piLocal) |
| + os.MkdirAll(keyHome, 0700) |
| + if err := os.WriteFile(filepath.Join(keyHome, provider.TokenFile), []byte(fakepi.TestKey), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + t.Cleanup(cancel) |
| + err = state.tx(ctx, func(tx *sql.Tx) error { |
| + if err := metered.Add(ctx, tx, metered.Conn{Connection: "cn_tx", LocalID: piLocal, Person: connPerson, Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: keyHome, Currency: "USD", PriceVersion: metered.Current[wire.ProviderTensorX], Budget: budget}, time.Now()); err != nil { |
| + return err |
| + } |
| + return metered.Checked(ctx, tx, piLocal, true) |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f := &hubForge{dir: remote} |
| + e := &Engineer{O: ClaudeOptions{Runner: cfg, Manager: m, State: state, SessionRoot: filepath.Join(root, "sessions"), Logger: slog.New(slog.NewTextHandler(testWriter{t}, nil))}, Clones: &Clones{Root: filepath.Join(root, "clones"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{connPerson}, MaxStep: 2 * time.Minute, Conns: conns, Pi: PiOptions{Install: inst}, Host: "test"} |
| + review := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk1", StepID: "rv1", Attempt: 1, Specialist: wire.SpecialistReview, Repo: "amadan.net/oficina/sample", Branch: "equipo/tk1-fix-typo", BaseSHA: base, CandidateSHA: cand, AvoidAccount: "claude-a", Title: "Fix the typo", Findings: []wire.Finding{}}} |
| + return &piRig{t: t, ctx: ctx, e: e, state: state, conns: conns, review: review} |
| +} |
| + |
| +// leave grants every step leave to spend while the test runs (S3 gives |
| +// steps their own: an urgent task or a released step). |
| +func leave(t *testing.T) { |
| + was := testLeaveToSpend |
| + testLeaveToSpend = func(stepRow) bool { return true } |
| + t.Cleanup(func() { testLeaveToSpend = was }) |
| +} |
| + |
| +func (r *piRig) runReview(brief string, attempt int64) wire.StepReport { |
| + r.t.Helper() |
| + row := r.review |
| + // One running step per task: each run is its own task's. |
| + row.Brief, row.StepID, row.TaskID = brief, row.StepID+"-"+itoa(attempt), row.TaskID+"-"+itoa(attempt) |
| + if err := r.state.AcceptDispatch(r.ctx, "f-"+row.StepID, row.DispatchCommand); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return r.e.review(r.ctx, row, func(wire.StepReport) {}) |
| +} |
| + |
| +func (r *piRig) conn() metered.Conn { |
| + r.t.Helper() |
| + c, ok, err := metered.Get(r.ctx, r.state.db, piLocal) |
| + if err != nil || !ok { |
| + r.t.Fatal(err) |
| + } |
| + return c |
| +} |
| + |
| +func (r *piRig) charges() int { |
| + var n int |
| + if err := r.state.db.QueryRow("SELECT count(*) FROM budget_charge WHERE connection=?", piLocal).Scan(&n); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +func (r *piRig) slotFree() bool { |
| + var holder string |
| + if err := r.state.db.QueryRow("SELECT holder FROM metered_slot WHERE local_id=?", piLocal).Scan(&holder); err != nil && err != sql.ErrNoRows { |
| + r.t.Fatal(err) |
| + } |
| + return holder == "" |
| +} |
| + |
| +var bigBudget = wire.Budget{Day: 1_000_000, Month: 10_000_000, Revision: 1} |
| + |
| +// A Review step of a Claude change runs on TensorX through Pi when the |
| +// step has leave to spend and no subscription can review: other_family, |
| +// judged on the model that ran (glm), its verdict through Equipo's |
| +// tool, its usage priced and charged once, the slot released after the |
| +// proof, and its session kept so the person can ask it. |
| +func TestPiReviewStep(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), bigBudget) |
| + leave(t) |
| + rep := r.runReview("", 1) |
| + if rep.State != wire.StepDone || rep.Verdict != wire.VerdictApprove || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "glm" || rep.Account != piLocal || !rep.Termination { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if !rep.Askable { |
| + t.Fatal("the session was not kept for questions") |
| + } |
| + if len(rep.Usage) != 1 || rep.Usage[0].Provider != wire.ProviderTensorX || rep.Usage[0].Connection != piLocal || !rep.Usage[0].Complete || rep.Usage[0].CostMicros == nil || *rep.Usage[0].CostMicros <= 0 { |
| + t.Fatalf("usage %+v", rep.Usage) |
| + } |
| + if n := r.charges(); n != 1 || !r.slotFree() || r.conn().SpendUnknown { |
| + t.Fatalf("charges %d, slot free %v, spend unknown %v", n, r.slotFree(), r.conn().SpendUnknown) |
| + } |
| + // A resent usage row charges once. |
| + if err := r.conns.Meter.Finish(r.ctx, piLocal, metered.Holder{Step: "rv1-1", Attempt: 1, Role: metered.RoleReview}, metered.Result{Usage: rep.Usage}, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := r.charges(); n != 1 { |
| + t.Fatalf("a resent row charged again: %d", n) |
| + } |
| +} |
| + |
| +// Without leave to spend (every step until S3), Review is never chosen |
| +// onto the metered connection: with Engineering's connection limited it |
| +// waits, deferred, and nothing runs. |
| +func TestPiReviewWithoutLeaveToSpend(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), bigBudget) |
| + rep := r.runReview("", 1) |
| + if rep.State != stepDeferred || r.charges() != 0 { |
| + t.Fatalf("report %+v, charges %d", rep, r.charges()) |
| + } |
| +} |
| + |
| +// The budget stops the next step: once the reported spend reaches it, |
| +// the next Review is held (deferred), not run. |
| +func TestPiBudgetHoldsTheNextStep(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), wire.Budget{Day: 1, Month: 1_000, Revision: 1}) |
| + leave(t) |
| + if rep := r.runReview("", 1); rep.State != wire.StepDone { |
| + t.Fatalf("first: %+v", rep) |
| + } |
| + rep := r.runReview("", 2) |
| + if rep.State != stepDeferred || r.charges() != 1 { |
| + t.Fatalf("after the budget: %+v, charges %d", rep, r.charges()) |
| + } |
| +} |
| + |
| +// A step with no usage figure (Pi ended before its message_end) pauses |
| +// the connection: spend unknown, and nothing more is admitted. |
| +func TestPiNoUsagePausesTheConnection(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), bigBudget) |
| + leave(t) |
| + rep := r.runReview("nousage", 1) |
| + if rep.State != wire.StepFailed || !r.conn().SpendUnknown || !r.slotFree() { |
| + t.Fatalf("report %s %s, spend unknown %v slot free %v", rep.State, rep.Reason, r.conn().SpendUnknown, r.slotFree()) |
| + } |
| + if rep := r.runReview("", 2); rep.State != stepDeferred { |
| + t.Fatalf("admitted while spend unknown: %+v", rep) |
| + } |
| +} |
| + |
| +// A key TensorX refuses (a revoked key, or a balance under $0.05) marks |
| +// the connection refused: sign in again, never limited. |
| +func TestPiKeyRefused(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), bigBudget) |
| + leave(t) |
| + rep := r.runReview("keyrefused", 1) |
| + if rep.State == wire.StepDone || !r.conn().Refused { |
| + t.Fatalf("report %+v, refused %v", rep, r.conn().Refused) |
| + } |
| + if rep.Switched == nil || rep.Switched.From != wire.ProviderTensorX { |
| + t.Fatalf("switched %+v", rep.Switched) |
| + } |
| +} |
| + |
| +// The S2 finish line, in CI: the same Review step with the real pinned |
| +// Pi against a fake TensorX on 127.0.0.1, recorded other_family. |
| +func TestPiReviewStepRealPi(t *testing.T) { |
| + inst := realPiInstall(t) |
| + tensorx := fakepi.StartTensorX(t) |
| + was := testPiCA |
| + testPiCA = func() string { return tensorx.CA } |
| + t.Cleanup(func() { testPiCA = was }) |
| + r := newPiRig(t, inst, bigBudget) |
| + leave(t) |
| + rep := r.runReview("", 1) |
| + if rep.State != wire.StepDone || rep.Verdict != wire.VerdictApprove || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "glm" || !strings.Contains(rep.Summary, "TensorX") { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if len(rep.Usage) != 1 || !rep.Usage[0].Complete || rep.Usage[0].CostMicros == nil || r.charges() != 1 || !r.slotFree() { |
| + t.Fatalf("usage %+v charges %d", rep.Usage, r.charges()) |
| + } |
| + seen := tensorx.Seen() |
| + if len(seen) == 0 || seen[0].Auth != "Bearer "+fakepi.TestKey { |
| + t.Fatalf("provider saw %+v", seen) |
| + } |
| + for _, req := range seen { |
| + for _, tool := range req.Tools { |
| + if tool == "bash" || tool == "write" || tool == "edit" { |
| + t.Fatalf("Review declared %v", req.Tools) |
| + } |
| + } |
| + } |
| + // A question resumes the Review's own session on its connection: Pi |
| + // sends the Review's history with it. |
| + a := askRow{AskCommand: wire.AskCommand{Person: connPerson, TaskID: rep.TaskID, StepID: rep.StepID, QuestionID: "q1", Attempt: 1, Specialist: wire.SpecialistReview, Repo: r.review.Repo, Branch: r.review.Branch, BaseSHA: r.review.BaseSHA, CandidateSHA: r.review.CandidateSHA, Title: "Fix the typo", Text: "Why approve?"}} |
| + if err := r.state.AcceptAsk(r.ctx, "f-q1", a.AskCommand); err != nil { |
| + t.Fatal(err) |
| + } |
| + se := &StepEngine{State: r.state, Meter: r.conns.Meter, MeteredAsk: r.e.askPi, Notify: func() {}} |
| + se.askMetered(r.ctx, r.ctx, a, piLocal, func(wire.AnswerReport) {}) |
| + after := tensorx.Seen() |
| + if len(after) <= len(seen) || after[len(after)-1].Messages <= seen[len(seen)-1].Messages || r.charges() != 2 { |
| + t.Fatalf("the question did not resume the session: %d then %d messages, charges %d", seen[len(seen)-1].Messages, after[len(after)-1].Messages, r.charges()) |
| + } |
| +} |
| + |
| +func sha256Hex(raw []byte) string { |
| + sum := sha256.Sum256(raw) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +// testWriter sends the runner's log lines to the test's log. |
| +type testWriter struct{ t *testing.T } |
| + |
| +func (w testWriter) Write(p []byte) (int, error) { |
| + w.t.Log(strings.TrimSpace(string(p))) |
| + return len(p), nil |
| +} |
| + |
| +// A question about a Review that ran on Pi stays on its step's own |
| +// session and connection (connectors spec §7): through the metered |
| +// guard, the kept session resumed (Pi sees the review in it), the |
| +// answer charged. |
| +func TestPiAskKeptSession(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), bigBudget) |
| + leave(t) |
| + rep := r.runReview("", 1) |
| + if !rep.Askable { |
| + t.Fatalf("not askable: %+v", rep) |
| + } |
| + a := askRow{AskCommand: wire.AskCommand{Person: connPerson, TaskID: rep.TaskID, StepID: rep.StepID, QuestionID: "q1", Attempt: 1, Specialist: wire.SpecialistReview, Repo: r.review.Repo, Branch: r.review.Branch, BaseSHA: r.review.BaseSHA, CandidateSHA: r.review.CandidateSHA, Title: "Fix the typo", Text: "Why approve?"}} |
| + if err := r.state.AcceptAsk(r.ctx, "f-q1", a.AskCommand); err != nil { |
| + t.Fatal(err) |
| + } |
| + se := &StepEngine{State: r.state, Meter: r.conns.Meter, MeteredAsk: r.e.askPi, Notify: func() {}} |
| + local, ok := se.meteredAsk(r.ctx, a) |
| + if !ok || local != piLocal { |
| + t.Fatalf("the question is not on its metered connection: %q %v", local, ok) |
| + } |
| + se.askMetered(r.ctx, r.ctx, a, local, func(wire.AnswerReport) {}) |
| + frames, _, err := r.state.Unacked(r.ctx, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var answer wire.AnswerReport |
| + for _, f := range frames { |
| + var v wire.AnswerReport |
| + if f.Type == wire.FrameAnswer && json.Unmarshal(f.Data, &v) == nil && v.QuestionID == "q1" && v.State == wire.QuestionAnswered { |
| + answer = v |
| + } |
| + } |
| + if !strings.Contains(answer.Text, "message 2") || len(answer.Usage) != 1 || answer.Usage[0].CostMicros == nil { |
| + t.Fatalf("answer %+v", answer) |
| + } |
| + if n := r.charges(); n != 2 || !r.slotFree() { |
| + t.Fatalf("charges %d slot free %v", n, r.slotFree()) |
| + } |
| +} |
| + |
| +// Engineering on Pi: its tools inside the namespace, the workspace |
| +// writable, charged as an Engineering attempt. |
| +func TestPiEngineeringRun(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), bigBudget) |
| + work := t.TempDir() |
| + os.WriteFile(filepath.Join(work, "README.md"), []byte("teh panes\n"), 0644) |
| + b := r.conns.MeteredMine(r.ctx, connPerson) |
| + if len(b) != 1 || b[0].Family != "glm" || !Metered(b[0]) { |
| + t.Fatalf("metered bindings %+v", b) |
| + } |
| + row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk9", StepID: "en1", Attempt: 1, Specialist: wire.SpecialistEngineering}} |
| + res := r.e.run(r.ctx, row, workspace.TaskTree{Dir: work}, specialistRun{action: "implement", binding: b[0], tools: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, prompt: "[Equipo: engineering] edit:README.md|teh|the"}) |
| + raw, _ := os.ReadFile(filepath.Join(work, "README.md")) |
| + if res.reason != "" || !res.terminated || string(raw) != "the panes\n" { |
| + t.Fatalf("run %+v; README %q", res, raw) |
| + } |
| + var role string |
| + if err := r.state.db.QueryRow("SELECT holder FROM budget_charge WHERE connection=?", piLocal).Scan(&role); err != nil || !strings.HasPrefix(role, metered.RoleEngineering+"|") { |
| + t.Fatalf("charged as %q: %v", role, err) |
| + } |
| +} |
| + |
| +// Review's independence is judged on the model that ran (connectors spec |
| +// §3, "Families"): Engineering ran on this same TensorX connection (glm), |
| +// so Review there is the same account, unless another family's model |
| +// answered. |
| +func TestPiReviewFamilyFromTheModelThatRan(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), bigBudget) |
| + leave(t) |
| + r.review.AvoidAccount = piLocal |
| + if rep := r.runReview("", 1); rep.State != wire.StepDone || rep.ReviewLabel != wire.ReviewSameAccount || rep.Family != "glm" { |
| + t.Fatalf("same model: %+v", rep) |
| + } |
| + rep := r.runReview("answeredby:deepseek/deepseek-v4-pro-0813", 2) |
| + if rep.State != wire.StepDone || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "deepseek" { |
| + t.Fatalf("another model: %+v", rep) |
| + } |
| +} |
| + |
| +// In a step nobody can answer the extension's question: a call it asks |
| +// about is refused, and the step goes on. |
| +func TestPiStepRefusesAsks(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), bigBudget) |
| + leave(t) |
| + rep := r.runReview("read:/etc/hostname", 1) |
| + if rep.State != wire.StepDone || !strings.Contains(rep.LogTail, "Refused a call") || !strings.Contains(rep.LogTail, "read /etc/hostname refused") { |
| + t.Fatalf("report %+v", rep) |
| + } |
| +} |
| + |
| +// An Engineering step the metered guard holds waits, deferred: here the |
| +// budget, which the Review before it reached. |
| +func TestPiEngineeringHeldIsDeferred(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), wire.Budget{Day: 1, Month: 1_000, Revision: 1}) |
| + leave(t) |
| + if rep := r.runReview("", 1); rep.State != wire.StepDone { |
| + t.Fatalf("review: %+v", rep) |
| + } |
| + row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk5", StepID: "en5", Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: r.review.Repo, Branch: "equipo/tk5-x", BaseSHA: r.review.BaseSHA, Title: "Do the thing", Findings: []wire.Finding{}}} |
| + if err := r.state.AcceptDispatch(r.ctx, "f-en5", row.DispatchCommand); err != nil { |
| + t.Fatal(err) |
| + } |
| + row.Base = r.review.BaseSHA |
| + rep := r.e.Exec(r.ctx, row, func(wire.StepReport) {}) |
| + if rep.State != stepDeferred || r.charges() != 1 { |
| + t.Fatalf("report %+v, charges %d", rep, r.charges()) |
| + } |
| +} |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index b9879601..af44a1f7 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -1,6 +1,7 @@ |
| package thin |
| import ( |
| + "amadan.net/oficina/equipo/internal/runner/provider/pi" |
| "context" |
| "crypto/sha256" |
| "encoding/hex" |
| @@ -38,7 +39,10 @@ type Options struct { |
| Version string |
| Claude ClaudeOptions |
| // Codex configures Codex coordinator sessions (pinned digests). |
| - Codex CodexOptions |
| + Codex CodexOptions |
| + // Pi, in tests, is a fake Pi's install and digests; empty, the |
| + // runner's own (EQUIPO_PI_ROOT, the committed pins). |
| + Pi PiOptions |
| Logger *slog.Logger |
| // Connected observes the stream for tests. |
| Connected func(bool) |
| @@ -295,7 +299,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| if err = engine.Start(ctx); err != nil { |
| return err |
| } |
| - engineer := &Engineer{O: o.Claude, Codex: o.Codex, Clones: clones, Forge: fg, CI: hostedCIOf(fg), Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, ConfirmMerge: link.ConfirmMerge, ConfirmPreview: link.ConfirmPreview, Preview: preview, Devbox: devbox, ConfirmPublication: link.ConfirmPublication, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Note: o.StepNote, Healthy: conns.Usable, Conns: conns, Delta: link.Delta, Activity: link.Activity, StepActivity: link.StepActivity, Retention: o.KeptRetention, Host: c.MachineLabel, Merged: func(string) { index.Kick() }} |
| + engineer := &Engineer{O: o.Claude, Codex: o.Codex, Pi: piOptions(c, o.Pi), Clones: clones, Forge: fg, CI: hostedCIOf(fg), Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, ConfirmMerge: link.ConfirmMerge, ConfirmPreview: link.ConfirmPreview, Preview: preview, Devbox: devbox, ConfirmPublication: link.ConfirmPublication, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Note: o.StepNote, Healthy: conns.Usable, Conns: conns, Delta: link.Delta, Activity: link.Activity, StepActivity: link.StepActivity, Retention: o.KeptRetention, Host: c.MachineLabel, Merged: func(string) { index.Kick() }} |
| link.Forget = engineer.RemoveKept |
| link.TaskEnded = engineer.PreviewTaskEnded |
| if devbox != nil { |
| @@ -324,6 +328,9 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| // A change of a connection's standing also looks again at questions |
| // held by the metered guard. |
| steps.Meter = conns.Meter |
| + // A question on a step's kept Pi session runs through the guard on |
| + // its own connection (connectors spec §7, Ask). |
| + steps.MeteredAsk = engineer.askPi |
| wake := steps.MeteredChanged |
| wakeSteps.Store(&wake) |
| if err = steps.Start(ctx); err != nil { |
| @@ -697,3 +704,16 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl |
| } |
| return err |
| } |
| + |
| +// piOptions is the runner's Pi: the install at EQUIPO_PI_ROOT, held to |
| +// this platform's committed pins unless a test pins its fake's. |
| +func piOptions(c runner.Config, test PiOptions) PiOptions { |
| + if test.Install.Node != "" { |
| + return test |
| + } |
| + if c.PiRoot == "" { |
| + return PiOptions{} |
| + } |
| + node, tree := pi.Paths(c.PiRoot) |
| + return PiOptions{Install: pi.Install{Node: node, Tree: tree}} |
| +} |
diff --git a/internal/runner/thin/spend.go b/internal/runner/thin/spend.go| new file mode 100644 |
| index 00000000..e13cb828 |
| --- /dev/null |
| +++ b/internal/runner/thin/spend.go |
| @@ -0,0 +1,25 @@ |
| +package thin |
| + |
| +// leaveToSpend is a step's leave to spend metered money (connectors spec |
| +// §0 decision 5 and §7): an urgent task or a released step. Steps carry |
| +// neither until slice S3 adds priority and Run now, so it is false in |
| +// every release build: no step is chosen onto a metered connection. A |
| +// test build may grant it (spend_testbuild.go), for the Pi cells' tests. |
| +func leaveToSpend(r stepRow) bool { |
| + return testLeaveToSpend != nil && testLeaveToSpend(r) |
| +} |
| + |
| +// testLeaveToSpend is nil in every build but a test build. |
| +var testLeaveToSpend func(stepRow) bool |
| + |
| +// piTestCA is a test build's certificate authority for a fake provider |
| +// a real Pi talks to ("" in every release build: provider.BuildPiPolicy |
| +// refuses one there anyway). |
| +func piTestCA() string { |
| + if testPiCA == nil { |
| + return "" |
| + } |
| + return testPiCA() |
| +} |
| + |
| +var testPiCA func() string |
diff --git a/internal/runner/thin/spend_testbuild.go b/internal/runner/thin/spend_testbuild.go| new file mode 100644 |
| index 00000000..9c678470 |
| --- /dev/null |
| +++ b/internal/runner/thin/spend_testbuild.go |
| @@ -0,0 +1,15 @@ |
| +//go:build testbuild |
| + |
| +package thin |
| + |
| +import "os" |
| + |
| +// A test build grants leave to spend to every step while |
| +// EQUIPO_TEST_LEAVE_TO_SPEND is 1 (a real Pi Review on a fake TensorX, |
| +// before S3 gives steps their own leave). A release build never passes |
| +// -tags testbuild (scripts/no-fake-worker.sh refuses one that has it). |
| +func init() { |
| + testLeaveToSpend = func(stepRow) bool { return os.Getenv("EQUIPO_TEST_LEAVE_TO_SPEND") == "1" } |
| + // The fake provider's certificate authority (EQUIPO_TEST_PI_CA). |
| + testPiCA = func() string { return os.Getenv("EQUIPO_TEST_PI_CA") } |
| +} |