Skip to content

akiiwa-games/AgentCompass / skills/agent-compass

agent-compass

Flagged

Choose owner, model and effort, outbound authorization, advisor use, and continuation for delegated work. Reads local usage and effective account policy, profiles the task with the configured System-One scorer, then allocates a compatible worker. Use for independent worker or advisor work; ordinary local execution needs no routing.

FileKindSize
SKILL.mdskill md5.5 KB
agents/openai.yamlconfig427 B
calibration/README.mdmarkdown55.2 KB
calibration/arena_capture.pyscript14.0 KB
calibration/community.pyscript25.2 KB
calibration/five_axis.pyscript196.4 KB
calibration/measurements.pyscript68.4 KB
calibration/refresh.pyscript48.6 KB
calibration/series.pyscript10.2 KB
calibration/sources.pyscript24.1 KB
calibration/tiers.pyscript14.6 KB
grok-bot/.gitignoreother47 B
grok-bot/dependency_patch.pyscript4.5 KB
grok-bot/install_cli.pyscript3.6 KB
grok-bot/test-recovery.mjsscript8.6 KB
grok-bot/test_install_cli.pyscript4.1 KB
grok-bot/upstream.jsonconfig3.4 KB
references/accounts.jsonconfig155.9 KB
references/classifier-cases.jsonconfig21.5 KB
references/dispatch-lifecycle.mdmarkdown28.9 KB
references/dispatch-rules.mdmarkdown11.3 KB
references/effort-matching.mdmarkdown5.1 KB
references/fast-modes.mdmarkdown3.5 KB
references/five-axis-scores.jsonconfig3.1 MB
references/gemini-decisions-api.mdmarkdown2.9 KB
references/grok-bot.mdmarkdown13.0 KB
references/herdr.mdmarkdown5.1 KB
references/jev-api.mdmarkdown1.6 KB
references/level-3-conversion.jsonconfig2.4 KB
references/model-capabilities.jsonconfig3.6 KB
references/model-capabilities.mdmarkdown14.6 KB
references/parent-address-gate.mdmarkdown10.1 KB
references/plan-templates.jsonconfig13.2 KB
references/provider-discovery.mdmarkdown11.5 KB
references/provider-usage.mdmarkdown4.1 KB
references/public-data.jsonconfig816 B
references/public-measurements.jsonconfig1.3 MB
references/roll-reference.mdmarkdown26.7 KB
references/router-internals.mdmarkdown93.7 KB
references/task-classifier.mdmarkdown6.1 KB
references/user-scores.jsonconfig6.8 KB
references/work-kinds.mdmarkdown4.7 KB
references/worker-communication.mdmarkdown2.1 KB
scripts/account_fleet.pyscript32.9 KB
scripts/account_state.pyscript22.2 KB
scripts/accounts_override.pyscript14.8 KB
scripts/allocator.pyscript19.8 KB
scripts/antigravity_plan.pyscript18.7 KB
scripts/antigravity_telemetry.pyscript5.1 KB
scripts/auto_bundles.pyscript31.3 KB
scripts/axis_scores.pyscript40.3 KB
scripts/caller_input.pyscript3.0 KB
scripts/candidate_eval.pyscript54.0 KB
scripts/candidate_ranking.pyscript9.5 KB
scripts/capability_catalog.pyscript8.0 KB
scripts/check_router_contract.pyscript2.8 KB
scripts/conftest.pyscript2.5 KB
scripts/cwd_policy.pyscript1.5 KB
scripts/data_age.pyscript1.5 KB
scripts/decision_ledger.pyscript18.9 KB
scripts/demo_plan.pyscript6.3 KB
scripts/dispatch_fallback.pyscript40.3 KB
scripts/dispatch_flow.pyscript58.7 KB
scripts/dispatch_ground_truth.pyscript43.5 KB
scripts/dispatch_registry.pyscript113.7 KB
scripts/entry.pyscript1.7 KB
scripts/env_vars.pyscript580 B
scripts/fast_modes.pyscript2.5 KB
scripts/fixtures/grok-api-responses.jsonconfig907 B
scripts/fixtures/reference-accounts.jsonconfig26.9 KB
scripts/grok_bot_paths.pyscript1005 B
scripts/host_herdr.pyscript16.8 KB
scripts/host_placement.pyscript9.4 KB
scripts/host_policy.pyscript10.1 KB
scripts/launch_failures.pyscript5.9 KB
scripts/launch_values.pyscript12.3 KB
scripts/ledger_snapshot.pyscript11.1 KB
scripts/live_models.pyscript21.1 KB
scripts/model_latch.pyscript7.6 KB
scripts/model_resolution.pyscript18.0 KB
scripts/override_store.pyscript2.2 KB
scripts/plan_state_residue.pyscript5.0 KB
scripts/provider_inventory.pyscript128.2 KB
scripts/provider_retry.pyscript34.6 KB
scripts/public_data.pyscript59.2 KB
scripts/quota_economy.pyscript38.0 KB
scripts/quota_exhaustion.pyscript5.9 KB
scripts/quota_overrides.pyscript25.6 KB
scripts/quota_pools.pyscript29.8 KB
scripts/reference_provenance.pyscript32.3 KB
scripts/released_names.pyscript3.8 KB
scripts/roll.pyscript106.3 KB
scripts/route_judge.pyscript83.4 KB
scripts/route_simulation.pyscript26.3 KB
scripts/router_test_support.pyscript6.7 KB
scripts/run_grok_bot.pyscript18.8 KB
scripts/scorer_client.pyscript55.2 KB
scripts/stage_help.pyscript5.8 KB
scripts/state_upgrade.pyscript24.0 KB
scripts/subscription_cli.pyscript3.6 KB
scripts/task_intake.pyscript33.6 KB
scripts/test_account_identity.pyscript7.1 KB
scripts/test_account_state.pyscript63.3 KB
scripts/test_accounts_override.pyscript30.1 KB
scripts/test_allocator.pyscript94.2 KB
scripts/test_antigravity_plan.pyscript13.2 KB
scripts/test_applicable_quota.pyscript9.1 KB
scripts/test_auto_bundles.pyscript10.8 KB
scripts/test_billing_routing_policy.pyscript9.9 KB
scripts/test_cadence_count.pyscript32.2 KB
scripts/test_calibration_units.pyscript27.0 KB
scripts/test_capability_catalog.pyscript5.0 KB
scripts/test_decision_ledger.pyscript8.5 KB
scripts/test_demo_plan.pyscript3.4 KB
scripts/test_derived_state.pyscript21.6 KB
scripts/test_dispatch.pyscript322.3 KB
scripts/test_dispatch_answers.pyscript14.8 KB
scripts/test_dispatch_fallback.pyscript53.2 KB
scripts/test_entry.pyscript1.6 KB
scripts/test_fast_modes.pyscript9.9 KB
scripts/test_five_axis.pyscript290.1 KB
scripts/test_five_axis_economy.pyscript105.0 KB
scripts/test_fleet_parity.pyscript15.6 KB
scripts/test_grok_bot.pyscript47.7 KB
scripts/test_ground_truth_recording.pyscript68.8 KB
scripts/test_herdr.pyscript14.1 KB
scripts/test_host_policy.pyscript24.6 KB
scripts/test_launch_values.pyscript8.0 KB
scripts/test_metered_usd.pyscript60.4 KB
scripts/test_model_resolution.pyscript9.2 KB
scripts/test_named_route_facts.pyscript28.6 KB
scripts/test_native_hosts.pyscript6.0 KB
scripts/test_new_user_fleet.pyscript3.3 KB
scripts/test_no_hardcode_classification.pyscript75.1 KB
scripts/test_no_legacy_scoring.pyscript6.5 KB
scripts/test_override_store.pyscript2.3 KB
scripts/test_plan_says_why.pyscript44.9 KB
scripts/test_provider_inventory.pyscript83.2 KB
scripts/test_provider_names.pyscript126.0 KB
scripts/test_provider_pools.pyscript14.2 KB
scripts/test_public_data.pyscript93.5 KB
scripts/test_quota_exhaustion.pyscript5.6 KB
scripts/test_rate_limit_windows.pyscript6.3 KB
scripts/test_record_says_why.pyscript26.5 KB
scripts/test_reference_provenance.pyscript16.7 KB
scripts/test_refresh_entry.pyscript110.7 KB
scripts/test_released_names.pyscript4.1 KB
scripts/test_reset_priority.pyscript4.8 KB
scripts/test_roll_answers.pyscript44.7 KB
scripts/test_roll_notifications.pyscript10.4 KB
scripts/test_route_judge.pyscript99.8 KB
scripts/test_route_simulation.pyscript7.0 KB
scripts/test_routing_parity.pyscript32.3 KB
scripts/test_routing_review.pyscript25.1 KB
scripts/test_setup_discovery_parity.pyscript9.5 KB
scripts/test_stage_help.pyscript2.0 KB
scripts/test_state_upgrade.pyscript13.8 KB
scripts/test_turn_refusal.pyscript16.7 KB
scripts/test_usage_cache.pyscript4.9 KB
scripts/test_usage_collector.pyscript21.4 KB
scripts/test_usage_core_claude_accounts.pyscript1.8 KB
scripts/test_usage_core_grok_cli_billing.pyscript15.6 KB
scripts/test_usage_core_magpie.pyscript5.4 KB
scripts/test_usage_core_magpie_pool.pyscript10.8 KB
scripts/test_usage_core_safety.pyscript24.4 KB
scripts/test_user_scores.pyscript102.3 KB
scripts/test_venice_usage.pyscript1.3 KB
scripts/test_window_scope.pyscript5.5 KB
scripts/turn_refusal.pyscript10.7 KB
scripts/usage_cache.pyscript4.7 KB
scripts/usage_collector.pyscript7.4 KB
scripts/usage_core.pyscript142.0 KB
scripts/usage_magpie.pyscript10.6 KB
scripts/usage_reading.pyscript17.1 KB
scripts/user_scores.pyscript72.8 KB
scripts/venice_usage.pyscript2.6 KB
scripts/window_scope.pyscript3.2 KB
scripts/worker_context.pyscript8.9 KB
scripts/worker_sessions.pyscript10.9 KB

scripts/provider_inventory.py

View on GitHub
"""Discover local launchable accounts; product configurations remain read-only.

Only allowlisted metadata leaves the adapters. Secrets are used for identity binding
only; product files and cached usage are read without any network requests.
"""
from __future__ import annotations

import copy
from contextlib import closing
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import shutil
import sqlite3
import tempfile
import tomllib
from typing import NamedTuple
import account_state
import antigravity_plan
import grok_bot_paths
from model_resolution import resolve_in
import provider_retry
import public_data
import usage_cache

MAX_BYTES = 5 * 1024 * 1024
# The collector's words for a 401/403, in either language it writes.
COLLECTOR_REJECTED = {'claude': ('登录凭据需由 Claude Code 更新', 'Login credentials must be updated by Claude Code'),
                      'codex': ('登录凭据需由 Codex 更新', 'Login credentials must be updated by Codex'),
                      'grok': ('登录凭据需由 Grok 更新', 'Login credentials must be updated by Grok')}
GROK_BOT_CLI = grok_bot_paths.runtime_dir() / grok_bot_paths.ENTRY
# Paseo built-in providers recognized from their Paseo entry without a model catalog.
PASEO_RECOGNIZED_ONLY = ('copilot', 'muse', 'dsh')
# Oh My Pi signs in to subscriptions with OAuth (agent.db `auth_credentials`). omp's provider id -> the AgentCompass
# family whose identity (auth_facts), plan templates and model rows such a login uses. A provider without a family
# here is not routed: AgentCompass has no identity, plan or model data for it.
OMP_OAUTH_FAMILIES = {'openai-codex': 'codex', 'anthropic': 'claude'}


PLAN_TEMPLATES = Path(__file__).resolve().parents[1] / 'references/plan-templates.json'
TEMPLATE_KEYS = ('windows', 'cadence', 'unmetered')
POOL_KEYS = ('windows', 'capacity_usd', 'observed', 'expires_at')
_SHIPPED_PLAN_TEMPLATES = None
_STDLIB_WHICH = shutil.which
_WHICH_CACHE = {}
_REGISTRY_EXE_CACHE = {}
INVENTORY_SCHEMA = 'agent-compass.providers.v2.local'
_LAST_PUBLISHED_INVENTORY = {}
_RESOLVE_CACHE = {}
_TOML_CACHE = {}
_DEFAULT_HOME_RESOLVED = Path.home().resolve()
_REPO_ROOT = Path(__file__).resolve().parents[3]


def _resolved(path: Path) -> Path:
    key = str(path)
    res = _RESOLVE_CACHE.get(key)
    if res is None:
        res = path.resolve()
        if len(_RESOLVE_CACHE) > 512:
            _RESOLVE_CACHE.clear()
        _RESOLVE_CACHE[key] = res
    return res




def quota_sources(accounts):
    """Accounts that draw on another account's quota, as declared in the account document.

    Either a top-level `quota_sources` map ({account: source}) or a per-account `quota_source`.
    Nothing is pooled by default: two products only share a pool when the user's config says so.
    """
    accounts = obj(accounts)
    declared = {k: v for k, v in obj(accounts.get('quota_sources')).items()}
    for name, spec in obj(accounts.get('accounts')).items():
        if isinstance(spec, dict) and 'quota_source' in spec:
            declared[name] = spec['quota_source']
    return {name: source for name, source in declared.items()
            if isinstance(name, str) and isinstance(source, str) and source and source != name}


def quota_source(account, accounts=None):
    return quota_sources(accounts).get(account, account) if accounts else account


def apply_shared_quota(accounts):
    """A pooled account mirrors its source's quota state; execution settings stay its own."""
    specs = accounts['accounts']
    inventory = obj(accounts.get('_discovery'))
    inv_accounts = obj(inventory.get('accounts'))
    for name, source_name in quota_sources(accounts).items():
        if name not in specs or source_name not in specs:
            continue
        bot, source = specs[name], specs[source_name]
        bot['quota_source'] = source_name
        for key in POOL_KEYS:
            if key in source:
                bot[key] = copy.deepcopy(source[key])
            else:
                bot.pop(key, None)
        # An unread source meter is unknown, not free, for the account drawing on it.
        bot.pop('unmetered', None)
        bot.pop('unlimited', None)
        if 'plan_unknown' in source:
            bot['plan_unknown'] = source['plan_unknown']
        else:
            bot.pop('plan_unknown', None)
        source_row = obj(inv_accounts.get(source_name))
        unavail = account_state.unavailable_text(source_row)
        if unavail:
            reason = f'provider discovery: {unavail}'
            bot['discovery_status'] = source_row['status']
            bot['verified'] = False
            for bundle in obj(bot.get('bundles')).values():
                if isinstance(bundle, dict):
                    bundle.setdefault('discovery_unavailable', reason)


def shipped_plan_templates():
    """plan-templates.json of the reference set this process holds (public_data.document), parsed once per set."""
    global _SHIPPED_PLAN_TEMPLATES
    if read_json is not _STDLIB_READ_JSON:     # a test's reader stands in for the file
        return obj(read_json(PLAN_TEMPLATES)[0])
    held = public_data.set_id(PLAN_TEMPLATES.parent)
    if _SHIPPED_PLAN_TEMPLATES is None or _SHIPPED_PLAN_TEMPLATES[0] != held:
        try:
            _SHIPPED_PLAN_TEMPLATES = (held, obj(public_data.document(PLAN_TEMPLATES)))
        except (OSError, ValueError):
            return {}
    return _SHIPPED_PLAN_TEMPLATES[1]


def plan_table(accounts, family, shipped=None):
    """Merged `{plan_id: entry}` for `family` from shipped plan-templates.json plus `accounts['plan_templates']`."""
    shipped_all = shipped_plan_templates() if shipped is None else obj(shipped)
    base = obj(shipped_all.get(family))
    overrides = obj(obj(obj(accounts).get('plan_templates')).get(family))
    return {**base, **overrides}


