package thin import ( "bufio" "context" "database/sql" "encoding/json" "errors" "io" "os" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/wire" ) // A token connection's check. The pinned CLI's `auth status` says signed // in for any token in its environment without asking the server, so only // a real request tells a good token from a bad one: one minimal turn (a // one-word reply) through the contained launch every turn uses, bounded // by tokenCheckLimit, its usage reported like any other. const ( tokenCheckLimit = 90 * time.Second tokenCheckPrompt = "Reply with the single word OK." ) // errCheckFailed: no reply and no refusal (a stop, a timeout, a broken // stream). It proves nothing about the token. var errCheckFailed = errors.New("the token check did not finish") // TokenCheck is what one check learned: its usage rows, whatever the // end, and the last rate limit the provider reported on it (nil: none), // read from rate_limit_event as a turn reads it. type TokenCheck struct { Rows []wire.Usage Seen *connect.Limit // Named: the account profile read on it (profile.go) changed the // connection's label. Named bool } // CheckToken runs one check. nil: the provider answered (a quota refusal // answers too: the token is good, the account busy). ErrLoginRequired: // the provider refused the token. Once the provider answered, the // account profile is read when one is due (profile.go). func (o ClaudeOptions) CheckToken(ctx context.Context, b runner.AccountBinding) (TokenCheck, error) { rows, seen, named, err := o.checkToken(ctx, b) return TokenCheck{Rows: rows, Seen: seen, Named: named}, err } func (o ClaudeOptions) checkToken(ctx context.Context, b runner.AccountBinding) (_ []wire.Usage, _ *connect.Limit, named bool, err error) { o.defaults() if o.Mac != nil { // A Mac: the darwin launch, token by descriptor (maccreds.go). return o.Mac.checkToken(ctx, o, b) } if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken || o.Manager == nil { return nil, nil, false, provider.ErrPolicy } parent := ctx ctx, cancel := context.WithTimeout(ctx, tokenCheckLimit) defer cancel() direct, err := o.Runner.DirectBinding(b) if err != nil { return nil, nil, false, err } lease, err := provider.OpenRuntimeCopy(ctx, direct, o.Refresh, o.LockWait) if err != nil { return nil, nil, false, err } defer lease.Close() binding := lease.Binding() scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-") if err != nil { return nil, nil, false, err } defer os.RemoveAll(scratch) // An empty workspace: the check reads nothing, and calls no tool. work, err := os.MkdirTemp(o.SessionRoot, "check-") if err != nil { return nil, nil, false, err } defer os.RemoveAll(work) tool, err := openToolSocket(context.Background(), o.Runner.StateDir, func(context.Context, string, string, json.RawMessage) (string, bool) { return toolNoTurn, true }) if err != nil { return nil, nil, false, err } defer tool.Close() sel := provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID} in, err := runner.PolicyInputs(ctx, o.Runner, sel, binding, work, "converse", scratch) if err != nil { return nil, nil, false, err } session := uuid() in.Argv = append(in.Argv, "--session-id", session) policy, err := provider.BuildPolicy(binding, in) if err != nil { return nil, nil, false, err } if claude.ExecutableDigest(policy) != o.Digest { return nil, nil, false, provider.ErrVersion } if err = lease.CheckCopy(ctx); err != nil { return nil, nil, false, err } launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "check/" + uuid(), Workspace: work, Selection: sel, Binding: binding, Policy: policy} // The account profile, once the provider answered: read after the // namespace is gone (the deferred kill below runs first) and before // the lease, which holds the token, closes. The token goes from the // lease's memory to the one request, and nowhere else. defer func() { if err != nil || o.Profile == nil { return } if env, e := provider.LaunchSecretEnv(launch); e == nil { token := []byte(env[provider.OAuthTokenEnv]) named = o.readProfile(parent, b, token) clear(token) } }() pctx, kill := context.WithCancel(context.Background()) defer kill() proc, err := o.Manager.StartRecorded(pctx, launch, in.Argv, nil) if err != nil { return nil, nil, false, err } // The namespace is killed at the limit (which ends the reads below) // and at the end; its exit is observed and its record released before // the copy goes. exited := make(chan struct{}) go func() { defer close(exited); _, _ = proc.Wait(context.Background()) }() stop := context.AfterFunc(ctx, kill) defer func() { stop() kill() select { case <-exited: case <-time.After(30 * time.Second): } (&coordBase{o: o}).forget(proc.ID()) }() rows, seen, err := readCheck(ctx, proc, session, b) return rows, seen, false, err } // readCheck sends the check's one prompt to proc and reads its stream to // the result, bounded by ctx: the usage rows and the last rate limit the // provider reported. nil: the provider answered (a quota refusal // answers too); ErrLoginRequired: it refused the token; errCheckFailed // (or ctx's error): no answer, which proves nothing about the token. func readCheck(ctx context.Context, proc provider.Process, session string, b runner.AccountBinding) ([]wire.Usage, *connect.Limit, error) { go func() { _, _ = io.Copy(io.Discard, io.LimitReader(proc.Stderr(), 1<<20)) }() raw, err := claude.UserContent(session, tokenCheckPrompt, nil) if err == nil { _, err = proc.Stdin().Write(raw) } if err != nil { return nil, nil, firstErr(ctx.Err(), errCheckFailed) } scan := bufio.NewScanner(proc.Stdout()) scan.Buffer(make([]byte, 0, 64<<10), claude.MaxFrameBytes) signal := "" // seen is the last rate limit the provider reported, read as a turn // reads it (claude.go). var seen *connect.Limit for scan.Scan() { events, err := claude.Decode(scan.Bytes()) if len(scan.Bytes()) > 0 && err != nil { break } for _, ev := range events { if sig := connect.ClaudeSignal(ev.Payload); sig != "" { signal = sig } if ev.Kind == "rate_limit_event" { if l, ok := connect.ClaudeRateLimit(ev.Payload); ok { seen = &l } continue } if ev.Kind != "turn.completed" && ev.Kind != "turn.failed" { continue } res, ok := claude.ParseResult(ev.Payload) outcome := wire.OutcomeReplied if !ok || res.Failed { outcome = wire.OutcomeFailed } if outcome == wire.OutcomeFailed && signal == connect.FailQuota && (seen == nil || !seen.Limited) { // Rate-limit retries ran out: quota, no reset reported. seen = &connect.Limit{Limited: true} } rows := usageRows(connect.ClaudeRows(ev.Payload), b, 1, outcome) switch { case signal == connect.FailAuth: return rows, nil, provider.ErrLoginRequired case outcome == wire.OutcomeReplied, signal == connect.FailQuota, seen != nil && seen.Limited: // A rejected rate limit is the provider's answer too. return rows, seen, nil } return rows, seen, errCheckFailed } } return nil, nil, firstErr(ctx.Err(), errCheckFailed) } // ReportCheck queues a check's usage for the instance (durable). func (s *State) ReportCheck(ctx context.Context, rows []wire.Usage) error { if len(rows) == 0 { return nil } return s.tx(ctx, func(t *sql.Tx) error { return s.enqueue(t, wire.FrameUsage, "", wire.UsageReport{CheckID: "chk_" + uuid(), Rows: rows}) }) }