| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "io" |
| 10 | "os" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/runner" |
| 14 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 15 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 16 | "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| 17 | "amadan.net/oficina/equipo/internal/wire" |
| 18 | ) |
| 19 | |
| 20 | // A token connection's check. The pinned CLI's `auth status` says signed |
| 21 | // in for any token in its environment without asking the server, so only |
| 22 | // a real request tells a good token from a bad one: one minimal turn (a |
| 23 | // one-word reply) through the contained launch every turn uses, bounded |
| 24 | // by tokenCheckLimit, its usage reported like any other. |
| 25 | const ( |
| 26 | tokenCheckLimit = 90 * time.Second |
| 27 | tokenCheckPrompt = "Reply with the single word OK." |
| 28 | ) |
| 29 | |
| 30 | // errCheckFailed: no reply and no refusal (a stop, a timeout, a broken |
| 31 | // stream). It proves nothing about the token. |
| 32 | var errCheckFailed = errors.New("the token check did not finish") |
| 33 | |
| 34 | // TokenCheck is what one check learned: its usage rows, whatever the |
| 35 | // end, and the last rate limit the provider reported on it (nil: none), |
| 36 | // read from rate_limit_event as a turn reads it. |
| 37 | type TokenCheck struct { |
| 38 | Rows []wire.Usage |
| 39 | Seen *connect.Limit |
| 40 | // Named: the account profile read on it (profile.go) changed the |
| 41 | // connection's label. |
| 42 | Named bool |
| 43 | } |
| 44 | |
| 45 | // CheckToken runs one check. nil: the provider answered (a quota refusal |
| 46 | // answers too: the token is good, the account busy). ErrLoginRequired: |
| 47 | // the provider refused the token. Once the provider answered, the |
| 48 | // account profile is read when one is due (profile.go). |
| 49 | func (o ClaudeOptions) CheckToken(ctx context.Context, b runner.AccountBinding) (TokenCheck, error) { |
| 50 | rows, seen, named, err := o.checkToken(ctx, b) |
| 51 | return TokenCheck{Rows: rows, Seen: seen, Named: named}, err |
| 52 | } |
| 53 | |
| 54 | func (o ClaudeOptions) checkToken(ctx context.Context, b runner.AccountBinding) (_ []wire.Usage, _ *connect.Limit, named bool, err error) { |
| 55 | o.defaults() |
| 56 | if o.Mac != nil { |
| 57 | // A Mac: the darwin launch, token by descriptor (maccreds.go). |
| 58 | return o.Mac.checkToken(ctx, o, b) |
| 59 | } |
| 60 | if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken || o.Manager == nil { |
| 61 | return nil, nil, false, provider.ErrPolicy |
| 62 | } |
| 63 | parent := ctx |
| 64 | ctx, cancel := context.WithTimeout(ctx, tokenCheckLimit) |
| 65 | defer cancel() |
| 66 | direct, err := o.Runner.DirectBinding(b) |
| 67 | if err != nil { |
| 68 | return nil, nil, false, err |
| 69 | } |
| 70 | lease, err := provider.OpenRuntimeCopy(ctx, direct, o.Refresh, o.LockWait) |
| 71 | if err != nil { |
| 72 | return nil, nil, false, err |
| 73 | } |
| 74 | defer lease.Close() |
| 75 | binding := lease.Binding() |
| 76 | scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-") |
| 77 | if err != nil { |
| 78 | return nil, nil, false, err |
| 79 | } |
| 80 | defer os.RemoveAll(scratch) |
| 81 | // An empty workspace: the check reads nothing, and calls no tool. |
| 82 | work, err := os.MkdirTemp(o.SessionRoot, "check-") |
| 83 | if err != nil { |
| 84 | return nil, nil, false, err |
| 85 | } |
| 86 | defer os.RemoveAll(work) |
| 87 | tool, err := openToolSocket(context.Background(), o.Runner.StateDir, func(context.Context, string, string, json.RawMessage) (string, bool) { return toolNoTurn, true }) |
| 88 | if err != nil { |
| 89 | return nil, nil, false, err |
| 90 | } |
| 91 | defer tool.Close() |
| 92 | sel := provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID} |
| 93 | in, err := runner.PolicyInputs(ctx, o.Runner, sel, binding, work, "converse", scratch) |
| 94 | if err != nil { |
| 95 | return nil, nil, false, err |
| 96 | } |
| 97 | session := uuid() |
| 98 | in.Argv = append(in.Argv, "--session-id", session) |
| 99 | policy, err := provider.BuildPolicy(binding, in) |
| 100 | if err != nil { |
| 101 | return nil, nil, false, err |
| 102 | } |
| 103 | if claude.ExecutableDigest(policy) != o.Digest { |
| 104 | return nil, nil, false, provider.ErrVersion |
| 105 | } |
| 106 | if err = lease.CheckCopy(ctx); err != nil { |
| 107 | return nil, nil, false, err |
| 108 | } |
| 109 | launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "check/" + uuid(), Workspace: work, Selection: sel, Binding: binding, Policy: policy} |
| 110 | // The account profile, once the provider answered: read after the |
| 111 | // namespace is gone (the deferred kill below runs first) and before |
| 112 | // the lease, which holds the token, closes. The token goes from the |
| 113 | // lease's memory to the one request, and nowhere else. |
| 114 | defer func() { |
| 115 | if err != nil || o.Profile == nil { |
| 116 | return |
| 117 | } |
| 118 | if env, e := provider.LaunchSecretEnv(launch); e == nil { |
| 119 | token := []byte(env[provider.OAuthTokenEnv]) |
| 120 | named = o.readProfile(parent, b, token) |
| 121 | clear(token) |
| 122 | } |
| 123 | }() |
| 124 | pctx, kill := context.WithCancel(context.Background()) |
| 125 | defer kill() |
| 126 | proc, err := o.Manager.StartRecorded(pctx, launch, in.Argv, nil) |
| 127 | if err != nil { |
| 128 | return nil, nil, false, err |
| 129 | } |
| 130 | // The namespace is killed at the limit (which ends the reads below) |
| 131 | // and at the end; its exit is observed and its record released before |
| 132 | // the copy goes. |
| 133 | exited := make(chan struct{}) |
| 134 | go func() { defer close(exited); _, _ = proc.Wait(context.Background()) }() |
| 135 | stop := context.AfterFunc(ctx, kill) |
| 136 | defer func() { |
| 137 | stop() |
| 138 | kill() |
| 139 | select { |
| 140 | case <-exited: |
| 141 | case <-time.After(30 * time.Second): |
| 142 | } |
| 143 | (&coordBase{o: o}).forget(proc.ID()) |
| 144 | }() |
| 145 | rows, seen, err := readCheck(ctx, proc, session, b) |
| 146 | return rows, seen, false, err |
| 147 | } |
| 148 | |
| 149 | // readCheck sends the check's one prompt to proc and reads its stream to |
| 150 | // the result, bounded by ctx: the usage rows and the last rate limit the |
| 151 | // provider reported. nil: the provider answered (a quota refusal |
| 152 | // answers too); ErrLoginRequired: it refused the token; errCheckFailed |
| 153 | // (or ctx's error): no answer, which proves nothing about the token. |
| 154 | func readCheck(ctx context.Context, proc provider.Process, session string, b runner.AccountBinding) ([]wire.Usage, *connect.Limit, error) { |
| 155 | go func() { _, _ = io.Copy(io.Discard, io.LimitReader(proc.Stderr(), 1<<20)) }() |
| 156 | raw, err := claude.UserContent(session, tokenCheckPrompt, nil) |
| 157 | if err == nil { |
| 158 | _, err = proc.Stdin().Write(raw) |
| 159 | } |
| 160 | if err != nil { |
| 161 | return nil, nil, firstErr(ctx.Err(), errCheckFailed) |
| 162 | } |
| 163 | scan := bufio.NewScanner(proc.Stdout()) |
| 164 | scan.Buffer(make([]byte, 0, 64<<10), claude.MaxFrameBytes) |
| 165 | signal := "" |
| 166 | // seen is the last rate limit the provider reported, read as a turn |
| 167 | // reads it (claude.go). |
| 168 | var seen *connect.Limit |
| 169 | for scan.Scan() { |
| 170 | events, err := claude.Decode(scan.Bytes()) |
| 171 | if len(scan.Bytes()) > 0 && err != nil { |
| 172 | break |
| 173 | } |
| 174 | for _, ev := range events { |
| 175 | if sig := connect.ClaudeSignal(ev.Payload); sig != "" { |
| 176 | signal = sig |
| 177 | } |
| 178 | if ev.Kind == "rate_limit_event" { |
| 179 | if l, ok := connect.ClaudeRateLimit(ev.Payload); ok { |
| 180 | seen = &l |
| 181 | } |
| 182 | continue |
| 183 | } |
| 184 | if ev.Kind != "turn.completed" && ev.Kind != "turn.failed" { |
| 185 | continue |
| 186 | } |
| 187 | res, ok := claude.ParseResult(ev.Payload) |
| 188 | outcome := wire.OutcomeReplied |
| 189 | if !ok || res.Failed { |
| 190 | outcome = wire.OutcomeFailed |
| 191 | } |
| 192 | if outcome == wire.OutcomeFailed && signal == connect.FailQuota && (seen == nil || !seen.Limited) { |
| 193 | // Rate-limit retries ran out: quota, no reset reported. |
| 194 | seen = &connect.Limit{Limited: true} |
| 195 | } |
| 196 | rows := usageRows(connect.ClaudeRows(ev.Payload), b, 1, outcome) |
| 197 | switch { |
| 198 | case signal == connect.FailAuth: |
| 199 | return rows, nil, provider.ErrLoginRequired |
| 200 | case outcome == wire.OutcomeReplied, signal == connect.FailQuota, seen != nil && seen.Limited: |
| 201 | // A rejected rate limit is the provider's answer too. |
| 202 | return rows, seen, nil |
| 203 | } |
| 204 | return rows, seen, errCheckFailed |
| 205 | } |
| 206 | } |
| 207 | return nil, nil, firstErr(ctx.Err(), errCheckFailed) |
| 208 | } |
| 209 | |
| 210 | // ReportCheck queues a check's usage for the instance (durable). |
| 211 | func (s *State) ReportCheck(ctx context.Context, rows []wire.Usage) error { |
| 212 | if len(rows) == 0 { |
| 213 | return nil |
| 214 | } |
| 215 | return s.tx(ctx, func(t *sql.Tx) error { |
| 216 | return s.enqueue(t, wire.FrameUsage, "", wire.UsageReport{CheckID: "chk_" + uuid(), Rows: rows}) |
| 217 | }) |
| 218 | } |
| 219 | |