def plan_defaults(accounts, family, plan, shipped=None):
    """Quota template for a subscription plan, independent of any configured account instance.

    The account document's `plan_templates` overrides the shipped references/plan-templates.json
    per family and plan. A template of `{"alias": "<plan>"}` resolves to that plan's template. Only
    `windows`, `cadence` and `unmetered` are copied onto an account; other keys (provenance, basis, price) are
    documentation. A plan's capacity is not in the template: it comes from the community capacity data by plan.
    """
    shipped_all = shipped_plan_templates() if shipped is None else obj(shipped)
    overrides = obj(obj(obj(accounts).get('plan_templates')).get(family))
    base = obj(shipped_all.get(family))
    template = None
    for _ in range(3):
        configured = overrides.get(plan)
        template = configured if isinstance(configured, dict) else obj(base.get(plan))
        plan = template.get('alias')
        if not isinstance(plan, str) or not template:
            break
    return copy.deepcopy({k: v for k, v in template.items() if k != 'alias'}) or None


def fill_template_gaps(spec, template):
    """Add template values the account does not set; never overwrite what the account already declares."""
    for key in TEMPLATE_KEYS:
        if key not in template:
            continue
        have = spec.get(key)
        if not have:
            spec[key] = copy.deepcopy(template[key])
        elif isinstance(have, dict) and isinstance(template[key], dict) and key != 'windows':
            for wid, value in template[key].items():
                have.setdefault(wid, copy.deepcopy(value))


def digest(*values):
    return hashlib.sha256('\0'.join(str(v or '') for v in values).encode()).hexdigest()


def obj(value):
    return value if isinstance(value, dict) else {}


def array(value):
    return value if isinstance(value, list) else []


def read_json(path, expected=dict):
    try:
        if path.stat().st_size > MAX_BYTES:
            return expected(), 'oversized'
        value = json.loads(path.read_text(encoding='utf-8-sig'))
        return (value, None) if isinstance(value, expected) else (expected(), 'invalid_shape')
    except FileNotFoundError:
        return expected(), 'missing'
    except (OSError, ValueError, UnicodeError):
        return expected(), 'unreadable'


_STDLIB_READ_JSON = read_json



def read_toml(value):
    if not isinstance(value, str):
        return {}
    cached = _TOML_CACHE.get(value)
    if cached is not None:
        return cached
    try:
        parsed = tomllib.loads(value)
    except ValueError:
        parsed = {}
    if len(_TOML_CACHE) > 256:
        _TOML_CACHE.clear()
    _TOML_CACHE[value] = parsed
    return parsed


def endpoint(value):
    value = str(value or '').rstrip('/')
    for suffix in ('/v1/chat/completions', '/v1/messages', '/v1/responses', '/v1'):
        if value.endswith(suffix):
            return value[:-len(suffix)]
    return value


# Official hosts have no /key/info. A self-built base is only a dollar candidate until a reading says so.
OFFICIAL_API_ORIGINS = frozenset({'https://api.anthropic.com', 'https://api.openai.com'})


def plan_name(family, value, tier=''):
    value = value.lower() if isinstance(value, str) else ''
    tier = tier if isinstance(tier, str) else ''
    if family == 'claude' and value == 'max':
        return 'max20' if '20x' in tier else 'max5' if '5x' in tier else 'max'
    return value or None


def auth_facts(family, auth, home, profile=None):
    """Return metadata plus in-memory binding material; never return raw auth."""
    auth = auth if isinstance(auth, dict) else {}
    if family == 'claude':
        oauth = auth.get('claudeAiOauth') or {}
        oauth = oauth if isinstance(oauth, dict) else {}
        token = oauth.get('accessToken') if isinstance(oauth.get('accessToken'), str) else None
        profile = obj(profile)
        account = profile.get('accountUuid') or profile.get('emailAddress')
        identity = digest('claude-account', account, profile.get('organizationUuid')) if token and account else digest('claude', token) if token else None
        return {'present': bool(token), 'identity': identity,
                'credential_identity': digest('claude', token) if token else None,
                'credential_version': digest(token, oauth.get('refreshToken')) if token else None,
                'credential_key': digest(_resolved(home), token) if token else None,
                # No plan from the login file: subscriptionType/rateLimitTier are frozen at the CLI's last login. The
                # plan is the live OAuth profile's, read with the usage reading (plan_source 'profile_api').
                'plan': None}
    tokens = auth.get('tokens') or {}
    tokens = tokens if isinstance(tokens, dict) else {}
    token = tokens.get('access_token') if isinstance(tokens.get('access_token'), str) else None
    account = tokens.get('account_id') if isinstance(tokens.get('account_id'), str) else None
    # No plan from the login: the id_token's chatgpt_plan_type is frozen when the Codex CLI last wrote auth.json and goes
    # stale when the subscription changes. The plan comes only from the live usage API's plan_type (this account's
    # reading, or the shared reading of the same subscription); with no reading it is unknown.
    return {'present': bool(token), 'identity': digest('codex', account or token) if token else None,
            'credential_identity': digest('codex', token, account or '') if token else None,
            'credential_key': digest(_resolved(home), str(token) + ':' + str(account or '')) if token else None,
            'plan': None}


def _extract_grok_auth_token(auth):
    if not isinstance(auth, dict):
        return None
    top = auth.get('access_token')
    if isinstance(top, str) and top:
        return top
    oidc = None
    legacy = None
    for scope, value in auth.items():
        if not isinstance(value, dict):
            continue
        key = value.get('key')
        if not isinstance(key, str) or not key:
            continue
        s = str(scope)
        if s.startswith('https://auth.x.ai::'):
            oidc = key
        elif s == 'https://accounts.x.ai/sign-in' or '/sign-in' in s:
            legacy = key
    return oidc or legacy


def grok_auth_facts(grok_home, environ=None):
    auth_doc, _ = read_json(Path(grok_home) / 'auth.json')
    file_tok = _extract_grok_auth_token(auth_doc)
    if file_tok:
        token = file_tok
    else:
        environ = environ or {}
        token = str(environ.get('GROK_API_KEY') or environ.get('GROK_TOKEN') or '').strip() or None
    return {
        'present': bool(token),
        'identity': digest('grok', token) if token else None,
        'credential_identity': digest('grok', token) if token else None,
        'credential_key': digest(_resolved(Path(grok_home)), token) if token else None,
    }


def omp_credentials(agent_dir):
    """Oh My Pi's stored sign-ins from agent.db, read-only and bounded; omp itself is never run.

    Returns {'logins', 'api_keys', 'problem'}. `logins` are the enabled OAuth credentials of providers in
    OMP_OAUTH_FAMILIES, in omp's order, as {'provider', 'family', 'data'}. `api_keys` is True when an enabled
    credential of another type (an API key) is stored. `problem` is 'unreadable' for a corrupt, locked or foreign
    database and None otherwise (a missing database included).
    """
    found = {'logins': [], 'api_keys': False, 'problem': None}
    path = Path(agent_dir) / 'agent.db'
    if not path.is_file():
        return found
    try:
        with closing(sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True, timeout=0.5)) as con:
            rows = con.execute("SELECT provider, credential_type, data FROM auth_credentials "
                               "WHERE disabled_cause IS NULL OR disabled_cause = '' ORDER BY id").fetchall()
    except sqlite3.Error:
        return dict(found, problem='unreadable')
    for provider, kind, raw in rows:
        if kind != 'oauth':
            found['api_keys'] = True
            continue
        family = OMP_OAUTH_FAMILIES.get(provider)
        try:
            data = json.loads(raw) if family and isinstance(raw, str) and len(raw) <= MAX_BYTES else None
        except ValueError:
            data = None
        if isinstance(data, dict) and isinstance(data.get('access'), str) and data['access']:
            found['logins'].append({'provider': provider, 'family': family, 'data': data})
    return found


def omp_models(agent_dir):
    """{omp provider id: [model ids]} from omp's own model cache (models.db), read-only; {} when unreadable."""
    path = Path(agent_dir) / 'models.db'
    if not path.is_file():
        return {}
    try:
        with closing(sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True, timeout=0.5)) as con:
            rows = con.execute('SELECT provider_id, models FROM model_cache').fetchall()
    except sqlite3.Error:
        return {}
    out = {}
    for provider_id, raw in rows:
        try:
            models = json.loads(raw) if isinstance(raw, str) and len(raw) <= MAX_BYTES else []
        except ValueError:
            continue
        ids = [m.get('id') for m in array(models) if isinstance(m, dict) and isinstance(m.get('id'), str)]
        if ids:   # cache keys carry a version suffix: `openai-codex:0.159.0`
            out.setdefault(str(provider_id).split(':', 1)[0], []).extend(ids)
    return out


def omp_auth(family, data):
    """An omp OAuth record in the shape auth_facts reads for the family's own CLI, plus its profile."""
    if family == 'claude':
        return ({'claudeAiOauth': {'accessToken': data.get('access'), 'refreshToken': data.get('refresh'),
                                   'subscriptionType': data.get('subscriptionType') or data.get('plan')}},
                {'accountUuid': data.get('accountUuid') or data.get('accountId'), 'emailAddress': data.get('email'),
                 'organizationUuid': data.get('organizationUuid') or data.get('orgId')})
    return {'tokens': {'access_token': data.get('access'), 'account_id': data.get('accountId'),
                       'id_token': data.get('idToken') or data.get('id_token')}}, None


def resolve_definition(name, definitions):
    env, seen = {}, set()
    current = name
    enabled = obj(definitions.get(name)).get('enabled') is not False
    while current not in seen:
        seen.add(current)
        spec = definitions.get(current) or {}
        if not isinstance(spec, dict):
            break
        env = {**{k: v for k, v in obj(spec.get('env')).items() if isinstance(v, str)}, **env}
        parent = spec.get('extends')
        if not parent:
            return current, env, enabled
        if not isinstance(parent, str):
            return current, env, False
        current = parent
    return name, env, False


def product_config(family, config):
    env = config.get('env') if isinstance(config.get('env'), dict) else {}
    if family == 'claude':
        token = env.get('ANTHROPIC_AUTH_TOKEN') or env.get('ANTHROPIC_API_KEY') or ''
        return (endpoint(env.get('ANTHROPIC_BASE_URL') or ('https://api.anthropic.com' if token else '')),
                token,
                [v for k, v in env.items() if 'MODEL' in k and isinstance(v, str)])
    parsed = read_toml(config.get('config'))
    selected = parsed.get('model_provider') if isinstance(parsed.get('model_provider'), str) else ''
    provider = obj(obj(parsed.get('model_providers')).get(selected))
    auth = config.get('auth') or {}
    auth = auth if isinstance(auth, dict) else {}
    token = provider.get('experimental_bearer_token') or auth.get('OPENAI_API_KEY') or ''
    return (endpoint(provider.get('base_url') or ('https://api.openai.com' if token else '')),
            token,
            [parsed['model']] if isinstance(parsed.get('model'), str) else [])


def cc_switch(path):
    """Do not inspect logs, execute usage_script, or open the DB writable."""
    if not path.exists():
        return [], 'missing'
    try:
        with closing(sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True, timeout=1)) as db:
            db.execute('PRAGMA query_only=ON')
            rows = db.execute('SELECT id, app_type, name, settings_config, category, is_current '
                              'FROM providers LIMIT 513').fetchall()
            health = {}
            if db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='provider_health'").fetchone():
                health = {(app, ident): bool(ok) for ident, app, ok in db.execute(
                    'SELECT provider_id, app_type, is_healthy FROM provider_health LIMIT 512')}
        result = []
        partial = len(rows) > 512
        for ident, family, name, raw, category, current in rows[:512]:
            try:
                config = json.loads(raw)
                if not isinstance(config, dict):
                    partial = True
                    continue
            except (ValueError, TypeError):
                partial = True
                continue
            result.append(({'id': f'cc-switch:{family}:{ident}', 'source': 'cc-switch',
                            'family': family, 'name': name, 'current': bool(current),
                            'category': category, 'healthy': health.get((family, ident))}, config))
        return result, 'partial' if partial else None
    except (sqlite3.Error, OSError):
        return [], 'unreadable'


def _which(product, path_value):
    if shutil.which is not _STDLIB_WHICH:
        return shutil.which(product, path=path_value)
    import time
    now_mono = time.monotonic()
    key = (product, path_value)
    cached = _WHICH_CACHE.get(key)
    if cached is not None and now_mono - cached[0] < 15.0:
        return cached[1]
    found = shutil.which(product, path=path_value)
    if not found and path_value is not None and path_value == os.environ.get('PATH'):
        # A long-running process (the tray, a daemon) keeps the PATH it started with; a CLI installed since then is
        # on the PATH a new process would get, so look there too.
        fresh = _fresh_windows_path()
        if fresh:
            found = shutil.which(product, path=fresh)
    _WHICH_CACHE[key] = (now_mono, found)
    return found


def _fresh_windows_path():
    """The PATH a newly started process gets: machine then user `Path` from the registry. Empty off Windows.

    Also empty when this process runs as another profile than the signed-in user's (USERPROFILE pointed at another
    home, as a sandbox or a foreign-profile check does): that user's registry PATH names CLIs that profile does not have.
    """
    if os.name != 'nt':
        return ''
    import winreg
    owner = _registry_profile()
    here = os.environ.get('USERPROFILE')
    if not owner or not here or os.path.normcase(os.path.abspath(here)) != os.path.normcase(os.path.abspath(owner)):
        return ''
    parts = []
    for hive, subkey in ((winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'),
                         (winreg.HKEY_CURRENT_USER, 'Environment')):
        try:
            with winreg.OpenKey(hive, subkey) as key:
                parts.append(os.path.expandvars(str(winreg.QueryValueEx(key, 'Path')[0])))
        except OSError:
            continue
    return os.pathsep.join(parts)


def _registry_profile():
    """The signed-in user's profile folder (HKCU `Volatile Environment` USERPROFILE); '' when it cannot be read."""
    import winreg
    try:
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Volatile Environment') as key:
            return os.path.expandvars(str(winreg.QueryValueEx(key, 'USERPROFILE')[0]))
    except OSError:
        return ''


def _registry_executables(product):
    import time
    now_mono = time.monotonic()
    cached = _REGISTRY_EXE_CACHE.get(product)
    if cached is not None and now_mono - cached[0] < 60.0:
        return list(cached[1])
    import winreg
    paths = []
    for hive in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE):
        try:
            with winreg.OpenKey(hive, r'Software\Microsoft\Windows\CurrentVersion\App Paths' + '\\' + product + '.exe') as key:
                value = winreg.QueryValue(key, None)
                paths.append(Path(value.strip('"')))
        except OSError:
            pass
        for subkey in (r'Software\Microsoft\Windows\CurrentVersion\Uninstall',
                       r'Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'):
            try:
                with winreg.OpenKey(hive, subkey) as root:
                    for index in range(min(winreg.QueryInfoKey(root)[0], 1024)):
                        try:
                            with winreg.OpenKey(root, winreg.EnumKey(root, index)) as key:
                                name = winreg.QueryValueEx(key, 'DisplayName')[0]
                                if str(name).lower().replace(' ', '-') != product:
                                    continue
                                folder = winreg.QueryValueEx(key, 'InstallLocation')[0]
                                paths.append(Path(folder) / (product + '.exe'))
                        except OSError:
                            continue
            except OSError:
                pass
    _REGISTRY_EXE_CACHE[product] = (now_mono, tuple(paths))
    return paths


def installed_executables(product, home, environ):
    """Bounded OS installation hints; never execute the application or scan a drive."""
    paths = []
    found = _which(product, environ.get('PATH'))
    if found:
        paths.append(_resolved(Path(found)))
    explicit = environ.get('MAGPIE_EXE' if product == 'magpie' else 'CC_SWITCH_EXE')
    if explicit:
        paths.insert(0, Path(explicit).expanduser())
    is_default_home = _resolved(home) == _DEFAULT_HOME_RESOLVED
    if is_default_home:
        repository = _REPO_ROOT
        for directory in (repository, repository / product, repository / 'tools', repository / 'tools' / product):
            candidate = directory / (product + ('.exe' if os.name == 'nt' else ''))
            if candidate.is_file():
                paths.append(candidate)
    if os.name != 'nt' or not is_default_home:
        return paths
    paths.extend(_registry_executables(product))
    return list(dict.fromkeys(paths))


def product_root(product, home, environ):
    explicit = environ.get('MAGPIE_CONFIG_DIR' if product == 'magpie' else 'CC_SWITCH_HOME')
    if explicit:
        return Path(explicit).expanduser()
    for exe in installed_executables(product, home, environ):
        if product == 'magpie':
            data = exe.parent / 'data'
            if (exe.parent / '.portable').is_file() or any((data / f).is_file() for f in ('providers.json', 'logins.json')):
                return data
        elif (exe.parent / 'portable.ini').is_file():
            return exe.parent / 'data/app'
    if product == 'magpie':
        return Path(environ.get('XDG_CONFIG_HOME') or home / '.config') / 'magpie'
    # CC Switch's own Tauri store records its relocated database; device settings
    # remain in the default folder. Do not fall back to an old DB after relocation.
    stores = [Path(environ.get('APPDATA') or home / 'AppData/Roaming'),
              Path(environ.get('XDG_CONFIG_HOME') or home / '.config'),
              Path(environ.get('XDG_DATA_HOME') or home / '.local/share'),
              home / 'Library/Application Support']
    for store in stores:
        data, _ = read_json(store / 'com.ccswitch.desktop/app_paths.json')
        value = data.get('app_config_dir_override')
        if isinstance(value, str) and value.strip():
            return Path(value).expanduser()
    return home / '.cc-switch'


def read_magpie(home, environ, result, bindings):
    root = product_root('magpie', home, environ)
    stored, error = read_json(root / 'providers.json')
    logins, login_error = read_json(root / 'logins.json', list)
    result['sources']['magpie_config'] = error or 'read'
    result['sources']['magpie_logins'] = login_error or 'read'
    result['source_paths']['magpie'] = str(root)
    if 'providers' in stored and not isinstance(stored['providers'], list):
        result['sources']['magpie_config'] = 'invalid_shape'
    for item in array(stored.get('providers')):
        if not isinstance(item, dict):
            result['sources']['magpie_config'] = 'partial'
            continue
        bases = {endpoint(item.get(k)) for k in ('anthropic', 'responses', 'chat') if item.get(k)}
        keys = {digest(k['key']): bool(k.get('off')) for k in array(item.get('keys')) if isinstance(k, dict) and k.get('key')}
        if item.get('key'):
            keys[digest(item['key'])] = False  # the active key wins over a duplicate backup
        matched = [name for name, binding in bindings.items() if binding['base'] in bases and binding['key'] in keys]
        builtin = item.get('id') in ('claude', 'codex', 'antigravity') and not bases and not keys
        if builtin:
            matched = [name for name, row in result['accounts'].items()
                       if row['family'] == item['id'] and row.get('billing') == 'subscription']
        disabled = item.get('off') or (builtin and item.get('hidden'))
        paused = [name for name in matched if disabled or (not builtin and keys[bindings[name]['key']])]
        models = [m for m in array(item.get('models')) if isinstance(m, str)]
        magpie_ids = [str(p) for p in dict.fromkeys((item.get('preset'), item.get('id')))
                      if not builtin and isinstance(p, str) and p.strip()]
        for name in matched:
            result['accounts'][name]['sources'].append('magpie-config')
            if magpie_ids:
                existing = result['accounts'][name].get('magpie_providers') or []
                result['accounts'][name]['magpie_providers'] = list(dict.fromkeys([*existing, *magpie_ids]))
            if name in paused:
                result['accounts'][name].update(status='paused', reason='disabled_in_magpie')
            # Magpie's empty picks mean defaults; noModels is its explicit Select none.
            if models or item.get('noModels') is True:
                result['accounts'][name]['models'] = models
        result['saved'].append({'id': 'magpie:' + str(item.get('id')), 'source': 'magpie_config',
            'name': item.get('name'), 'status': 'paused' if disabled or paused else 'bound' if matched else 'saved',
            'bound_to': matched, 'models': models, 'removal_pauses': not builtin})
    for login in logins:
        if not isinstance(login, dict):
            result['sources']['magpie_logins'] = 'partial'
            continue
        family = login.get('agent')
        facts = auth_facts(family, obj(login.get('auth')), root, login.get('profile')) if family in ('claude', 'codex') else {}
        matched = [name for name, binding in bindings.items() if facts.get('identity')
                   and (binding['identity'] == facts['identity'] or (facts.get('credential_identity')
                        and facts['credential_identity'] == binding.get('credential_identity')))
                   and result['accounts'][name]['family'] == family]
        active = family in matched or login.get('held') is True
        enabled = (active or login.get('on') is True) and not any(login.get(k) for k in ('paused', 'hidden'))
        plan = facts.get('plan') or plan_name(family, login.get('plan'))
        for name in matched:
            result['accounts'][name]['sources'].append('magpie-logins')
            refused = login.get('lapsed') and (family != 'claude' or
                      (login.get('refused') or facts.get('credential_version')) == bindings[name].get('credential_version'))
            if not enabled or refused:
                result['accounts'][name].update(status='paused', reason='account_disabled_in_magpie')
            if plan:
                result['accounts'][name]['plan'] = plan
        result['saved'].append({'id': 'magpie-login:' + digest(family, login.get('id') or login.get('user'))[:20],
            'source': 'magpie_logins', 'family': family, 'plan': plan, 'bound_to': matched,
            'status': 'paused' if not enabled or login.get('lapsed') else 'bound' if matched else 'saved',
            'credentials_present': bool(facts.get('present'))})


# The user's removals (a credential taken out of the launcher stays paused) live in the published inventory, so that file
# is not only derived. {the schema an earlier release wrote: (does the document have it, the step that carries it)}:
# releases v0.1.0 to v0.3.1 named the schema `route-manager.providers.v2.local` and kept `removed` and `saved` in the shape
# of today (the identities are the same digests); v0.3.2 renamed the schema, and its first publish replaced such a file.
LOCAL_UPGRADES = {
    'route-manager.providers.v2.local (v0.1.0 to v0.3.1)': (
        lambda doc: doc.get('schema') == 'route-manager.providers.v2.local',
        lambda doc: {**doc, 'schema': INVENTORY_SCHEMA}),
}


def previous_inventory(path):
    """The last published inventory in the current shape (`LOCAL_UPGRADES`); `{}` when there is none. A file that
    cannot be read, or of another schema that holds removals nothing can read, is a fault, not something to replace:
    the next publish would drop what the user removed. Another schema without removals holds only derived data."""
    import state_upgrade
    doc, why = read_json(path)
    if why not in (None, 'missing'):
        raise ValueError(state_upgrade.format_issue(path, f'provider inventory unreadable ({why})', _inventory_fix(path)))
    for has_shape, step in LOCAL_UPGRADES.values():
        if has_shape(doc):
            doc = step(doc)
    if doc.get('schema') != INVENTORY_SCHEMA and doc.get('removed'):
        raise ValueError(state_upgrade.format_issue(
            path, f'provider inventory of schema {doc.get("schema")!r} holds removals that cannot be read', _inventory_fix(path)))
    return doc


def _inventory_fix(path):
    import state_upgrade
    return state_upgrade.fix_delete(path, 'this discards which credentials you removed in the launcher: they are routable '
                                          'again until you remove them again; the next discovery writes a new file')


def apply_removals(result, previous):
    """A confirmed product removal pauses the same credential until restored.

    Missing/unreadable databases do not mean their accounts were deleted. Keep a
    tombstone only while that exact credential is still installed in the launcher.
    """
    if previous.get('schema') != result['schema']:
        return
    current = {r['id']: r for r in result['saved']}
    pending = list(previous.get('removed') or [])
    for item in previous.get('saved') or []:
        if result['sources'].get(item.get('source')) != 'read':
            if item.get('status') == 'paused':
                for name in item.get('bound_to') or []:
                    old = obj(previous.get('accounts')).get(name) or {}
                    row = result['accounts'].get(name) or {}
                    if old.get('status') == 'paused' and old.get('identity') and old['identity'] == row.get('identity'):
                        row.update(status='paused', reason='last_known_disabled_in_' + item['source'])
                        if item['id'] not in current:
                            result['saved'].append(item)
                            current[item['id']] = item
            continue
        new = current.get(item['id']) or {}
        if item.get('removal_pauses') is False:
            continue  # removing built-in subscription picks restores Magpie defaults
        for name in item.get('bound_to') or []:
            old = obj(previous.get('accounts')).get(name) or {}
            if name not in (new.get('bound_to') or []) and old.get('identity'):
                pending.append({'entry': item['id'], 'source': item['source'], 'account': name, 'identity': old['identity']})
    kept = {}
    for removed in pending:
        row = result['accounts'].get(removed['account']) or {}
        if not row.get('identity') or row['identity'] != removed.get('identity'):
            continue
        restored = removed['account'] in (current.get(removed['entry'], {}).get('bound_to') or [])
        if restored:
            continue
        row.update(status='paused', reason='removed_from_' + removed['source'])
        kept[(removed['entry'], removed['account'])] = removed
    result['removed'] = list(kept.values())


def _expand_home(value, home):
    text = str(value or '').strip()
    if text == '~':
        return Path(home)
    if text.startswith(('~/', '~\\')):
        return Path(home) / text[2:]
    return Path(os.path.expandvars(text)).expanduser()


def consult_home(home, environ):
    """The ChatGPT Web bridge profile the consultation client uses: PRO_CONSULT_HOME, else the default folder."""
    value = str(environ.get('PRO_CONSULT_HOME') or '').strip()
    return _expand_home(value, home) if value else Path(home) / '.codex-chatgpt-web-consult'


def is_consult_home(path, home, environ=None):
    """True when `path` is an isolated ChatGPT Web / Pro consultation profile rather than a Codex worker home."""
    environ = os.environ if environ is None else environ
    p = Path(path)
    if p.name.lstrip('.').startswith(('codex-chatgpt-web', 'codex-pro-consult')):
        return True
    return _resolved(p) == _resolved(consult_home(home, environ))


def orca_user_data_dirs(home=None):
    """Orca's Electron userData directories under `home` (Windows roaming, macOS Application Support, Linux ~/.config).

    ORCA_USER_DATA_PATH is deliberately not read: an inherited value would point a test or sandbox home at the real install.
    """
    home = Path(home) if home is not None else Path.home()
    found = {}
    for p in (home / 'AppData' / 'Roaming' / 'orca',
              home / 'Library' / 'Application Support' / 'orca',
              home / '.config' / 'orca'):
        if p.is_dir():
            found.setdefault(str(_resolved(p)), p)
    return list(found.values())


def orca_codex_homes(home=None):
    """Codex homes Orca manages per signed-in account. Orca mirrors only config.toml into them, so AGENTS.md and skills never arrive."""
    return [h for ud in orca_user_data_dirs(home)
            for h in sorted((ud / 'codex-accounts').glob('*/home')) if h.is_dir()]


def dot_configuration(home, environ):
    """Dot is configured by DOT2API_BASE_URL plus DOT2API_API_KEY, or a client.json with both values."""
    if str(environ.get('DOT2API_BASE_URL') or '').strip() and str(environ.get('DOT2API_API_KEY') or '').strip():
        return 'ready'
    config, error = read_json(home / '.dot2api/client.json')
    if error:
        return 'missing_configuration' if error == 'missing' else 'invalid_configuration'
    base, key = config.get('base_url'), config.get('api_key')
    valid = (isinstance(base, str) and base.strip().startswith(('http://', 'https://'))
             and isinstance(key, str) and bool(key.strip()))
    return 'ready' if valid else 'invalid_configuration'


def consult_configuration(web_home):
    """The same local checks the consultation client applies before it contacts the bridge."""
    config, error = read_json(web_home / 'config.json')
    if error:
        return 'missing_configuration' if error == 'missing' else 'invalid_configuration'
    valid = (config.get('mode') == 'browser-only' and config.get('browserInteractionMode') == 'automatic'
             and config.get('host') == '127.0.0.1' and isinstance(config.get('port'), int)
             and not isinstance(config.get('port'), bool) and config.get('proAvailable') is True)
    return 'ready' if valid else 'invalid_configuration'


def _harness_slots(home, environ, definitions):
    """Claude and Codex homes shared by discovery and the dollar-candidate scan. Consult homes stay out."""
    home = Path(home)
    slots = {'claude': ('claude', home / '.claude'), 'codex': ('codex', home / '.codex')}
    for family in ('claude', 'codex'):
        for other in sorted(home.glob(f'.{family}-*')):
            if not other.is_dir():
                continue
            if family == 'codex' and is_consult_home(other, home, environ):
                continue
            slot_name = other.name.lstrip('.')
            slots[slot_name] = (family, other)
    for name in definitions:
        family, env, _enabled = resolve_definition(name, definitions)
        if family in ('claude', 'codex'):
            root_key = 'CLAUDE_CONFIG_DIR' if family == 'claude' else 'CODEX_HOME'
            candidate = home / f'.{name}'
            fallback_home = candidate if candidate.is_dir() else home / ('.' + family)
            raw_root = env.get(root_key)
            target_home = _expand_home(raw_root, home) if raw_root else fallback_home
            if family == 'codex' and is_consult_home(target_home, home, environ):
                continue
            slots[name] = (family, target_home)
    orca_slots = set()
    seen_codex_homes = {_resolved(slot_home) for family, slot_home in slots.values() if family == 'codex'}
    for orca_home in orca_codex_homes(home):
        if is_consult_home(orca_home, home, environ) or _resolved(orca_home) in seen_codex_homes:
            continue
        slot_name = f'orca-{orca_home.parent.name}'
        slots[slot_name] = ('codex', orca_home)
        orca_slots.add(slot_name)
        seen_codex_homes.add(_resolved(orca_home))
    return slots, orca_slots


def _slot_layout(name, family, default_home, home, definitions):
    _family, env, enabled = resolve_definition(name, definitions)
    root_key = 'CLAUDE_CONFIG_DIR' if family == 'claude' else 'CODEX_HOME'
    raw_root = env.get(root_key)
    account_home = _expand_home(raw_root, home) if raw_root else default_home
    raw_sec = env.get('CLAUDE_SECURESTORAGE_CONFIG_DIR') if family == 'claude' else ''
    credential_home = _expand_home(raw_sec, home) if raw_sec else account_home
    return env, enabled, account_home, credential_home


def _product_reading(family, account_home, env, auth):
    """Base URL and API key as the product stores them. Nothing is written."""
    settings, _error = read_json(account_home / 'settings.json') if family == 'claude' else ({}, None)
    if family == 'claude':
        config = {**settings, 'env': {**obj(settings.get('env')), **env}}
    else:
        try:
            config = {'auth': auth, 'config': (account_home / 'config.toml').read_text(encoding='utf-8-sig')}
        except (OSError, UnicodeError):
            # One unreadable Codex file is that harness only. UnicodeError is not an OSError.
            config = {'auth': auth}
    base, token, models = product_config(family, config)
    return config, base, token if isinstance(token, str) else '', models


def _magpie_state(family, account_home, config, token, is_api, cached):
    """Explicit Magpie, or a cache row already bound to one. An unbound custom base is not Magpie."""
    source, _error = read_json(account_home / 'usage-float.json') if family == 'claude' else ({}, None)
    collector_base = str(config.get('env', {}).get('ANTHROPIC_BASE_URL') or '').rstrip('/') if family == 'claude' else ''
    magpie_candidates = set()
    override = None
    if is_api and family == 'claude':
        if source.get('source') == 'magpie':
            acct = source.get('account') if isinstance(source.get('account'), str) else ''
            override = digest('magpie', collector_base, token, source.get('provider') or family, acct)
            magpie_candidates.add(override)
        elif (not source.get('source') and collector_base.startswith('https://')
              and collector_base != 'https://api.anthropic.com'):
            magpie_candidates.add(digest('magpie', collector_base, token, family, ''))
    if cached.get('credential_key') in magpie_candidates:
        override = cached['credential_key']
    is_magpie = (
        source.get('source') == 'magpie'
        or cached.get('credential_key') in magpie_candidates
        or cached.get('backend_kind') == 'gateway'
    )
    return is_magpie, override


def _non_magpie_record(home, environ, provider_id):
    """Credential a Magpie probe stored as not Magpie.

    usage_cache.read drops a file whose providers table is empty. That is the file a
    failed probe leaves when this account is the only row, so the record is read raw.
    """
    path = usage_cache.read_paths(None, home, environ)[0]
    try:
        document = json.loads(Path(path).read_text(encoding='utf-8-sig'))
    except (OSError, ValueError, UnicodeError):
        return None
    gateways = document.get('non_magpie_gateways') if isinstance(document, dict) else None
    if not isinstance(gateways, dict):
        return None
    recorded = gateways.get(provider_id)
    return recorded if isinstance(recorded, str) and recorded else None


def _live_auth_token_subscription(family, account_home, paseo_env, provider_id, home, environ):
    """Claude ANTHROPIC_AUTH_TOKEN on a custom base, still read as a Magpie subscription.

    Metered USD does not take this account (docs/technical-reference.md, Metered USD).
    ANTHROPIC_API_KEY alone is not this source. A probe that records the credential as
    not Magpie drops it, and the harness can then be a dollar candidate.
    """
    if family != 'claude':
        return False
    import usage_magpie
    extra = paseo_env if isinstance(paseo_env, dict) else None
    source = usage_magpie.read_source(account_home, extra)
    if source is None or source.explicit:
        return False
    settings, _error = read_json(account_home / 'settings.json')
    file_env = obj(settings.get('env'))
    overlay = extra or {}
    auth = str(overlay.get('ANTHROPIC_AUTH_TOKEN') or file_env.get('ANTHROPIC_AUTH_TOKEN') or '').strip()
    if not auth:
        return False
    return _non_magpie_record(home, environ, provider_id) != source.credential_key


def _metered_category_evidence(cached, credential_key):
    """Billing category proved for this digest. The latest read's amount is separate."""
    if _metered_spend_evidence(cached, credential_key) is not None:
        return True
    if not credential_key or not isinstance(cached, dict) or cached.get('credential_key') != credential_key:
        return False
    details = cached.get('usage_details')
    return isinstance(details, dict) and details.get('kind') == 'metered_usd' and details.get('category') == 'metered'


def _metered_spend_evidence(cached, credential_key):
    """A /key/info spend for this credential. A permission miss or a 404 is not an amount."""
    if not credential_key or not isinstance(cached, dict) or cached.get('credential_key') != credential_key:
        return None
    details = cached.get('usage_details')
    if not isinstance(details, dict) or details.get('kind') != 'metered_usd':
        return None
    spend = details.get('spent_usd')
    if isinstance(spend, bool) or not isinstance(spend, (int, float)):
        return None
    if spend != spend or spend in (float('inf'), float('-inf')) or spend < 0:
        return None
    budget = details.get('budget_usd')
    budget_usd = None
    if (isinstance(budget, (int, float)) and not isinstance(budget, bool) and budget > 0
            and budget == budget and budget != float('inf')):
        budget_usd = float(budget)
    return {'spent_usd': float(spend), 'budget_usd': budget_usd}


def harness_usd_candidates(home=None, environ=None):
    """Self-built API-key harnesses that a usage poll may read with GET /key/info.

    Zero network. The key stays in the returned records and is not written to a file.
    Official API hosts, explicit Magpie gateways, and a live ANTHROPIC_AUTH_TOKEN
    subscription source are not candidates.
    """
    environ = os.environ if environ is None else environ
    home = Path(home) if home is not None else Path(environ.get('ROUTER_PROVIDER_HOME') or Path.home())
    paseo_path = Path(environ.get('PASEO_HOME') or home / '.paseo') / 'config.json'
    paseo, _error = read_json(paseo_path)
    agents = paseo.get('agents') if isinstance(paseo.get('agents'), dict) else {}
    definitions = agents.get('providers') if isinstance(agents.get('providers'), dict) else {}
    cache = usage_cache.read(None, home, environ)[0] or {}
    cache_rows = cache.get('providers') if isinstance(cache.get('providers'), dict) else {}
    slots, _orca_slots = _harness_slots(home, environ, definitions)
    found = []
    for name, (family, default_home) in slots.items():
        try:
            env, enabled, account_home, credential_home = _slot_layout(name, family, default_home, home, definitions)
            if not enabled:
                continue
            auth = {}
            if family == 'codex':
                auth, _auth_error = read_json(credential_home / 'auth.json')
            config, base, token, _models = _product_reading(family, account_home, env, auth)
        except UnicodeError:
            continue
        if not (base and token) or base in OFFICIAL_API_ORIGINS:
            continue
        cached = obj(cache_rows.get(name))
        is_magpie, _magpie_key = _magpie_state(family, account_home, config, token, True, cached)
        if is_magpie or _live_auth_token_subscription(
                family, account_home, env, name, home, environ):
            continue
        found.append({
            'provider_id': name,
            'family': family,
            'home': str(account_home),
            'endpoint': base,
            'api_key': token,
            'credential_key': digest('api', _resolved(account_home), base, token),
        })
    return found


def write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, name = tempfile.mkstemp(prefix=path.name + '.', suffix='.tmp', dir=path.parent)
    try:
        with os.fdopen(fd, 'w', encoding='utf-8') as stream:
            json.dump(value, stream, ensure_ascii=False, indent=2)
            stream.write('\n')
        os.replace(name, path)
    finally:
        Path(name).unlink(missing_ok=True)


_SCOPE = []


class snapshot:
    """Within this block, argument-free discover() runs once and later calls get a copy: one routing decision sees one
    inventory instead of rescanning local product files five times. Only discovery is shared; quota, policy, disablement
    and reservations are read live. Nested blocks join the outer one."""

    def __enter__(self):
        self.owner = not _SCOPE
        if self.owner:
            _SCOPE.append({})
        return self

    def __exit__(self, *exc):
        if self.owner:
            _SCOPE.clear()


def discover(home=None, environ=None, now=None):
    if _SCOPE and home is None and environ is None and now is None:
        if 'inventory' not in _SCOPE[0]:
            _SCOPE[0]['inventory'] = _discover()
        return copy.deepcopy(_SCOPE[0]['inventory'])
    return _discover(home, environ, now)


class _UsageCache(NamedTuple):
    """The collector's cached readings, polls and attempts by account (usage_cache), read once per discovery."""
    rows: dict
    polls: dict
    attempts: dict


def _read_usage_cache(home, environ):
    cache = usage_cache.read(None, home, environ)[0] or {}
    return _UsageCache(*(cache.get(key) if isinstance(cache.get(key), dict) else {}
                         for key in ('providers', 'poll', 'attempts')))


def _merge(result, known_bindings, accounts=None, launchers=None, bindings=None):
    """Add one source's rows in the order it found them. A row of None takes that account out again (Oh My Pi's API
    side when only subscription logins exist)."""
    for name, row in (accounts or {}).items():
        if row is None:
            result['accounts'].pop(name, None)
        else:
            result['accounts'][name] = row
    result['launchers'].update(launchers or {})
    known_bindings.update(bindings or {})


def _discover(home=None, environ=None, now=None):
    environ = os.environ if environ is None else environ
    home = Path(home) if home is not None else Path(environ.get('ROUTER_PROVIDER_HOME') or Path.home())
    now = now or datetime.now(timezone.utc)
    state_dir = Path(environ.get('ROUTER_STATE_DIR') or home / '.agent-compass')
    paseo_path = Path(environ.get('PASEO_HOME') or home / '.paseo') / 'config.json'
    paseo, paseo_error = read_json(paseo_path)
    agents = paseo.get('agents') if isinstance(paseo.get('agents'), dict) else {}
    definitions = agents.get('providers') or {}
    if not isinstance(definitions, dict):
        definitions = {}
    cache = _read_usage_cache(home, environ)
    result = {'schema': INVENTORY_SCHEMA, 'generated_at': now.isoformat(),
              'accounts': {}, 'launchers': {}, 'saved': [], 'source_paths': {},
              'sources': {'paseo': paseo_error or 'read'}}
    # Sources retain private binding material only until this function returns.
    bindings = {}
    accounts, launchers = result['accounts'], result['launchers']
    _merge(result, bindings, **_discover_native_slots(home, environ, now, definitions, cache))
    # Existing independent harnesses keep their established account association.
    _merge(result, bindings, launchers=_definition_launchers(definitions, launchers))
    _merge(result, bindings, accounts={'antigravity': _discover_antigravity(home, environ, now, state_dir, cache.rows)})
    _merge(result, bindings, **_discover_opencode(home, environ, launchers['opencode']))
    _merge(result, bindings, **_discover_grok(home, environ, now, definitions, cache))
    _merge(result, bindings, **_discover_omp(home, environ, definitions, accounts))
    _merge(result, bindings, **_paseo_recognized_only(definitions, accounts))
    _merge(result, bindings, accounts=_paseo_advertised(definitions, accounts, launchers))
    _merge(result, bindings, **_discover_pi(home, environ, now, definitions, cache, accounts, launchers['pi']))
    override_doc = _load_accounts_override(environ, state_dir)
    _merge(result, bindings, **_override_meters(override_doc, cache.rows, accounts))
    # Configuration validity only; whether the local service answers is checked at dispatch.
    web_home = consult_home(home, environ)
    result['source_paths']['chatgpt-web'] = str(web_home)
    _merge(result, bindings, accounts=_web_bridges(home, environ, web_home))
    _merge(result, bindings, **_discover_grok_bot(state_dir, environ))
    read_cc_switch(home, environ, definitions, result, bindings)
    read_magpie(home, environ, result, bindings)
    previous = previous_inventory(state_dir / 'provider-inventory.json')
    apply_removals(result, previous)
    _pause_disabled_plugins(result, state_dir)
    _sync_launcher_status(result)
    # One subscription can be exposed through multiple launchers/products. Keep
    # its quota owner stable instead of giving each alias a full allowance.
    _assign_quota_owners(accounts)
    _latch_exhausted_quota(accounts, state_dir, cache.rows)
    _share_online_plan(accounts)
    _settle_account_states(result, cache.rows, previous, state_dir, now, environ, override_doc, bindings)
    return result


def _apply_collector_refusal(row, cached, poll, attempt, now, rejected):
    """A ready account whose matching usage reading was refused: its plan is inactive, or its login was rejected."""
    if row['status'] != 'ready':
        return
    if account_state.usage_refused_plan(cached):
        retry_at = account_state.usage_refused_retry_at(cached, poll=poll, attempt=attempt, now=now)
        row.update(
            status=account_state.PLAN_INACTIVE,
            reason=account_state.usage_refused_reason(cached, retry_at=retry_at),
            **({'plan_inactive_at': cached.get('error_at') or cached.get('fetched_at')}
               if (cached.get('error_at') or cached.get('fetched_at')) else {}),
            **({'plan_inactive_retry_at': retry_at} if retry_at else {}),
        )
    elif account_state.usage_refused_credentials(cached, rejected):
        row.update(status=account_state.AUTH_FAILED, reason='credentials_rejected_by_collector')


def _discover_native_slots(home, environ, now, definitions, cache):
    """Claude and Codex sign-ins: the default homes, conventional alternate homes (.claude-*, .codex-*, also shown when
    they have no launcher), Paseo provider homes and Orca's per-account Codex homes."""
    slots, orca_slots = _harness_slots(home, environ, definitions)
    accounts, launchers, bindings = {}, {}, {}
    for name, (family, default_home) in slots.items():
        row, bindings[name] = _native_slot(name, family, default_home, name in orca_slots,
                                           home, environ, now, definitions, cache)
        accounts[name] = row
        launchers[name] = {'family': family, 'status': row['status']}
    return {'accounts': accounts, 'launchers': launchers, 'bindings': bindings}


def _native_slot(name, family, default_home, is_orca, home, environ, now, definitions, cache):
    """One Claude or Codex slot's row and its private binding material."""
    env, enabled, account_home, credential_home = _slot_layout(name, family, default_home, home, definitions)
    auth, _error = read_json(credential_home / ('.credentials.json' if family == 'claude' else 'auth.json'))
    profile_path = home / '.claude.json' if credential_home == home / '.claude' else credential_home / '.claude.json'
    profile, _ = read_json(profile_path) if family == 'claude' else ({}, None)
    facts = auth_facts(family, auth, credential_home, profile.get('oauthAccount'))
    config, base, token, models = _product_reading(family, account_home, env, auth)
    if family == 'claude':
        oauth_token = config['env'].get('CLAUDE_CODE_OAUTH_TOKEN')
        if isinstance(oauth_token, str) and oauth_token:
            facts.update(present=True, identity=digest('claude', oauth_token),
                         credential_identity=digest('claude', oauth_token), credential_version=digest(oauth_token, ''),
                         credential_key=digest(_resolved(credential_home), oauth_token), plan=None)
    is_api = bool(base and token)
    bound = name == family or name in definitions or is_orca
    row = {'family': family, 'provider': name, 'home': str(account_home),
           'cli_installed': bool(_which(family, environ.get('PATH'))),
           'sources': ['native'] + (['paseo'] if name in definitions else []) + (['orca'] if is_orca else []),
           'status': 'ready' if bound and enabled and (facts['present'] or is_api) else
                     'disabled' if not enabled else 'saved' if not bound else 'missing_credentials',
           # No plan from the login: a live reading sets it below (usage_api / profile_api), else it is unknown.
           'plan': None, 'plan_source': None,
           'credential_key': facts['credential_key'],
           'identity': facts['identity'], 'billing': ('metered' if base in OFFICIAL_API_ORIGINS
                                                     else 'unknown') if is_api else 'subscription'}
    binding = {'identity': facts['identity'], 'base': base, 'key': digest(token) if token else None,
               'credential_identity': facts.get('credential_identity'),
               'credential_version': facts.get('credential_version')}
    if is_api:
        row.update(plan=None, plan_source=None,
                   credential_key=digest('api', _resolved(account_home), base, token),
                   identity=digest(base, token))
        binding.update(identity=row['identity'], credential_identity=None, credential_version=None)
        if models:
            row['models'] = models
    # This is the collector's local cache binding, not a gateway request.
    cached = obj(cache.rows.get(name))
    is_magpie, magpie_key = _magpie_state(family, account_home, config, token, is_api, cached)
    if magpie_key:
        row['credential_key'] = magpie_key
    if is_api and is_magpie:
        row['billing'] = 'subscription'
    if (cached.get('credential_key') and cached.get('credential_key') == row.get('credential_key')):
        row['usage_binding'] = 'matches'
        _apply_collector_refusal(row, cached, cache.polls.get(name), cache.attempts.get(name), now,
                                 COLLECTOR_REJECTED[family])
        _apply_cached_plan(row, cached, family, is_api)
    elif cached:
        row['usage_binding'] = 'changed'
    # A self-built key is a candidate only. Billing becomes metered when this credential's /key/info spend is cached.
    # A live ANTHROPIC_AUTH_TOKEN subscription source is not a candidate.
    if (is_api and not is_magpie and enabled and base not in OFFICIAL_API_ORIGINS
            and not _live_auth_token_subscription(
                family, account_home, env, name, home, environ)):
        _apply_metered_usd(row, cached)
    return row, binding


def _apply_cached_plan(row, cached, family, is_api):
    """The plan of a usage reading taken with this slot's current credential."""
    label = cached.get('plan_label') if isinstance(cached.get('plan_label'), str) else ''
    online = configured_plan(family, label) if label.strip() else None
    if online and family == 'codex' and not is_api:
        # The usage API's plan_type of a reading taken with the current credential: the only Codex plan source.
        row.update(plan=online, plan_source='usage_api', plan_read_at=cached.get('fetched_at'))
    elif online and family == 'claude' and not is_api and cached.get('plan_source') == 'profile_api':
        # The live OAuth profile read with this credential's usage reading: the only Claude plan source.
        row.update(plan=online, plan_source='profile_api', plan_read_at=cached.get('fetched_at'))
    elif not row.get('plan') and online and not (family == 'claude' and not is_api):
        row.update(plan=online, plan_source='collector', plan_read_at=cached.get('fetched_at'))


def _apply_metered_usd(row, cached):
    """A self-built API-key slot is a dollar candidate; a cached /key/info reading for its credential makes it metered."""
    row['usd_candidate'] = True
    evidence = _metered_spend_evidence(cached, row.get('credential_key'))
    # Without an amount in the latest read the category stays, and no budget is copied from it.
    if evidence is None and not _metered_category_evidence(cached, row.get('credential_key')):
        return
    row['billing'] = 'metered'
    row['backend_kind'] = 'metered_usd'
    row['plan'] = 'metered USD'
    if evidence is not None and evidence['budget_usd'] is not None:
        row['budget_usd'] = evidence['budget_usd']


def _definition_launchers(definitions, launchers):
    """Launchers of Paseo definitions and the independent harnesses that no slot has already listed."""
    found = {}
    for name in set(definitions) | {'antigravity-resilient', 'opencode', 'pi'}:
        if name in launchers:
            continue
        family, _, enabled = resolve_definition(name, definitions)
        found[name] = {'family': family, 'status': 'ready' if enabled else 'disabled'}
    return found


def _discover_antigravity(home, environ, now, state_dir, cache_rows):
    """The agy sign-in, proven by a /usage reading or the account tier Google reports (antigravity_plan)."""
    agy = obj(cache_rows.get('antigravity'))
    agy_present = bool(_which('agy', environ.get('PATH')))
    agy_cli = bool(agy_present or _which('gemini', environ.get('PATH')))
    # agy answers /usage only for a signed-in account, so a quota reading is the sign-in proof.
    agy_read = bool(array(agy.get('windows')))
    # /usage carries no tier; the tier comes from Google with agy's own sign-in (antigravity_plan), which is also a sign-in proof.
    agy_state = antigravity_plan.cached_state(state_dir, now)
    agy_tier, agy_flapping = agy_state['plan'], agy_state['flapping']
    agy_data_error = agy_state['data_error']
    agy_plan_error = agy_state['plan_error']
    agy_tier_read_at = antigravity_plan.read_cache(state_dir).get('read_at') if agy_tier else None
    agy_resolved = configured_plan('antigravity', agy_tier) if agy_tier else None
    agy_known = set(plan_table({}, 'antigravity'))
    agy_plan = agy.get('plan_label') or (agy_resolved if agy_resolved in agy_known else agy_tier)
    row = {'family': 'antigravity', 'provider': 'antigravity-resilient',
        'home': str(home / '.gemini'), 'cli_installed': agy_cli,
        'sources': ['native'] + (['usage-cache'] if agy_read else []) + (['account-tier'] if agy_tier else []),
        'status': 'ready' if agy_present else 'missing_client',
        'plan': agy_plan,
        'plan_source': 'usage_api' if agy.get('plan_label') else 'account-tier' if agy_tier else None,
        **({'plan_read_at': agy.get('fetched_at') if agy.get('plan_label') else agy_tier_read_at}
           if (agy.get('plan_label') or agy_tier_read_at) else {}),
        **({'plan_error': str(agy_plan_error)} if agy_present and not agy_plan and agy_plan_error else {}),
        'billing': 'subscription', **({'data_error': agy_data_error} if agy_present and agy_data_error else {})}
    if agy_present and agy_flapping:
        # Two Google accounts take turns in agy's one keyring slot: no reading says which account a tier or a quota
        # belongs to, so the account is neither ready nor inactive (antigravity_plan module docstring).
        row.update(
            status=account_state.AGY_ACCOUNT_FLAPPING,
            reason=(f"{agy_flapping['accounts']} Google accounts in agy's keyring slot within "
                    f"{agy_flapping['window_minutes']} min, since {agy_flapping['since']}"),
            plan_source=None, plan=None)
        row.pop('plan_read_at', None)
        row.pop('plan_error', None)
    return row


def _discover_opencode(home, environ, launcher):
    """OpenCode's free models need no sign-in; its launcher needs the installed client."""
    installed = bool(_which('opencode', environ.get('PATH')))
    status = 'missing_client' if launcher['status'] == 'ready' and not installed else launcher['status']
    row = {'family': 'opencode', 'provider': 'opencode',
        'home': str(home / '.config/opencode'), 'cli_installed': installed,
        'sources': ['native'], 'status': status, 'plan': 'free', 'billing': 'subscription'}
    return {'accounts': {'opencode': row}, 'launchers': {'opencode': {**launcher, 'status': status}}}


def _discover_grok(home, environ, now, definitions, cache):
    """Grok's ACP launcher is not an OAuth Claude/Codex slot. A cached reading is
    metadata only; it cannot by itself prove that a client is installed."""
    grok_cached = obj(cache.rows.get('grok'))
    grok_home = home / '.grok'
    grok_native = bool(_which('grok', environ.get('PATH'))) or grok_home.is_dir()
    grok_defined = 'grok' in definitions
    _, _, grok_enabled = resolve_definition('grok', definitions)
    grok_facts = grok_auth_facts(grok_home, environ)
    grok_windows = [w for w in array(grok_cached.get('windows')) if isinstance(w, dict) and w.get('id')]
    grok_has_failure = bool(
        grok_cached.get('error_status') is not None
        or grok_cached.get('error_code')
        or grok_cached.get('error_at')
        or (grok_cached.get('stale') is True and grok_cached.get('error'))
        or (grok_cached.get('available') is False and grok_cached.get('error'))
    )
    grok_ckey = grok_cached.get('credential_key')
    if grok_ckey:
        grok_matches = bool(grok_facts['credential_key'] and grok_ckey == grok_facts['credential_key'])
    elif grok_has_failure:
        grok_matches = bool(grok_facts['present'])
    else:
        grok_matches = bool(grok_cached)
    grok_sources = (['native'] if grok_native else []) + (['paseo'] if grok_defined else [])
    if grok_cached and grok_matches and (grok_windows or not grok_has_failure):
        grok_sources.append('usage-cache')
    grok_status = 'disabled' if not grok_enabled else 'ready' if grok_defined or grok_native else 'missing_client'
    grok_plan_raw = grok_cached.get('plan_label') if grok_matches else None
    grok_plan = grok_plan_raw.strip() if isinstance(grok_plan_raw, str) and grok_plan_raw.strip() else None
    grok_plan_err = ((grok_cached.get('usage_details') or {}).get('plan_tier_error')
                     if grok_matches and isinstance(grok_cached.get('usage_details'), dict) else None)
    grok_row = {
        'family': 'grok', 'provider': 'grok',
        'sources': grok_sources, 'status': grok_status,
        'plan': grok_plan,
        'billing': 'subscription',
        **({'plan_source': grok_cached.get('plan_source') or 'usage_api'} if grok_plan else {}),
        **({'plan_read_at': grok_cached['fetched_at']} if grok_plan and grok_cached.get('fetched_at') else {}),
        **({'credential_key': grok_facts['credential_key'], 'identity': grok_facts['identity']}
           if grok_facts['present'] else {}),
    }
    binding = {
        'identity': grok_facts['identity'],
        'credential_identity': grok_facts['credential_identity'],
        'base': '',
        'key': None,
    }
    # Preserve window IDs to share the collector's quota accounting when present.
    if grok_matches and grok_cached:
        grok_row['usage_binding'] = 'matches'
        if grok_windows:
            grok_row['usage_windows'] = [w['id'] for w in grok_windows]
        if not grok_plan:
            grok_row['plan_error'] = str(grok_plan_err or 'subscription tier not reported by Grok API')
        if grok_has_failure:
            grok_row['usage_read_failed'] = True
        _apply_collector_refusal(grok_row, grok_cached, cache.polls.get('grok'), cache.attempts.get('grok'), now,
                                 COLLECTOR_REJECTED['grok'])
    elif grok_cached and grok_ckey:
        grok_row['usage_binding'] = 'changed'
    return {'accounts': {'grok': grok_row}, 'launchers': {'grok': {'family': 'grok', 'status': grok_row['status']}},
            'bindings': {'grok': binding}}


def _discover_omp(home, environ, definitions, accounts):
    """Oh My Pi is Paseo's built-in `omp` provider. The `omp` account is its API-key side (~/.omp/agent/models.yml or
    stored API keys), so it is metered: explicit selection only. Each OAuth subscription login in omp is its own
    account. Like Pi on ChatGPT, one that signs in as a native account (same identity) shares that account's quota
    (`quota_account`); otherwise it is the subscription's only way in and routes on the family's plan defaults. Billing
    is subscription either way."""
    omp_native = (bool(_which('omp', environ.get('PATH')))
                  or (home / '.bun' / 'bin' / ('omp.exe' if os.name == 'nt' else 'omp')).is_file())
    omp_defined = 'omp' in definitions
    _, _, omp_enabled = resolve_definition('omp', definitions)
    omp_status = ('disabled' if not omp_enabled or not omp_defined
                  else 'ready' if omp_native or obj(definitions.get('omp')).get('command') else 'missing_client')
    omp_sources = (['native'] if omp_native else []) + (['paseo'] if omp_defined else [])
    found = {'omp': {'family': 'omp', 'provider': 'omp',
        'sources': omp_sources, 'status': omp_status, 'plan': 'API (Oh My Pi)', 'billing': 'metered'}}
    launchers = {'omp': {'family': 'omp', 'status': omp_status}}
    bindings = {}
    omp_dir = home / '.omp' / 'agent'
    omp_found = omp_credentials(omp_dir)
    logins = omp_found['logins']
    cached_models = omp_models(omp_dir) if logins else {}
    models_file = any((omp_dir / f).is_file() for f in ('models.yml', 'models.yaml'))
    if omp_status == 'ready' and not models_file and not omp_found['api_keys']:
        # Nothing shows an API key (no models.yml, no stored key; keys only in environment variables cannot be seen).
        # With only subscription logins there is no API side to report; an unreadable database hides both.
        if omp_found['problem']:
            found['omp'].update(status='missing_credentials', reason='agent.db unreadable')
        elif logins:
            found['omp'] = None
            launchers['omp']['api_side'] = False
    taken = {}
    for login in logins:
        provider, family = login['provider'], login['family']
        taken[provider] = taken.get(provider, 0) + 1
        name = f'omp-{provider}' + (f'-{taken[provider]}' if taken[provider] > 1 else '')
        auth, profile = omp_auth(family, login['data'])
        facts = auth_facts(family, auth, omp_dir, profile)
        # The rows this source adds or replaces are omp rows, never an owner.
        owner = next((cname for cname, crow in accounts.items()
                      if cname not in found and crow.get('family') == family
                      and crow.get('identity') and crow['identity'] == facts['identity']),
                     None)
        plan = facts['plan'] or (accounts[owner].get('plan') if owner else None)
        found[name] = {
            'family': 'omp', 'provider': 'omp', 'quota_family': family, 'omp_provider': provider,
            'home': str(omp_dir), 'sources': omp_sources, 'status': omp_status,
            'plan': plan, 'identity': facts['identity'], 'billing': 'subscription',
            **({'omp_models': cached_models[provider]} if cached_models.get(provider) else {}),
            **({'quota_account': owner} if owner else {}),
        }
        bindings[name] = {'identity': facts['identity'], 'credential_identity': facts.get('credential_identity'),
                          'base': '', 'key': None}
    return {'accounts': found, 'launchers': launchers, 'bindings': bindings}


def _paseo_recognized_only(definitions, accounts):
    """Other Paseo built-in launchers are recognized from their Paseo entry alone. Their
    billing is unknown and no model is invented, so they produce no bundle until the
    user configures models; unknown billing then stays explicit-selection only."""
    found, launchers = {}, {}
    for name in PASEO_RECOGNIZED_ONLY:
        if name in definitions and name not in accounts:
            _, _, enabled = resolve_definition(name, definitions)
            models = [m if isinstance(m, str) else m['id'] for m in array(obj(definitions[name]).get('models'))
                      if isinstance(m, str) or isinstance(m, dict) and isinstance(m.get('id'), str)]
            found[name] = {'family': name, 'provider': name, 'sources': ['paseo'],
                'status': 'ready' if enabled else 'disabled', 'billing': 'metered' if name == 'dsh' else 'unknown',
                **({'plan': 'API (DeepSeek Harness)'} if name == 'dsh' else {}),
                **({'models': models} if models else {})}
            launchers[name] = {'family': name, 'status': 'ready' if enabled else 'disabled'}
    return {'accounts': found, 'launchers': launchers}


def _paseo_advertised(definitions, accounts, launchers):
    """Other explicitly configured launchers can supply their own advertised IDs.
    Saved product profiles alone do not imply a launchable client."""
    found = {}
    for name, definition in definitions.items():
        if name in accounts:
            continue
        models = [m for m in array(obj(definition).get('models')) if isinstance(m, str)]
        if models:
            launcher = launchers[name]
            found[name] = {'family': launcher['family'], 'provider': name,
                'sources': ['paseo'], 'status': launcher['status'], 'models': models,
                'billing': 'unknown'}
    return found


def _discover_pi(home, environ, now, definitions, cache, accounts, launcher):
    """Pi signed in to ChatGPT. Signed in as a native Codex account it shares that account's quota (`quota_account`)."""
    raw_pi = resolve_definition('pi', definitions)[1].get('PI_CODING_AGENT_DIR')
    pi_home = _expand_home(raw_pi, home) if raw_pi else home / '.pi/agent'
    pi_auth, _ = read_json(pi_home / 'auth.json')
    pi_codex = obj(pi_auth.get('openai-codex'))
    pi_installed = bool(_which('pi', environ.get('PATH')))
    status = launcher['status']
    if status == 'ready' and not pi_installed and not pi_codex.get('access'):
        status = 'missing_client'
    launchers = {'pi': {**launcher, 'status': status}}
    if pi_codex.get('access'):
        pi_facts = auth_facts('codex', {'tokens': {'access_token': pi_codex.get('access'),
                                                   'account_id': pi_codex.get('accountId')}}, pi_home)
        matched_codex = next(
            (cname for cname, crow in accounts.items()
             if crow.get('family') == 'codex' and crow.get('identity') and crow.get('identity') == pi_facts.get('identity')),
            None,
        )
        pi_cached = obj(cache.rows.get('pi'))
        pi_matches = bool(pi_cached.get('credential_key') and pi_cached.get('credential_key') == pi_facts.get('credential_key'))
        # Pi's login carries no id_token; its plan is what the usage API or the account it signs in as reports.
        pi_online = configured_plan('codex', pi_cached.get('plan_label')) if pi_matches and pi_cached.get('plan_label') else None
        pi_plan = pi_facts['plan'] or pi_online or (accounts[matched_codex].get('plan') if matched_codex else None)
        pi_row = {
            'family': 'pi',
            'quota_family': 'codex',
            'provider': 'pi',
            'home': str(pi_home),
            'cli_installed': pi_installed,
            'sources': ['native'] + (['paseo'] if 'pi' in definitions else []),
            'status': status,
            'plan': pi_plan,
            'credential_key': pi_facts['credential_key'],
            'identity': pi_facts['identity'],
            'billing': 'subscription',
            **({'plan_source': 'usage_api', 'plan_read_at': pi_cached.get('fetched_at')} if not pi_facts['plan'] and pi_online else {}),
            **({'quota_account': matched_codex} if matched_codex else {}),
        }
        binding = {'identity': pi_facts['identity'], 'credential_identity': pi_facts.get('credential_identity'),
                   'base': '', 'key': None}
        if pi_matches:
            pi_row['usage_binding'] = 'matches'
            _apply_collector_refusal(pi_row, pi_cached, cache.polls.get('pi'), cache.attempts.get('pi'), now,
                                     COLLECTOR_REJECTED['codex'])
        elif pi_cached:
            pi_row['usage_binding'] = 'changed'
        return {'accounts': {'pi': pi_row}, 'launchers': launchers, 'bindings': {'pi': binding}}
    if pi_installed or pi_home.is_dir() or (home / '.pi').is_dir():
        return {'accounts': {'pi': {
            'family': 'pi',
            'provider': 'pi',
            'home': str(pi_home),
            'cli_installed': pi_installed,
            'sources': ['native'] + (['paseo'] if 'pi' in definitions else []),
            'status': 'disabled' if status == 'disabled' else 'missing_credentials',
            'plan': None,
            'billing': 'subscription',
        }}, 'launchers': launchers}
    return {'launchers': launchers}


def _load_accounts_override(environ, state_dir):
    override_env = environ.get('AGENTCOMPASS_ACCOUNTS_OVERRIDE')
    override_path = Path(override_env).expanduser() if override_env else state_dir / 'accounts-override.json'
    import accounts_override
    return accounts_override.load_override(override_path) or {}


def _override_budget(pspec, pcached):
    """A positive budget from the override or the cached reading's details, else a '$N' plan label."""
    details = obj(pcached.get('usage_details'))
    for raw_budget in (pspec.get('budget_usd'), details.get('budget_usd')):
        if isinstance(raw_budget, (int, float)) and not isinstance(raw_budget, bool) and raw_budget > 0:
            return float(raw_budget)
    plabel = str(pcached.get('plan_label') or '').strip()
    if plabel.startswith('$'):
        try:
            parsed = float(plabel[1:].split()[0].replace(',', ''))
        except ValueError:
            parsed = 0.0
        if parsed > 0:
            return parsed
    return None


def _override_meters(override_doc, cache_rows, accounts):
    """Metered dollar accounts the user declared in accounts-override.json with an endpoint and an API key."""
    found, launchers = {}, {}
    for pname, pspec in obj(override_doc.get('accounts')).items():
        if pname in accounts or not isinstance(pspec, dict) or pspec.get('disabled') is True:
            continue
        if str(pspec.get('billing') or '').strip().lower() != 'metered':
            continue
        ep = str(pspec.get('endpoint') or '').strip()
        key = str(pspec.get('api_key') or '').strip()
        import state_upgrade
        if state_upgrade.legacy_meter_field_names(pspec):
            # The fields are not a budget and not a window. A complete account is listed so the tray can say why.
            if ep and key:
                pfamily = str(pspec.get('family') or pspec.get('provider') or 'codex')
                found[pname] = {
                    'family': pfamily,
                    'provider': pname,
                    'sources': ['router-override'],
                    'status': account_state.LEGACY_METER,
                    'reason': state_upgrade.LEGACY_METER_REASON,
                    'plan': 'metered USD',
                    'billing': 'metered',
                    'backend_kind': 'metered_usd',
                }
                launchers[pname] = {'family': pfamily, 'status': 'paused'}
            continue
        if not ep or not key:
            continue
        budget_usd = _override_budget(pspec, obj(cache_rows.get(pname)))
        pfamily = str(pspec.get('family') or pspec.get('provider') or 'codex')
        pmodels = [m for m in array(pspec.get('models')) if isinstance(m, str)]
        found[pname] = {
            'family': pfamily,
            'provider': pname,
            'sources': ['router-override'],
            'status': 'ready',
            'plan': f'${budget_usd:g}' if budget_usd is not None else 'metered USD',
            'billing': 'metered',
            'backend_kind': 'metered_usd',
            **({'budget_usd': budget_usd} if budget_usd is not None else {}),
            **({'models': pmodels} if pmodels else {}),
            **({'cwd_regex': pspec['cwd_regex']} if pspec.get('cwd_regex') else {}),
        }
        launchers[pname] = {'family': pfamily, 'status': 'ready'}
    return {'accounts': found, 'launchers': launchers}


def _web_bridges(home, environ, web_home):
    """Dot and the ChatGPT Web bridge, from their local configuration."""
    found = {name: {'family': name, 'provider': name, 'sources': ['native'], 'status': status}
             for name, status in (('dot', dot_configuration(home, environ)),
                                  ('chatgpt-web', consult_configuration(web_home)))}
    # The bridge is only ready when its config reports proAvailable: a ready bridge is a Pro web seat.
    if found['chatgpt-web']['status'] == 'ready':
        found['chatgpt-web']['plan'] = 'pro'
    return found


def _discover_grok_bot(state_dir, environ):
    """Remote external runner. No model benchmarks, inferred quota or credential reads."""
    bot_config, bot_error = read_json(state_dir / 'grok-bot/config.json')
    bot_configured = bot_error is None and isinstance(bot_config.get('bot_id'), str) and bool(bot_config['bot_id'].strip())
    bot_status = 'missing_configuration' if not bot_configured else \
        'ready' if GROK_BOT_CLI.is_file() and _which('node', environ.get('PATH')) else 'missing_client'
    row = {
        'family': 'grok-bot', 'provider': 'grok-bot', 'sources': ['native'], 'status': bot_status,
        'billing': 'unknown', 'execution': 'remote', 'dispatch': 'automatic',
        'capabilities': ['text_prompt', 'thread_read'], 'auth_check': 'upstream_at_dispatch',
    }
    return {'accounts': {'grok-bot': row}, 'launchers': {'grok-bot': {'family': 'grok-bot', 'status': bot_status}}}


def read_cc_switch(home, environ, definitions, result, bindings):
    """CC Switch records bind to the accounts already found; unbound records are listed as saved."""
    _, _, grok_enabled = resolve_definition('grok', definitions)
    cc_path = product_root('cc-switch', home, environ) / 'cc-switch.db'
    result['source_paths']['cc-switch'] = str(cc_path)
    rows, cc_error = cc_switch(cc_path)
    result['sources']['cc-switch'] = cc_error or 'read'
    for entry, config in rows:
        family = 'grok' if entry['family'] == 'grokbuild' else entry['family']
        if family == 'grok' and entry['current']:
            if 'cc-switch' not in result['accounts']['grok']['sources']:
                result['accounts']['grok']['sources'].append('cc-switch')
            if grok_enabled:
                result['accounts']['grok']['status'] = 'ready'
                if entry.get('healthy') is False:
                    result['accounts']['grok'].update(status='paused', reason='unhealthy_in_cc_switch')
        base, token, models = product_config(family, config)
        facts = auth_facts(family, config.get('auth') or {}, home) if family in ('claude', 'codex') else {}
        matched = [name for name, binding in bindings.items() if result['accounts'][name]['family'] == family and
                   ((facts.get('identity') and facts['identity'] == binding['identity']) or
                    (base and token and base == binding['base'] and digest(token) == binding['key']))]
        # Claude Official normally has no saved OAuth: it uses the active native sign-in.
        if not matched and entry['current'] and entry['category'] == 'official' and family in ('claude', 'grok') and (family == 'grok' or not base):
            if result['accounts'].get(family, {}).get('billing') == 'subscription':
                matched = [family]
        for name in matched:
            if 'cc-switch' not in result['accounts'][name]['sources']:
                result['accounts'][name]['sources'].append('cc-switch')
            result['accounts'][name]['display_name'] = entry['name']
            if models and result['accounts'][name].get('billing') != 'subscription':
                result['accounts'][name]['models'] = models
            if entry.get('healthy') is False:
                result['accounts'][name].update(status='paused', reason='unhealthy_in_cc_switch')
        result['saved'].append({**entry, 'bound_to': matched, 'models': models,
                                'plan': facts.get('plan'), 'status': 'paused' if entry.get('healthy') is False else 'bound' if matched else 'saved'})


def _pause_disabled_plugins(result, state_dir):
    """A plugin the user switched off in the AgentCompass panel takes its account out of routing at once."""
    plugin_state, _ = read_json(state_dir / 'plugins.json')
    plugin_rows = obj(plugin_state.get('plugins'))
    for plugin_id, account in (('dot2api', 'dot'), ('chatgpt-web', 'chatgpt-web')):
        if obj(plugin_rows.get(plugin_id)).get('enabled') is False and account in result['accounts']:
            result['accounts'][account].update(status='paused', reason='plugin_disabled_in_agentcompass')


def _sync_launcher_status(result):
    for name, row in result['accounts'].items():
        if name in result['launchers']:
            result['launchers'][name]['status'] = row['status']


def _latch_exhausted_quota(accounts, state_dir, cache_rows):
    """Confirmed quota exhaustion (quota_exhaustion) holds the whole account, or only the windows that ran out."""
    import quota_exhaustion
    exhaustion_path = state_dir / 'quota-exhaustion.json'
    exhausted_accounts = obj(read_json(exhaustion_path)[0].get('accounts')) if exhaustion_path.is_file() else {}
    for name, row in accounts.items():
        if not obj(exhausted_accounts.get(name)).get('blocked'):
            continue
        latched = quota_exhaustion.exhausted_windows(name, cache_rows.get(name), path=exhaustion_path)
        if quota_exhaustion.ALL in latched:
            row.update(status='quota_exhausted', reason='confirmed quota exhausted; refresh quota after recovery')
        elif latched:
            # Only these windows are out; the account's other windows stay routable.
            row['exhausted_windows'] = sorted(latched)


def _assign_quota_owners(accounts):
    owners = {}
    ordered = sorted(
        accounts,
        key=lambda name: (
            accounts[name]['status'] != 'ready',
            accounts[name]['status'] not in account_state.LISTED_STATES,
            name != accounts[name]['family'],
            name,
        ),
    )
    for name in ordered:
        row = accounts[name]
        ident = row.get('identity')
        if ident and (row.get('family') in ('claude', 'codex') or not row.get('quota_account')):
            row['quota_account'] = owners.setdefault((row['family'], ident), name)
    for name in ordered:
        row = accounts[name]
        ident = row.get('identity')
        qfam = row.get('quota_family') or row['family']
        if ident and row.get('quota_account') and (qfam, ident) in owners:
            row['quota_account'] = owners[(qfam, ident)]


LIVE_PLAN_SOURCES = ('usage_api', 'profile_api')     # a plan read live with this account's own credential


def _share_online_plan(rows):
    """Accounts on one subscription have one plan: the newest usage-API plan_type among them."""
    online = {}
    for row in rows.values():
        owner = row.get('quota_account')
        if owner and row.get('plan_source') in LIVE_PLAN_SOURCES and str(row.get('plan_read_at') or '') >= online.get(owner, ('', ''))[0]:
            online[owner] = (str(row.get('plan_read_at') or ''), row['plan'])
    for row in rows.values():
        owner = row.get('quota_account')
        if owner in online and row.get('billing') == 'subscription':
            read_at, plan = online[owner]
            if row.get('plan_source') in LIVE_PLAN_SOURCES and str(row.get('plan_read_at') or '') >= read_at:
                continue
            row.update(plan=plan, plan_source='usage_api_shared', plan_read_at=read_at)


def _reads_usage(name, row, override_doc=None):
    """Subscription accounts the collector reads. An installed agy with no proven sign-in is not an account yet."""
    if row.get('billing') != 'subscription':
        return False
    family = row.get('family')
    if family in ('claude', 'codex', 'pi'):
        return True
    if family == 'antigravity':
        verified = obj(obj((override_doc or {}).get('accounts')).get(name)).get('verified') is True
        return sign_in_proven(row) or verified
    if family == 'omp':
        return row.get('quota_account') not in (None, name)   # a login of its own has no collector
    return family == 'grok' and bool(row.get('usage_windows') or row.get('usage_read_failed'))


def _credential_identity(slot, rows, bindings):
    return (bindings or {}).get(slot, {}).get('credential_identity') or rows[slot].get('credential_key')


def _refused_at(slot, cache_rows):
    crow = obj(cache_rows.get(slot))
    return account_state._time(crow.get('error_at') or crow.get('fetched_at'))


def _quota_members(rows):
    """Account names by the subscription (quota owner) they draw on."""
    members = {}
    for name, row in rows.items():
        members.setdefault(row.get('quota_account') or name, []).append(name)
    return members


def _lift_superseded_refusals(rows, members, cache_rows, now, bindings):
    """A sibling with a good reading newer than a cached refusal supersedes that stale refusal (e.g. after renewal)."""
    for group in members.values():
        good_by_slot = {}
        for slot in group:
            if rows[slot].get('usage_binding') == 'changed':
                continue
            issue, good_iso = account_state.reading(cache_rows.get(slot), now)
            qfam = rows[slot].get('quota_family') or rows[slot].get('family')
            if issue is None and not account_state.plan_is_inactive(qfam, rows[slot].get('plan')):
                good_time = account_state._time(good_iso)
                if good_time is not None:
                    good_by_slot[slot] = good_time
        newest_group_good = max(good_by_slot.values(), default=None)
        for slot in group:
            crow = obj(cache_rows.get(slot))
            ref_at = _refused_at(slot, cache_rows)
            if rows[slot].get('status') == account_state.PLAN_INACTIVE and account_state.usage_refused_plan(crow):
                if newest_group_good is not None and (ref_at is None or newest_group_good > ref_at):
                    rows[slot]['status'] = account_state.READY
                    rows[slot].pop('reason', None)
                    rows[slot].pop('plan_inactive_at', None)
                    rows[slot].pop('plan_inactive_retry_at', None)
            elif rows[slot].get('status') == account_state.AUTH_FAILED:
                cid = _credential_identity(slot, rows, bindings)
                newest_cred_good = max((t for s, t in good_by_slot.items()
                                        if cid and _credential_identity(s, rows, bindings) == cid), default=None)
                if newest_cred_good is not None and (ref_at is None or newest_cred_good > ref_at):
                    rows[slot]['status'] = account_state.READY
                    rows[slot].pop('reason', None)


def _usage_reading(name, row, rows, group, cache_rows, now, override_doc):
    """Whether the collector reads this account and, when it does, the reading's problem and last good time.
    Readings of the same subscription count for each other; a reading taken with another credential does not."""
    if not _reads_usage(name, row, override_doc):
        return False, None, None
    found = [('credential_changed', None) if rows[other].get('usage_binding') == 'changed'
             else account_state.reading(cache_rows.get(other), now) for other in group]
    good = [last for issue, last in found if issue is None]
    times = sorted(last for _, last in found if last)
    problem, last_good = (None, max(good)) if good else (found[0][0], times[-1] if times else None)
    row['last_success_at'] = last_good
    return True, problem, last_good


def _live_latch(name, row, rows, latches, good_at, state_dir, now):
    """The plan-inactive latch holding this account (its own or its quota owner's), sealed to the credential it holds;
    a latch the account has outlived is cleared."""
    latch_name = name if name in latches else row.get('quota_account') if row.get('quota_account') in latches else None
    latch = latches.get(latch_name) if latch_name else None
    if latch and not latch.get('credential_key'):
        latch_row = rows.get(latch_name) or row
        if latch_row.get('credential_key'):
            online_plan = latch_row.get('plan') if latch_row.get('plan_source') in account_state.ONLINE_PLAN_SOURCES else None
            account_state.seal_latch_credential(latch_name, latch_row['credential_key'], online_plan=online_plan,
                                                state_dir=state_dir, expected_observed_at=latch.get('observed_at'))
            latch['credential_key'] = latch_row['credential_key']
            if online_plan and not latch.get('online_plan'):
                latch['online_plan'] = online_plan
    if latch and account_state.latch_outlived(latch, good_at, row, now=now):
        if account_state.clear_latch(latch_name, state_dir=state_dir, expected_observed_at=latch.get('observed_at')):
            latches.pop(latch_name, None)
            latch = None
    return latch


def _lift_provider_hold(name, row, good_at, state_dir):
    """Re-login recovery: an account held because its provider refused it (provider_retry) lifts the same way, on a
    good usage reading newer than the hold or another credential. Accounts without a usage reader keep a clear."""
    try:
        provider_retry.lift_after_reading(name, last_good=good_at,
                                          credential_key=row.get('credential_key'),
                                          path=Path(state_dir) / provider_retry.FILE
                                          if state_dir and not os.environ.get('ROUTER_PROVIDER_RETRY') else None)
    except OSError:
        pass


def _settle_ready_account(name, row, rows, group, latch, reads, problem, last_good, cache_rows, previous_row, now,
                          hours, bindings):
    """A ready account takes, in order, a quota sibling's inactive plan or rejected login, its own inactive plan, its
    latch, or its failing reading."""
    inactive_peer = next(
        (rows[other] for other in group
         if rows[other].get('usage_binding') != 'changed' and rows[other].get('status') == account_state.PLAN_INACTIVE),
        None,
    )
    cred_id = _credential_identity(name, rows, bindings)
    auth_peer = next(
        (rows[other] for other in group
         if rows[other].get('usage_binding') != 'changed' and rows[other].get('status') == account_state.AUTH_FAILED
         and cred_id and cred_id == _credential_identity(other, rows, bindings)),
        None,
    )
    if inactive_peer is not None:
        row.update(status=account_state.PLAN_INACTIVE, reason=inactive_peer.get('reason'))
        for k in ('plan_inactive_at', 'plan_inactive_retry_at'):
            if inactive_peer.get(k):
                row[k] = inactive_peer[k]
    elif auth_peer is not None:
        row.update(status=account_state.AUTH_FAILED, reason=auth_peer.get('reason'))
    elif account_state.plan_is_inactive(row.get('quota_family') or row.get('family'), row.get('plan')):
        row.update(status=account_state.PLAN_INACTIVE, reason=f"plan {row.get('plan')}")
    elif latch:
        row.update(status=account_state.PLAN_INACTIVE, reason=account_state.latch_reason(latch),
                   plan_inactive_at=latch.get('observed_at'),
                   plan_inactive_retry_at=account_state.latch_retry_at(latch))
    elif reads and problem and cache_rows:
        cached_at = next((obj(cache_rows.get(o)).get('error_at') or obj(cache_rows.get(o)).get('fetched_at')
                          for o in group
                          if obj(cache_rows.get(o)).get('error_at') or obj(cache_rows.get(o)).get('fetched_at')), None)
        account_state.failing(row, problem, last_good, previous_row, now, hours, cached_at=cached_at)


def _mirror_grok_onto_bot(result):
    """A ready grok-bot takes the state of a Grok account that is not dispatchable for its plan, login or reading."""
    rows = result['accounts']
    row = rows.get('grok')
    bot_row = rows.get('grok-bot')
    if (isinstance(row, dict) and isinstance(bot_row, dict)
            and bot_row.get('status') == account_state.READY
            and row.get('status') in (account_state.PLAN_INACTIVE, account_state.AUTH_FAILED, account_state.USAGE_FAILING)
            and not account_state.dispatchable(row)):
        for k in ('status', 'failing_since', 'exclude_after_hours', 'usage_excluded',
                  'last_success_at', 'plan_inactive_at', 'plan_inactive_retry_at'):
            if k in row:
                bot_row[k] = row[k]
        if row.get('reason'):
            bot_row['reason'] = row.get('reason')
        if 'grok-bot' in result['launchers']:
            result['launchers']['grok-bot']['status'] = bot_row['status']


def _settle_account_states(result, cache_rows, previous, state_dir, now, environ, override_doc, bindings=None):
    """Give each account its one state (account_state). A snapshot with no rows at all means no collector has run on
    this machine; route_judge.readiness_gap reports that, so accounts are not each marked as failing."""
    rows = result['accounts']
    members = _quota_members(rows)
    previous_rows = obj(previous.get('accounts'))
    hours = account_state.exclude_after_hours(environ, override_doc)
    latches = account_state.latched(state_dir)
    _lift_superseded_refusals(rows, members, cache_rows, now, bindings)
    for name, row in rows.items():
        group = sorted(members.get(row.get('quota_account') or name) or [name], key=lambda other: other != name)
        reads, problem, last_good = _usage_reading(name, row, rows, group, cache_rows, now, override_doc)
        good_at = last_good if problem is None else None
        latch = _live_latch(name, row, rows, latches, good_at, state_dir, now)
        if reads:
            _lift_provider_hold(name, row, good_at, state_dir)
        if row.get('status') != account_state.READY:
            continue
        _settle_ready_account(name, row, rows, group, latch, reads, problem, last_good, cache_rows,
                              previous_rows.get(name), now, hours, bindings)
        if name in result['launchers'] and not account_state.dispatchable(row):
            result['launchers'][name]['status'] = row['status']
    _mirror_grok_onto_bot(result)
    _assign_quota_owners(rows)


# The variables that point an account directory elsewhere, with the directory each names by default.
ACCOUNT_DIR_VARIABLES = (('CLAUDE_CONFIG_DIR', '.claude'), ('CLAUDE_SECURESTORAGE_CONFIG_DIR', '.claude'),
                         ('CODEX_HOME', '.codex'), ('PI_CODING_AGENT_DIR', '.pi/agent'))


# The harnesses whose native sub-agents run inside the calling session, on its own account, with the variable that
# names that account's directory and its default under the home.
SESSION_ACCOUNT_DIRS = {'claude': ('CLAUDE_CONFIG_DIR', '.claude'), 'codex': ('CODEX_HOME', '.codex')}


def session_account(family, inventory, environ=None, home=None):
    """The account a session of `family` runs on: the one discovered account of that family whose home is the directory
    the session's environment names (SESSION_ACCOUNT_DIRS). None when that is not recorded (another family, no such
    row, or more than one): never guessed. Read-only."""
    if family not in SESSION_ACCOUNT_DIRS:
        return None
    environ = os.environ if environ is None else environ
    home = Path(home or environ.get('ROUTER_PROVIDER_HOME') or Path.home())
    key, default = SESSION_ACCOUNT_DIRS[family]
    own = _expand_home(environ.get(key) or str(home / default), home).resolve()
    rows = obj((inventory or {}).get('accounts'))
    found = [name for name, row in rows.items() if isinstance(row, dict) and row.get('family') == family
             and row.get('home') and _expand_home(row['home'], home).resolve() == own]
    return found[0] if len(found) == 1 else None


def environment_rewrites_accounts(home, environ=None):
    """True when this process's environment points an account directory somewhere else (a worker started on another
    account). Discovery ignores those variables, but such a process does not speak for the machine's shared files."""
    environ = os.environ if environ is None else environ
    for key, default in ACCOUNT_DIR_VARIABLES:
        value = environ.get(key)
        if value and _expand_home(value, Path(home)).resolve() != (Path(home) / default).resolve():
            return True
    return False


def current():
    # Reread local product files each time; do not contact any gateway.
    if _SCOPE and 'current' in _SCOPE[0]:
        return copy.deepcopy(_SCOPE[0]['current'])
    result = discover()
    home = Path(os.environ.get('ROUTER_PROVIDER_HOME') or Path.home())
    target = Path(os.environ.get('ROUTER_STATE_DIR') or home / '.agent-compass') / 'provider-inventory.json'
    try:
        fingerprint = json.dumps({k: v for k, v in result.items() if k != 'generated_at'}, sort_keys=True)
        if ((_LAST_PUBLISHED_INVENTORY.get(target) != fingerprint or not target.is_file())
                and not environment_rewrites_accounts(home)):
            write_json(target, result)
            _LAST_PUBLISHED_INVENTORY[target] = fingerprint
    except OSError:
        pass
    if _SCOPE:
        _SCOPE[0]['current'] = copy.deepcopy(result)
    return result


def launcher_family(provider):
    if provider in ('claude', 'codex', 'pi', 'omp', 'opencode', 'antigravity-resilient'):
        return provider
    row = current().get('launchers', {}).get(provider) or {}
    return row.get('family') if row.get('status') == 'ready' else None


def account_family(account, accounts=None, inventory=None):
    """Resolve account type from discovery or its explicit bundle specification, never its name."""
    if inventory is None:
        inventory = (accounts or {}).get('_discovery')
    if inventory is None:
        inventory = current()
    row = obj(obj(inventory.get('accounts')).get(account))
    spec = obj(obj((accounts or {}).get('accounts')).get(account))
    if row.get('family') or spec.get('family'):
        return row.get('family') or spec['family']
    families = {b.get('harness') or b.get('provider') for b in obj(spec.get('bundles')).values()
                if isinstance(b, dict)} - {None}
    return next(iter(families)) if len(families) == 1 else None


# The plan names each family reports or a user may write, word for word once the vendor's name is dropped. Anything
# else stays what it is, has no template, and is priced at UNKNOWN_PLAN_PRICED_AS with a warning. `prolite` is the usage
# API's name for the $100 tier (an inference from the Codex binary and the price ladder), so it is `pro100`, never `pro`.
PLAN_NAMES = {
    'claude': {'pro': 'pro', 'max': 'max', 'max5': 'max5', 'max 5x': 'max5', 'max x5': 'max5', '5x': 'max5',
               'x5': 'max5', 'max20': 'max20', 'max 20x': 'max20', 'max x20': 'max20', '20x': 'max20',
               'x20': 'max20', 'free': 'free', 'team': 'team', 'enterprise': 'enterprise'},
    'codex': {'plus': 'plus', 'pro': 'pro', 'pro100': 'pro100', 'pro 100': 'pro100', '100': 'pro100',
              'prolite': 'pro100', 'pro lite': 'pro100', 'free': 'free', 'team': 'team', 'enterprise': 'enterprise'},
}
UNKNOWN_PLAN_PRICED_AS = {'claude': 'pro', 'codex': 'plus'}


def configured_plan(family, label, accounts=None, shipped=None):
    raw = str(label or '').lower()
    if not raw.strip():
        return raw
    names = PLAN_NAMES.get(family)
    if names is not None:
        for candidate in (raw, account_state.strip_pool_count(raw)):
            words = account_state.plan_words(candidate)
            if words in names:
                return names[words]
            without_vendor = account_state.plan_without_vendor(candidate)
            if without_vendor in names:
                return names[without_vendor]
    table = plan_table(accounts, family, shipped=shipped)
    if table:
        tier_map = {}
        for plan_id, entry in table.items():
            if not isinstance(entry, dict):
                continue
            for token in (plan_id, *array(entry.get('tiers'))):
                if isinstance(token, str) and token.strip():
                    w = account_state.plan_words(token)
                    if w:
                        tier_map.setdefault(w, plan_id)
        for candidate in (raw, account_state.strip_pool_count(raw)):
            words = account_state.plan_words(candidate)
            stripped_enum = words.removeprefix('subscription tier ').strip()
            without_vendor = account_state.plan_without_vendor(candidate)
            for key in (words, stripped_enum, without_vendor):
                if key and key in tier_map:
                    return tier_map[key]
    return raw


def unavailable_reason(inventory, account, provider=None):
    accounts = obj(inventory.get('accounts'))
    prov_row = obj(accounts.get(provider)) if provider and provider != account else {}
    row = prov_row if prov_row.get('status') in account_state.LISTED_STATES else obj(accounts.get(account))
    launcher = obj(obj(inventory.get('launchers')).get(provider or account))
    if account_state.unavailable_text(row):
        return f'provider discovery: {account_state.unavailable_text(row)}'
    reason = (row.get('reason') or row.get('status')) if row.get('status') is not None and not account_state.dispatchable(row) else launcher.get('status')
    if reason and reason != 'ready':
        return f'provider discovery: {reason}; restore the account in its local product or sign in again, then reroute'
    return None


def _auto_catalog(inventory, live, now_epoch, environ=None):
    """Advertised models per provider: configured/discovered lists, plus the tray model-catalog cache when live."""
    env = os.environ if environ is None else environ
    providers = {}
    for name, row in (inventory.get('accounts') or {}).items():
        models = [m for m in (row.get('models') or []) if isinstance(m, str)]
        magpie_eps = [p for p in (row.get('magpie_providers') or []) if isinstance(p, str) and p]
        if models and row.get('status', 'ready') == 'ready':
            providers[name] = {'ok': True, 'type': 'configured', 'checked_at': now_epoch, 'models': models,
                               **({'endpoint_providers': magpie_eps} if magpie_eps else {})}
    if live:
        home = Path(env.get('ROUTER_PROVIDER_HOME') or Path.home())
        cache, _ = read_json(Path(env.get('ROUTER_STATE_DIR') or home / '.agent-compass') / 'model-catalog.json')
        for name, entry in obj(cache.get('providers')).items():
            if not isinstance(entry, dict) or entry.get('type') == 'static':
                continue
            if name in providers:
                ids = {(m.get('id') if isinstance(m, dict) else m) for m in entry.get('models') or []}
                extra = [m for m in providers[name]['models'] if m not in ids]
                eps = providers[name].get('endpoint_providers')
                entry = {**entry, 'models': list(entry.get('models') or []) + extra,
                         **({'endpoint_providers': eps} if eps else {})}
            providers[name] = entry
    return {'providers': providers}


def _apply_auto_bundles(accounts, inventory, live, environ=None):
    """Runtime-derived bundles (auto_bundles) replace the retired per-proxy `__high` synthesis.

    Read-only: the `seen` file is read when live; the tray model refresh is the writer.
    """
    import time
    import auto_bundles
    now_epoch = time.time()
    families = {name: row.get('family') for name, row in (inventory.get('accounts') or {}).items()}
    env = os.environ if environ is None else environ
    home = Path(env.get('ROUTER_PROVIDER_HOME') or Path.home())
    state = Path(env.get('ROUTER_STATE_DIR') or home / '.agent-compass')
    seen = auto_bundles.read_seen(state / 'auto-bundles-seen.json') if live else {}
    derived = auto_bundles.derive(accounts, _auto_catalog(inventory, live, now_epoch, environ), now_epoch,
                                  seen=seen, account_families=families)
    for account, rows in derived['bundles'].items():
        for bundle in rows.values():
            reason = unavailable_reason(inventory, account, bundle.get('provider', account))
            if reason:
                bundle['discovery_unavailable'] = reason
            if bundle.get('effort'):
                accounts.setdefault('dispatch_efforts', {}).setdefault(account, {}).setdefault(bundle['model'], [bundle['effort']])
    for account, rows in derived['bundles'].items():
        target = accounts['accounts'][account].setdefault('bundles', {})
        for bid, bundle in rows.items():
            target.setdefault(bid, bundle)
    accounts['_auto_bundles'] = {'excluded': derived['excluded'],
                                 'seen': derived['seen'] if live else {}}


def listed_rows(accounts, account, provider, model, effort, live_doc):
    """({bundle id: row}, None) for a model the user named on `account` that has no row there, when the account's
    provider lists it in `live_doc` (live_models.load_or_refresh); else (None, the fact that refuses it). The rows are
    what discovery derives for an advertised model (auto_bundles), with the provider's list as the authority over a
    family guessed from the name. A row carries the effort the user named where its harness takes one. Read-only."""
    import time
    import auto_bundles
    import live_models
    entry = ((live_doc or {}).get('providers') or {}).get(provider)
    if not isinstance(entry, dict):
        off = '' if live_models.enabled() else ' (live model lists are off: AGENTCOMPASS_LIVE_MODELS)'
        return None, f'the model list of provider {provider} could not be read{off}'
    if entry.get('ok') is not True:
        return None, (f'the model list of provider {provider} could not be read '
                      f"({live_models.unavailable_detail(entry) or entry.get('error') or 'model_list_unavailable'})")
    if not live_models.offers_model(provider, model, entry):
        return None, f'provider {provider} does not list {model}'
    families = {name: row.get('family') for name, row in (((accounts.get('_discovery') or {}).get('accounts')) or {}).items()}
    derived = auto_bundles.derive(accounts, {'providers': {provider: {'ok': True, 'checked_at': time.time(),
                                                                      'models': [model]}}},
                                  time.time(), account_families=families, named={(account, model)})
    rows = dict(derived['bundles'].get(account) or {})
    if not rows:
        excluded = [e['reason'] for e in derived['excluded'] if e.get('account') == account]
        return None, (f"{account} cannot launch it ({'; '.join(excluded)})" if excluded
                      else f'account {account} does not launch through provider {provider}')
    if effort:
        named_rows = {}
        for row in rows.values():
            if auto_bundles.HARNESS_DEFAULT_EFFORT.get(row.get('harness')) is not None or row.get('effort'):
                row = dict(row, effort=effort)
            named_rows[auto_bundles.auto_bundle_id(account, row.get('harness'), row['model'], row.get('effort'))] = row
        rows = named_rows
    return rows, None


def with_listed_rows(accounts, listed):
    """A copy of `accounts` with the rows `listed_rows` derived (`{'account', 'rows'}`) for one calculation, and their
    efforts in the launch contract: never written to defaults or settings."""
    if not isinstance(listed, dict) or not listed.get('rows'):
        return accounts
    out = copy.deepcopy(accounts)
    account = listed['account']
    target = out['accounts'][account].setdefault('bundles', {})
    for bid, row in listed['rows'].items():
        target.setdefault(bid, dict(row))
        if row.get('effort'):
            efforts = out.setdefault('dispatch_efforts', {}).setdefault(account, {}).setdefault(row['model'], [])
            if row['effort'] not in efforts:
                efforts.append(row['effort'])
    return out


UNVERIFIABLE_SIGN_IN = ('antigravity', 'opencode', 'grok')
UNVERIFIED_SIGN_IN_LABEL = 'installed, sign-in unverified'
# Plans whose models run without any account: there is no sign-in to prove (OpenCode's free models).
NO_SIGN_IN_PLANS = {'opencode': ('free',)}


def needs_no_sign_in(row):
    return isinstance(row, dict) and row.get('plan') in NO_SIGN_IN_PLANS.get(row.get('family'), ())


def sign_in_proven(row):
    """True when discovery can tell this account is signed in, not merely that its CLI is installed."""
    if not isinstance(row, dict) or row.get('family') not in UNVERIFIABLE_SIGN_IN or needs_no_sign_in(row):
        return True
    sources = row.get('sources') or []
    if isinstance(sources, str):
        sources = [sources]
    return bool({'usage-cache', 'account-tier'} & set(sources)) or bool(row.get('identity') or row.get('credential_key'))


def launch_verified(row, previous):
    """Decide whether a discovered account may be a confident routing pick.

    Antigravity, OpenCode and Grok report status ready when the CLI is installed, which is not a
    sign-in. The shipped template leaves them unverified. A machine fleet that already marked the
    slot verified, or a usage-cache reading, keeps the previous launchable state. The status string
    itself stays `ready` so provider listings do not change.
    """
    if not isinstance(row, dict):
        return False
    ready = account_state.dispatchable(row)
    if row.get('family') not in UNVERIFIABLE_SIGN_IN or sign_in_proven(row):
        return ready
    return bool(previous is True and ready)


def account_state_label(row):
    """Same words setup uses when a CLI is installed but sign-in cannot be read."""
    status = row.get('status') if isinstance(row, dict) else None
    if (isinstance(row, dict) and row.get('family') in UNVERIFIABLE_SIGN_IN and status == 'ready'
            and not needs_no_sign_in(row)):
        return UNVERIFIED_SIGN_IN_LABEL
    return status


def apply(accounts, inventory=None, *, live=None, environ=None):
    """Discovery's accounts and the bundles derived from what their providers advertise, into `accounts`. `environ`
    locates the tray's model catalog and the `seen` file of another home (`agentcompass doctor`); default os.environ."""
    if live is None:
        live = inventory is None
    inventory = current() if inventory is None else inventory
    accounts['_discovery'] = inventory
    specs = accounts['accounts']
    templates = copy.deepcopy(specs)
    if inventory.get('accounts'):
        _drop_undiscovered_templates(accounts, inventory)
    shipped_templates = shipped_plan_templates()

    for name, row in inventory['accounts'].items():
        if name not in specs:
            if row['status'] not in account_state.LISTED_STATES:
                continue
            spec = _discovered_spec(name, row, templates, accounts)
            if spec is None:
                continue
            specs[name] = spec
        spec = specs[name]
        spec['verified'] = launch_verified(row, spec.get('verified'))
        spec['discovery_status'] = row['status']
        if row.get('cwd_regex') and 'cwd_regex' not in spec:
            spec['cwd_regex'] = row['cwd_regex']
        if row.get('backend_kind') == 'metered_usd':
            _settle_metered_usd_spec(spec, row)
            continue
        template, plan, quota_family = _settle_plan(spec, row, accounts, shipped_templates)
        _settle_unknown_tier(spec, row, template, plan, quota_family)
        _settle_bundles(spec, name, row, inventory, accounts)
    _apply_auto_bundles(accounts, inventory, live, environ)
    _fold_into_quota_owners(accounts, inventory)
    apply_shared_quota(accounts)
    return accounts


def _drop_undiscovered_templates(accounts, inventory):
    """Template accounts discovery did not find on this machine leave the account document."""
    specs = accounts['accounts']
    for name in list(specs):
        family = account_family(name, accounts, inventory)
        if family in ('claude', 'codex') and name != family:
            row = inventory['accounts'].get(name)
            if not row or row.get('status') == 'missing_credentials':
                specs.pop(name, None)
        # Oh My Pi's API-key side (the template `omp` account) when discovery found only subscription logins.
        if (family == 'omp' and name not in inventory['accounts']
                and obj(obj(inventory.get('launchers')).get('omp')).get('api_side') is False):
            specs.pop(name, None)


def _discovered_spec(name, row, templates, accounts):
    """The account document entry for a discovered account the document does not name, or None when it gets none."""
    family = row['family']
    if row.get('backend_kind') == 'metered_usd':
        spec = {
            'plan': row.get('plan') or 'metered USD',
            'billing': 'metered',
            'backend_kind': 'metered_usd',
            'verified': True,
            'expires_at': None,
            'windows': {},
            'bundles': {},  # auto_bundles derives one bundle per advertised model below
        }
        if row.get('status') == account_state.LEGACY_METER:
            import state_upgrade
            spec['legacy_meter'] = row.get('reason') or state_upgrade.LEGACY_METER_REASON
        else:
            budget = row.get('budget_usd')
            if isinstance(budget, (int, float)) and not isinstance(budget, bool) and budget > 0:
                spec['windows'] = {'balance': {}}
                spec['capacity_usd'] = {'balance': float(budget)}
        return spec
    if family == 'pi':
        if row.get('quota_account') and row.get('quota_account') != name:
            return None
        base_tpl = copy.deepcopy(templates.get('codex', {}))
        base_tpl['plan'] = row.get('plan') or 'unknown'
        base_tpl['billing'] = 'subscription'
        base_tpl['bundles'] = {
            f'{name}__{bid}': {**{k: v for k, v in b.items() if k != 'modeId'}, 'provider': 'pi', 'harness': 'pi'}
            for bid, b in base_tpl.get('bundles', {}).items()
            if b.get('provider') == 'pi'
        }
        return base_tpl
    if family == 'omp' and row.get('quota_family') in templates:
        # The family's own bundles, launched through omp with omp's `<provider>/<model>` ids. A login that
        # shares a native account's quota hands these to that account below (quota_account), beside its
        # native and Pi siblings; harness_order ranks the siblings.
        qfamily = row['quota_family']
        spec = copy.deepcopy(templates[qfamily])
        spec['billing'] = 'subscription'
        cached = set(row.get('omp_models') or [])
        spec['bundles'] = {
            f'{name}__{bid}': {'model': b['model'], **({'effort': b['effort']} if b.get('effort') else {}),
                               'provider': 'omp', 'harness': 'omp',
                               'launch_model': f"{row['omp_provider']}/{b.get('launch_model') or b['model']}"}
            for bid, b in spec.get('bundles', {}).items()
            if b.get('provider', qfamily) == qfamily and (not cached or (b.get('launch_model') or b['model']) in cached)}
        return spec
    if family == 'grok':
        return copy.deepcopy(templates.get('grok') or {
            'plan': 'unknown', 'billing': 'subscription', 'expires_at': None,
            'unmetered': True, 'windows': {},
            'bundles': {'grok47_high': {'provider': name, 'harness': 'grok', 'model': 'grok-4.7', 'effort': 'high'}},
        })
    if family == 'grok-bot':
        return {'plan': 'unknown', 'billing': 'unknown',
            'windows': {}, 'bundles': {
            'grok_bot': {'provider': name, 'harness': 'grok-bot', 'model': 'grok-bot'},
        }}
    if family in ('claude', 'codex') and family in templates:
        spec = copy.deepcopy(templates[family])
        if row.get('billing') == 'unknown':
            spec['billing'] = 'metered'
        spec['bundles'] = {f'{name}__{bid}': {**b, 'provider': name, 'harness': family} for bid, b in spec['bundles'].items()
                           if b.get('provider', family) == family}
        for bundle in spec['bundles'].values():
            bundle.setdefault('modeId', 'bypassPermissions' if family == 'claude' else 'full-access')
        efforts = accounts.get('dispatch_efforts')
        if isinstance(efforts, dict) and family in efforts and name not in efforts:
            efforts[name] = copy.deepcopy(efforts[family])
        return spec
    if row.get('models'):
        return {'plan': row.get('plan') or 'discovered',
            'billing': row.get('billing') or 'unknown', 'windows': {},
            'bundles': {}}  # auto_bundles derives these below
    return None


def _settle_metered_usd_spec(spec, row):
    """A metered dollar account: its plan label, and a balance window sized by its budget when it has one."""
    spec['billing'] = 'metered'
    spec['backend_kind'] = 'metered_usd'
    row_plan = row.get('plan')
    if isinstance(row_plan, str) and row_plan.strip():
        spec['plan'] = row_plan
    if row.get('status') == account_state.LEGACY_METER:
        import state_upgrade
        spec['legacy_meter'] = row.get('reason') or state_upgrade.LEGACY_METER_REASON
        spec['windows'] = {}
        spec.pop('capacity_usd', None)
        spec.setdefault('bundles', {})
        return
    spec.pop('legacy_meter', None)
    budget = row.get('budget_usd')
    if isinstance(budget, (int, float)) and not isinstance(budget, bool) and budget > 0:
        spec['windows'] = {'balance': {}}
        cap = spec.get('capacity_usd')
        if not isinstance(cap, dict):
            cap = {}
            spec['capacity_usd'] = cap
        cap['balance'] = float(budget)
    else:
        spec['windows'] = {}
        cap = spec.get('capacity_usd')
        if isinstance(cap, dict):
            cap.pop('balance', None)
            if not cap:
                spec.pop('capacity_usd', None)
    spec.setdefault('bundles', {})


def _settle_plan(spec, row, accounts, shipped_templates):
    """The discovered plan with its template's windows and capacity, and the discovered billing. Returns the template
    (None when no template names the plan), the plan and the family whose plans apply."""
    family = row['family']
    plan = row.get('plan')
    quota_family = row.get('quota_family') or family   # an omp OAuth login uses the plans of the family it signs in to
    # A plan the user wrote in the account document seeds the template when discovery reports none
    # (claude/codex without a discovered plan stay unknown below).
    template_plan = configured_plan(
        quota_family,
        plan or (spec.get('plan') if family not in ('claude', 'codex') else None),
        accounts=accounts,
        shipped=shipped_templates,
    )
    template = plan_defaults(accounts, quota_family, template_plan, shipped=shipped_templates) if template_plan else None
    # A plan no template names is unknown: it is priced at the family's smallest paid plan and warned about, never
    # at the largest. An account on a metered API key has no plan to know.
    priced_as = UNKNOWN_PLAN_PRICED_AS.get(quota_family) if template is None and row.get('billing') == 'subscription' else None
    spec.pop('plan_unknown', None)
    spec.pop('plan_priced_as', None)
    if priced_as and not account_state.plan_is_inactive(quota_family, plan):
        template = plan_defaults(accounts, quota_family, priced_as, shipped=shipped_templates)
        spec.update(plan_unknown=str(plan or template_plan or 'not reported'), plan_priced_as=priced_as)
    if plan:
        previous_plan = configured_plan(quota_family, spec.get('plan'), accounts=accounts, shipped=shipped_templates)
        spec['plan'] = plan
        if previous_plan == template_plan:
            pass  # same named plan can have account-specific promotional capacity
        elif template and family != 'grok':
            for key in TEMPLATE_KEYS:
                if key in template:
                    spec[key] = copy.deepcopy(template[key])
                else:
                    spec.pop(key, None)
    if template and family != 'grok' and not (family in ('claude', 'codex') and not plan):
        fill_template_gaps(spec, template)
    if row.get('billing') and row['billing'] != 'unknown':
        spec['billing'] = row['billing']
    if family in ('claude', 'codex') and (not plan or row.get('billing') == 'metered'):
        spec['plan'] = 'API' if row.get('billing') == 'metered' else 'unknown'
        if row.get('billing') == 'metered':
            spec['windows'] = {}
        elif spec.get('plan_priced_as'):
            for key in TEMPLATE_KEYS:
                if key in template:
                    spec[key] = copy.deepcopy(template[key])
    return template, plan, quota_family


def _mark_unknown_tier(spec, row, raw_label, not_reported, unrecognized):
    """A tier no plan template names: the plan is unknown, with the reader's own error or which label was not known."""
    is_placeholder = not account_state.plan_reported(raw_label)
    spec['plan'] = 'unknown'
    spec['plan_unknown'] = str(row.get('plan_error') or (not_reported if is_placeholder else f'{unrecognized} {raw_label!r}'))


def _settle_unknown_tier(spec, row, template, plan, quota_family):
    """Antigravity and Grok tiers that no template names, and Grok's usage windows."""
    family = row['family']
    if family == 'antigravity' and template is None and not account_state.plan_is_inactive(quota_family, plan):
        _mark_unknown_tier(spec, row, str(plan or spec.get('plan') or '').strip(),
                           'subscription tier not reported by loadCodeAssist', 'unrecognized Antigravity tier')
    if family == 'grok':
        window_ids = row.get('usage_windows') or []
        spec['unmetered'] = not bool(window_ids)
        if window_ids:
            spec.setdefault('windows', {}).update({wid: {'hours': 168, 'launch_min_remaining_pct': 5}
                                                   for wid in window_ids if wid not in spec.get('windows', {})})
        if template is None:
            _mark_unknown_tier(spec, row, str(plan or '').strip(),
                               'subscription tier not reported by Grok API', 'unrecognized tier')


def _settle_bundles(spec, name, row, inventory, accounts):
    """Mark bundles discovery cannot launch, and bind each to a model the configured provider advertises: an advertised
    name is the row model_resolution.resolve_in makes it (a manual bundle is a launcher's row: no endpoint is known)."""
    advertised = row.get('models')
    for bundle in spec.get('bundles', {}).values():
        reason = unavailable_reason(inventory, name, bundle.get('provider', name))
        if reason:
            bundle['discovery_unavailable'] = reason
        if isinstance(advertised, list):
            own = resolve_in(bundle['model'], accounts)['key'] or bundle['model']
            match = bundle.get('launch_model') if bundle.get('launch_model') in advertised else next(
                (m for m in advertised if (resolve_in(m, accounts)['key'] or m.rsplit('/', 1)[-1]) == own), None)
            if match:
                bundle['launch_model'] = match
            else:
                bundle['discovery_unavailable'] = 'model not advertised by the configured provider'


def _fold_into_quota_owners(accounts, inventory):
    """A second account on the owner's subscription (Pi signed in as the Codex account) re-derives what the owner
    already launches through the same launcher; the owner's rows and its enable/disable curation stand."""
    from account_fleet import bundle_harness
    specs = accounts['accounts']

    def launch_key(bid, bundle, account):
        model = resolve_in(bundle.get('model'), accounts)['key'] or bundle.get('model')
        return bundle.get('provider', account), bundle_harness(bundle, account, bid), model, bundle.get('effort')

    for name, row in inventory['accounts'].items():
        owner = row.get('quota_account')
        if owner and owner != name and name in specs and owner in specs:
            offered = {launch_key(bid, b, owner) for bid, b in specs[owner].get('bundles', {}).items()}
            for bid, bundle in specs[name].get('bundles', {}).items():
                if launch_key(bid, bundle, name) not in offered:
                    specs[owner]['bundles'][bid] = {**bundle, 'provider': bundle.get('provider', name)}
            specs[name]['bundles'] = {}
            specs[name]['quota_account'] = owner


def merge_usage(usage, accounts, now, names=None):
    """Invalidate another credential's cached quota; never probe an upstream."""
    inventory = accounts.get('_discovery') or {}
    result = copy.deepcopy(usage)
    sources = quota_sources(accounts)
    relevant = None if names is None else (set(names) | {sources[n] for n in names if n in sources})
    for name, row in (inventory.get('accounts') or {}).items():
        if (relevant is None or name in relevant) and row.get('usage_binding') == 'changed':
            result.setdefault('accounts', {})[name] = {
                'status': 'unknown', 'reason': 'credential_changed', 'windows': []}
    # If a launcher is disabled but another exposes the same subscription, its
    # matching fresh reading still belongs to that subscription's quota owner.
    for name, row in (inventory.get('accounts') or {}).items():
        owner = row.get('quota_account')
        source = obj(obj(result.get('accounts')).get(name))
        target = obj(obj(result.get('accounts')).get(owner))
        owner_row = obj(obj(inventory.get('accounts')).get(owner))
        # Only a reading of the owner's own identity crosses over, and never onto a credential that has since changed.
        if (owner and owner != name and (names is None or owner in names)
                and row.get('usage_binding') == 'matches' and source.get('status') == 'fresh'
                and target.get('status') != 'fresh'
                and row.get('identity') and row.get('identity') == owner_row.get('identity')
                and owner_row.get('usage_binding') != 'changed'):
            result.setdefault('accounts', {})[owner] = copy.deepcopy(source)
    rows = result.setdefault('accounts', {})
    for name, source in quota_sources(accounts).items():
        if names is None or name in names:
            rows[name] = {**copy.deepcopy(rows.get(source) or {
                'status': 'unknown', 'reason': 'account_missing', 'windows': []}), 'quota_source': source}
    return result
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall