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/auto_bundles.py

View on GitHub
"""Runtime-derived ("auto") bundles from detected models.

Pure functions only: nothing here reads or writes ~/.agent-compass, calls a model, or edits
references/accounts.json. Callers pass the merged accounts document, the model-catalog cache
(tray/model_catalog.py format) and the sparse user overrides.

A discovered name resolves, most specific first, to:
  1. calibrated   - the canonical model has a row in accounts['models'] (exact id or alias).
  2. family       - the same-series row `series_target` names (model_resolution's family resolution). The name has no
                    scores of its own: calibration (calibration/five_axis.py) converts them from that row when the model
                    enters the public data, so until then it is out of automatic routing (rule B) and a named dispatch
                    carries the data error.
  3. unmeasured   - no row and no same-series row: the same, with no series to convert from.
The catalog's provider_names table is read first (model_resolution.resolve_in): a name the account's endpoint declares
is that provider's row (calibrated) or no row there (retired, other_weights: out of automatic routing, a named route
still launches); else a name its maker moved to a newer dated snapshot is that snapshot's row (calibrated).
No default row, score or price is supplied here.
"""
import copy
import hashlib
import json
import os
import re
from pathlib import Path

import public_data
import released_names
from model_resolution import DIRECT_SOURCES, PROVIDER_NAME_STATUSES, expand_host_providers, resolve_in, split_model_effort

AUTO_PREFIX = 'auto:'
STALE_LIMIT_SECONDS = 7 * 24 * 3600
EFFORTS = ('minimal', 'low', 'medium', 'high', 'xhigh', 'max')
EFFORT_SUFFIX = re.compile(r'^(?P<base>.+?)-(?P<effort>' + '|'.join(EFFORTS) + r')$')
NON_CHAT = re.compile(r'embed|image|imagen|dall-?e|tts|speech|audio|whisper|transcri|rerank|moderation|veo|video', re.I)
HARNESS_DEFAULT_EFFORT = {'codex': 'high', 'pi': 'high', 'claude': 'high', 'opencode': None,
                          'antigravity-resilient': None, 'grok': 'high'}
HARNESS_MODE = {'codex': 'full-access', 'claude': 'bypassPermissions',
                'opencode': 'build', 'antigravity-resilient': 'full-access'}
# A model catalog entry of an endpoint (tray/model_catalog.py: an OpenAI-compatible base URL) lists ids in its own
# namespace, so the endpoint is the name's serving provider; any other entry is a launcher's list, whose `provider/name`
# ids name the provider it launches (model_resolution.serving_providers).
ENDPOINT_TYPES = ('openai_compatible',)
_PUBLIC_CATALOG_CACHE = None


def _public_catalog():
    global _PUBLIC_CATALOG_CACHE
    ref = Path(__file__).resolve().parents[1] / 'references' / 'accounts.json'
    held = public_data.set_id(ref.parent)
    if _PUBLIC_CATALOG_CACHE is None or _PUBLIC_CATALOG_CACHE[0] != held:
        try:
            doc = public_data.document(ref)
        except (OSError, ValueError):
            doc = {}
        _PUBLIC_CATALOG_CACHE = (held, {
            'models': doc.get('models') if isinstance(doc.get('models'), dict) else {},
            'aliases': doc.get('aliases') if isinstance(doc.get('aliases'), dict) else {},
            'families': doc.get('families'),
            'provider_names': doc.get('provider_names'),
        })
    return _PUBLIC_CATALOG_CACHE[1]


def _model_api_family(model, accounts=None):
    src = accounts if isinstance(accounts, dict) and isinstance(accounts.get('models'), dict) else _public_catalog()
    models = src.get('models') or {}
    canon = resolve_in(model, src)['key'] or str(model or '')
    return str((models.get(canon) or {}).get('api_family') or '').strip().lower()


def split_effort(raw, accounts=None):
    """('claude-opus-5-5', 'high') for 'claude-opus-5-5-high'; (raw, None) without an effort suffix.

    '-max' is also a size name (qwen3.7-max), so with `accounts` it splits only when the base is calibrated.
    """
    name = str(raw or '').strip()
    match = EFFORT_SUFFIX.match(name)
    if not match:
        return name, None
    if match['effort'] == 'max' and accounts is not None:
        known = accounts.get('models') or {}
        if match['base'] not in known and match['base'] not in (accounts.get('aliases') or {}):
            return name, None
    return match['base'], match['effort']


def is_chat_model(raw):
    return not NON_CHAT.search(str(raw or ''))


def series_target(raw_model, accounts, providers=()):
    """The same-series row model_resolution's family resolution gives this name (a name that is itself a row resolves
    exactly and has none), or None."""
    resolved = resolve_in(raw_model, accounts, providers)
    return resolved['key'] if resolved['source'] == 'family' and resolved['key'] else None


def _name_candidates(raw_model, accounts):
    """(base, ids to look up most specific first): raw, effort-stripped, alias-resolved, vendor-tag-stripped."""
    aliases = (accounts.get('aliases') if isinstance(accounts, dict) and isinstance(accounts.get('aliases'), dict) else {})
    acct_for_split = accounts if isinstance(accounts, dict) and 'models' in accounts else {'models': accounts if isinstance(accounts, dict) else {}}
    base, _ = split_effort(str(raw_model).rsplit('/', 1)[-1], acct_for_split)
    name = base
    seen = set()
    while name in aliases and name not in seen:
        seen.add(name)
        name = aliases[name]
    stripped = base
    while True:  # vendor date/tag suffixes (@20251001, -20261023, :free, -latest) are not new models
        nxt = re.sub(r'(?:@\d{8}|-\d{8}|:\w+|\[\w+\]|-(?:latest|preview))$', '', stripped)
        if nxt == stripped:
            break
        stripped = nxt
    return base, (str(raw_model), base, name, stripped, aliases.get(stripped, stripped))


def endpoint_providers(entry, provider, account, accounts=None):
    """The serving providers (model_resolution.serving_providers `endpoints`) of the names a catalog entry lists for an
    account: the entry's provider and the account for an endpoint account, plus—for a Magpie-bound account
    (`endpoint_providers` / `_discovery.accounts[account].magpie_providers`)—its Magpie preset/provider ids mapped
    through `provider_names.host_providers['magpie']`; none for a launcher's list. Non-Magpie accounts never read
    Magpie's preset table. Read by derive and by the tray's model list alike."""
    entry_eps = tuple((entry or {}).get('endpoint_providers') or ())
    disc_eps = tuple((((accounts or {}).get('_discovery') or {}).get('accounts') or {}).get(account, {}).get('magpie_providers') or ())
    magpie_eps = tuple(dict.fromkeys(p for p in (*entry_eps, *disc_eps) if p))
    entry_type = (entry or {}).get('type')
    if entry_type not in ENDPOINT_TYPES and not (magpie_eps and entry_type in (None, 'configured')):
        return ()
    base = tuple(dict.fromkeys(p for p in (provider, account) if p))
    if not magpie_eps:
        return base
    src = accounts if isinstance(accounts, dict) and isinstance(accounts.get('provider_names'), dict) else _public_catalog()
    preset_lower = {str(p).lower() for p in magpie_eps}
    own = tuple(p for p in base if str(p).lower() not in preset_lower)
    return tuple(dict.fromkeys((*own, *expand_host_providers(magpie_eps, 'magpie', src))))


def endpoint_presets(entry, provider, account, accounts=None):
    """The unexpanded endpoint/preset ids `endpoint_providers` held before `expand_host_providers` replaced Magpie's
    preset ids: `(*base, *magpie_eps)` for an endpoint account, `()` for a launcher's list."""
    entry_eps = tuple((entry or {}).get('endpoint_providers') or ())
    disc_eps = tuple((((accounts or {}).get('_discovery') or {}).get('accounts') or {}).get(account, {}).get('magpie_providers') or ())
    magpie_eps = tuple(dict.fromkeys(p for p in (*entry_eps, *disc_eps) if p))
    entry_type = (entry or {}).get('type')
    if entry_type not in ENDPOINT_TYPES and not (magpie_eps and entry_type in (None, 'configured')):
        return ()
    base = tuple(dict.fromkeys(p for p in (provider, account) if p))
    return tuple(dict.fromkeys((*base, *magpie_eps)))


def superseded_by(raw_model, accounts, providers=()):
    """The newer model id public data names for this model, or None (latest, or unknown to the data).

    The only source of a discovered model's default checkbox: `accounts['superseded']` maps an old model id
    to {'by': newer id, 'basis': ...}. Efforts and harnesses of one model share its entry. A name its serving provider
    declares is that row alone (or no row: retired), never the spellings of the row the name is elsewhere.
    """
    table = accounts.get('superseded') if isinstance(accounts.get('superseded'), dict) else {}
    resolved = resolve_in(raw_model, accounts, providers)
    if resolved['source'] in ('provider', 'default', 'conflict', *PROVIDER_NAME_STATUSES):
        entry = table.get(resolved['key']) if resolved['key'] else None
        return entry['by'] if isinstance(entry, dict) and entry.get('by') else None
    names = [*_name_candidates(raw_model, accounts)[1], resolved['bare']]
    if resolved['source'] in DIRECT_SOURCES:
        names.append(resolved['key'])
    for candidate in names:
        entry = table.get(candidate)
        if isinstance(entry, dict) and entry.get('by'):
            return entry['by']
    return None


def off_by_default(account, model):
    """The one wording of a row off by default in the shipped data (`disabled_by_default`: public data names a newer
    model, `superseded_by`). Not the user's checkbox: naming the model reaches it."""
    return (f'{account}/{model} is off by default in the shipped data (a newer model supersedes it), so automatic routing '
            'does not choose it; naming the model (--model) uses it')


def default_profile(raw_model, accounts, providers=()):
    """How a model name resolves, with its source: {'model', 'source', 'target', 'basis'}. Never mutates accounts.

    `providers`: the endpoints serving the name (model_resolution.serving_providers). A name a serving provider declares
    with no row (retired, other_weights) has none there: its model is the name qualified by that provider
    (`<provider>/<name>`), so every later resolution of the bundle's model reads the same declaration and never the row
    the name is elsewhere."""
    base = _name_candidates(raw_model, accounts)[0]
    resolved = resolve_in(raw_model, accounts, providers)
    if resolved['source'] == 'provider':
        # A row whose own id reads as another row with no provider known (a name its maker moved: the undated row of a
        # moved name) is kept qualified by the declaring provider, so a later resolution of the bundle's model reads
        # the same declaration.
        model = (resolved['key'] if resolve_in(resolved['key'], accounts)['key'] == resolved['key']
                 else f"{resolved['provider']}/{split_model_effort(raw_model)[0].rsplit('/', 1)[-1]}")
        return {'model': model, 'source': 'calibrated', 'target': resolved['key'],
                'basis': f"Calibrated row in accounts.models: {resolved['provider']} serves this name as {resolved['key']} "
                         '(provider_names).'}
    if resolved['source'] == 'default':
        # A row whose own id reads as another row (the undated row a repository id is declared to be) keeps the
        # advertised spelling, so a later resolution of the bundle's model reads the same declaration.
        model = (resolved['key'] if resolve_in(resolved['key'], accounts)['key'] == resolved['key']
                 else split_model_effort(raw_model)[0])
        return {'model': model, 'source': 'calibrated', 'target': resolved['key'],
                'basis': f"Calibrated row in accounts.models: the maker now serves this name as {resolved['key']} "
                         '(provider_names defaults).'}
    if resolved['source'] in DIRECT_SOURCES:
        # An alias of a row whose own id reads as another row (a name its maker moved) keeps the alias's spelling.
        model = (resolved['key'] if resolve_in(resolved['key'], accounts)['key'] == resolved['key']
                 else split_model_effort(raw_model)[0])
        return {'model': model, 'source': 'calibrated', 'target': resolved['key'],
                'basis': 'Calibrated row in accounts.models.'}
    if resolved['source'] in PROVIDER_NAME_STATUSES:
        why = ('no longer serves this name (retired)' if resolved['source'] == 'retired'
               else 'serves this name as weights the public data has no row for (other_weights)')
        return {'model': f"{resolved['provider']}/{resolved['bare']}", 'source': resolved['source'], 'target': None,
                'basis': f"{resolved['provider']} {why}, by provider_names: no row, out of automatic routing; a route the "
                         'user names still launches.'}
    if resolved['source'] == 'conflict':
        return {'model': base, 'source': 'unmeasured', 'target': None,
                'basis': 'Its serving providers declare different rows (provider_names): no row, out of automatic routing.'}
    target = series_target(raw_model, accounts, providers)
    if target:
        return {'model': base, 'source': 'family', 'target': target,
                'basis': f'Same series as {target}; no scores of its own until calibration converts them from it.'}
    return {'model': base, 'source': 'unmeasured', 'target': None,
            'basis': 'No row and no same-series row: no scores (out of automatic routing).'}


def harness_compatibility(harness, model, account_spec, accounts=None, listed=False):
    """('ok'|'unverified'|'excluded', reason). Read-only rules; no endpoint is called here.

    `listed`: the user named this model on the account and the account's provider lists it. The provider's list is then
    the authority over what the name suggests: neither the non-chat name pattern nor a family the public data does not
    know excludes it (automatic routing keeps both). A family the data does know still decides.

    A metered account (including a metered USD balance) is driven by Codex CLI over the Responses API.
    That bridge is not verified for non-OpenAI models, so those models on codex/pi are 'unverified'
    (still derivable; metered bundles stay a routing last resort). Claude Code needs an Anthropic
    Messages endpoint; non-Claude models there are excluded unless the account declares
    `anthropic_compatible: true`.
    """
    spec = account_spec or {}
    if not is_chat_model(model) and not listed:
        return 'excluded', 'non-chat model (embedding/image/audio)'
    api_family = _model_api_family(model, accounts)
    proxy = spec.get('billing') == 'metered' or spec.get('backend_kind') == 'metered_usd'
    if harness in ('codex', 'pi'):
        if api_family == 'codex' or not proxy:
            return 'ok', ''
        if spec.get('responses_api_verified') is True:
            return 'ok', 'proxy declares responses_api_verified'
        return 'unverified', 'non-OpenAI model through proxy Responses API bridge (not verified)'
    if harness == 'claude':
        if api_family == 'claude' or spec.get('anthropic_compatible') is True:
            return 'ok', ''
        if listed and not api_family:
            return 'ok', 'listed by the provider; public data has no API family for it'
        return 'excluded', 'Claude Code requires an Anthropic Messages endpoint'
    return 'ok', ''


def _account_harnesses(account, spec):
    """(harness, catalog provider) pairs an account already launches through, from its manual bundles."""
    from account_fleet import bundle_harness  # local import: account_fleet imports this module's peers
    pairs = {}
    for bid, bundle in (spec.get('bundles') or {}).items():
        if isinstance(bundle, dict):
            pairs.setdefault(bundle_harness(bundle, account, bid), bundle.get('provider') or account)
    if not pairs:
        pairs[PER_MODEL] = account  # proxy / discovered account: harness chosen per model
    return pairs


def launch_providers(account, spec):
    """The catalog providers `account` launches through, sorted: its manual bundles' providers and the account itself
    (`derive` reads a provider's model list for an account under these names only)."""
    return sorted({*_account_harnesses(account, spec).values(), account})


PER_MODEL = '*'


def proxy_harness(family, model, accounts):
    """Harness for a model on an account without manual bundles."""
    family = str(family or 'codex')
    if family in ('claude', 'codex'):
        models = accounts.get('models') or {}
        canon = resolve_in(model, accounts)['key'] or str(model or '')
        api_family = str((models.get(canon) or {}).get('api_family') or '').strip().lower()
        return 'claude' if api_family == 'claude' else 'codex'
    return family


def _metered_draws(spec):
    """The dollar balance this account draws when a budget exists. No period is invented."""
    windows = spec.get('windows') if isinstance(spec.get('windows'), dict) else {}
    return ['balance'] if 'balance' in windows else []


def _draws(spec, model, accounts):
    import window_scope
    windows = spec.get('windows') if isinstance(spec.get('windows'), dict) else {}
    canonical = resolve_in(model, accounts)['key'] or model
    return [wid for wid, w in windows.items() if window_scope.binds_any((canonical, model), w)]


def _availability(entry, raw, now, seen_at):
    """detected | stale (<7d, still selectable) | expired (>=7d, not selectable)."""
    listed = bool(entry.get('ok')) and any((m.get('id') if isinstance(m, dict) else m) == raw for m in entry.get('models') or [])
    if listed:
        return 'detected', now
    last = seen_at or entry.get('checked_at')
    if last is None or now - last >= STALE_LIMIT_SECONDS:
        return 'expired', last
    return 'stale', last


def auto_bundle_id(account, harness, model, effort=None):
    return f'{AUTO_PREFIX}{account}:{harness}:{model}' + (f'@{effort}' if effort else '')


def name_tag(raw):
    """The suffix that tells apart a second advertised name of one key on an account (`#` + sha256(name)[:8])."""
    return '#' + hashlib.sha256(raw.encode()).hexdigest()[:8]


def split_id(bid):
    """(account, harness, model name, effort or None, tag or None) of an auto bundle id
    (auto:<account>:<harness>:<model name>[@<effort>][#<tag>]), else None."""
    if not isinstance(bid, str) or not bid.startswith(AUTO_PREFIX):
        return None
    parts = bid[len(AUTO_PREFIX):].split(':', 2)
    if len(parts) != 3:
        return None
    account, harness, rest = parts
    rest, _, tag = rest.partition('#')
    model, _, effort = rest.partition('@')
    return account, harness, model, effort or None, tag or None


def harness_by_model(bundles):
    """True for an account whose auto bundles take their harness from the model (`_account_harnesses`: no bundle of
    its own), so a stored choice's harness says nothing of its own."""
    return not any(isinstance(b, dict) and not b.get('auto') for b in (bundles or {}).values())


def stored_choices(document, accounts):
    """{account: [choice]}: the user's checkboxes on auto bundles in an accounts-override document, keyed by the
    account their id names (the tray may store one under the account that pays for it). Each holds the model name of
    the id as written and the key that name resolves to now (`default_profile`): a stored choice applies to the
    bundle its model name resolves to now, so an alias added by a release or a data set published between releases
    never strands it (owner review, round 8)."""
    out = {}
    for spec in ((document or {}).get('accounts') or {}).values():
        for sid, pref in ((spec.get('bundles') if isinstance(spec, dict) else None) or {}).items():
            parts = split_id(sid)
            if parts is None or not isinstance(pref, dict) or not isinstance(pref.get('disabled'), bool):
                continue
            account, harness, name, effort, tag = parts
            out.setdefault(account, []).append({'id': sid, 'harness': harness, 'name': name, 'effort': effort,
                                                'tag': tag, 'key': default_profile(name, accounts)['model'],
                                                'disabled': pref['disabled']})
    return out


def replayed_owners(bundles):
    """{id v0.7.0 gave an auto bundle of one account (`_v0_7_0_id`, `derive`): the model that bundle is now}."""
    return {b['_v0_7_0_id']: b.get('model') for b in (bundles or {}).values()
            if isinstance(b, dict) and b.get('auto') and b.get('_v0_7_0_id')}


def choice_for(choices, bundle, accounts, by_model, owners):
    """(disabled or None, [stored ids], whether they disagree) for an auto bundle: the stored choice whose id is the one
    v0.7.0 gave this bundle (`_v0_7_0_id`, `derive`), and every stored choice of its account at its effort (and its
    harness, unless the account takes the harness from the model) whose model name resolves now to the bundle's key or
    is the bundle's advertised name, a tagged one only for the name its tag hashes. An id v0.7.0 gave another advertised
    name of the account (`owners`, `replayed_owners`) is that name's own: it is read only by the bundles of the model
    that name is now (owner review, round 10). Several that disagree leave the bundle disabled: the user took the model
    out of automatic routing under one of its names (a named route still launches)."""
    raw = bundle.get('launch_model') or bundle.get('model') or ''
    spelled, tag = _name_candidates(raw, accounts)[0], name_tag(raw)[1:]
    hits = [c for c in choices or () if c['id'] == bundle.get('_v0_7_0_id') or (
            owners.get(c['id'], bundle.get('model')) == bundle.get('model')
            and c['effort'] == bundle.get('effort') and (by_model or c['harness'] == bundle.get('harness'))
            and c['tag'] in (None, tag) and (c['key'] == bundle.get('model') or c['name'] == spelled))]
    if not hits:
        return None, [], False
    values = {c['disabled'] for c in hits}
    return True in values, sorted(c['id'] for c in hits), len(values) > 1


def mark_choice(bundle, ids, disagree):
    """The stored ids a bundle read its checkbox from (`_choice_ids`, the ids the tray replaces when the user sets it
    again) and, when they disagree, `_choice_conflict` (listed once by `agentcompass doctor`)."""
    if ids:
        bundle['_choice_ids'] = ids
    if disagree:
        bundle['_choice_conflict'] = ids


def derive(accounts, catalog, now, overrides=None, seen=None, account_families=None, named=()):
    """Return {'bundles': {account: {bid: bundle}}, 'excluded': [...], 'seen': {...}}.

    overrides: sparse preferences document ({'accounts': {acc: {'bundles': {bid: {'disabled': bool}}}}}),
    the same shape tray router_data.toggle_harness_model writes.
    seen: {bundle_id: last_detected_epoch}; the returned 'seen' should be persisted by the caller.
    account_families: {account: discovered launcher family}, for accounts whose harness is chosen per model.
    named: {(account, advertised id)} the user named and the provider lists (`harness_compatibility(listed=True)`).
    Manual bundles always win for the same (account, harness, canonical base model).
    """
    providers = (catalog or {}).get('providers') or {}
    choices = stored_choices(overrides, accounts)
    seen = dict(seen or {})
    out = {'bundles': {}, 'excluded': [], 'seen': seen}

    def base_key(model, served):
        # Only exact ids/aliases (and a row the serving provider declares) collapse; a family guess keeps its own name.
        return default_profile(model, accounts, served)['model']

    released_accounts = released_names.as_v0_7_0(accounts)

    for account, spec in (accounts.get('accounts') or {}).items():
        if not isinstance(spec, dict):
            continue
        # The id v0.7.0 gave each bundle, replayed in the same catalog order (owner review, round 9): the row v0.7.0
        # resolved the advertised name to (`released_names.as_v0_7_0`), and the tag of that advertised spelling when an
        # earlier name of the account already held the id. A choice the user stored under it is that name's own; the
        # advertised spelling is known only here, where discovery lists it. Every name of the account is replayed
        # before any bundle takes its id or reads its choice: a later name may hold the id an earlier one would take.
        released, pending = {}, []
        manual = {(h, base_key(b.get('model') or '', ()), b.get('effort'))     # a manual bundle is a launcher's row
                  for bid, b in (spec.get('bundles') or {}).items()
                  if isinstance(b, dict) for h in [_harness_of(b, account, bid)]}
        manual_models = {(h, m) for h, m, _ in manual}
        metered = spec.get('billing') == 'metered'
        for pair_harness, provider in _account_harnesses(account, spec).items():
            entry = providers.get(provider) or providers.get(account)
            if not isinstance(entry, dict) or entry.get('type') == 'static':
                continue
            for item in entry.get('models') or []:
                raw = item.get('id') if isinstance(item, dict) else item
                if not isinstance(raw, str) or not raw.strip():
                    continue
                if '[' in raw:  # context-window variants (claude-opus-4-6[1m]) are the same model
                    continue
                base, id_effort = split_effort(raw, accounts)
                served = endpoint_providers(entry, provider, account, accounts)
                presets = endpoint_presets(entry, provider, account, accounts)
                profile = default_profile(raw, accounts, served)
                harness = pair_harness if pair_harness != PER_MODEL else \
                    proxy_harness((account_families or {}).get(account) or spec.get('family'), profile['model'], accounts)
                listed = (account, raw) in named
                status, reason = harness_compatibility(harness, profile['model'], spec, accounts, listed=listed)
                if status != 'excluded' and not is_chat_model(raw) and not listed:
                    status, reason = 'excluded', 'non-chat model (embedding/image/audio)'
                key = base_key(raw, served)
                if status == 'excluded':
                    out['excluded'].append({'account': account, 'harness': harness, 'model': raw, 'reason': reason})
                    continue
                effort = id_effort or HARNESS_DEFAULT_EFFORT.get(harness)
                if (harness, key, effort) in manual or (id_effort is None and (harness, key) in manual_models):
                    continue
                released_id = auto_bundle_id(account, harness, default_profile(raw, released_accounts)['model'], effort)
                if released.get(released_id, raw) != raw:
                    released_id += name_tag(raw)
                released[released_id] = raw
                model_name = profile['model'] if profile['source'] != 'calibrated' else key
                pending.append((raw, harness, key, effort, released_id, model_name, provider, entry, profile, status,
                                reason, pair_harness, served, presets))
        owners = {released_id: model_name for _, _, _, _, released_id, model_name, *_ in pending}
        for raw, harness, key, effort, released_id, model_name, provider, entry, profile, status, reason, pair_harness, \
                served, presets in pending:
            bid = auto_bundle_id(account, harness, key, effort)
            taken = out['bundles'].get(account, {}).get(bid)
            # The id v0.7.0 gave another model's name stays that name's own: this one takes its tagged id.
            if (taken and taken['launch_model'] != raw) or owners.get(bid, model_name) != model_name:
                bid += name_tag(raw)
            availability, last = _availability(entry, raw, now, seen.get(bid))
            if availability == 'detected':
                seen[bid] = now
            chosen, chosen_ids, disagree = choice_for(
                choices.get(account), {'launch_model': raw, 'model': model_name, 'effort': effort, 'harness': harness,
                                       '_v0_7_0_id': released_id}, accounts, pair_harness == PER_MODEL, owners)
            # The checkbox default is public data alone: checked unless superseded there. The user's
            # model-management checkbox (`choice_for`) overrides it. Metered stays a last resort in routing.
            default_disabled = (superseded_by(raw, accounts, served) is not None
                                or superseded_by(key, accounts, served) is not None)
            # Unchecked only by default, not by the user: naming this model still reaches it.
            by_default = default_disabled and chosen is None and availability != 'expired'
            bundle = {
                'provider': provider, 'harness': harness, 'model': model_name, 'launch_model': raw,
                **({'effort': effort} if effort else {}),
                **({'modeId': HARNESS_MODE[harness]} if harness in HARNESS_MODE else {}),
                'draws': _metered_draws(spec) if metered else _draws(spec, key, accounts),
                'disabled': bool(default_disabled if chosen is None else chosen) or availability == 'expired',
                **({'disabled_by_default': True} if by_default else {}),
                'auto': True, 'billing': 'metered' if metered else 'subscription',
                'score_source': profile['source'], 'score_basis': profile['basis'],
                'availability': availability, 'last_detected_at': last,
                'compatibility': status, **({'compatibility_reason': reason} if reason else {}),
                '_v0_7_0_id': released_id,
                **({'_served': list(served)} if served else {}),   # the serving providers read here (stored_model)
                **({'_presets': list(presets)} if presets else {}),  # unexpanded preset/endpoint ids (_bundle_has_prefix)
            }
            if availability == 'expired':
                bundle['discovery_unavailable'] = True
            mark_choice(bundle, chosen_ids, disagree)
            out['bundles'].setdefault(account, {})[bid] = bundle
    return out


def _harness_of(bundle, account, bid):
    from account_fleet import bundle_harness
    return bundle_harness(bundle, account, bid)


def merge_into(accounts, derived):
    """Copy of accounts with the auto bundles added. Manual bundles are never replaced."""
    merged = copy.deepcopy(accounts)
    for account, rows in derived['bundles'].items():
        target = merged['accounts'].setdefault(account, {}).setdefault('bundles', {})
        for bid, bundle in rows.items():
            target.setdefault(bid, bundle)
    return merged


# --- `seen` persistence (last detection time per auto bundle) -------------------------------------
def read_seen(path):
    try:
        value = json.loads(Path(path).read_text(encoding='utf-8-sig'))
    except (OSError, ValueError):
        return {}
    rows = value.get('seen') if isinstance(value, dict) else None
    return {k: float(v) for k, v in (rows or {}).items()
            if isinstance(k, str) and isinstance(v, (int, float)) and not isinstance(v, bool)}


def write_seen(path, seen, now=None):
    """Atomic write; prunes entries older than 4x the stale limit so the file cannot grow forever."""
    path = Path(path)
    cutoff = (now if now is not None else max(seen.values(), default=0)) - 4 * STALE_LIMIT_SECONDS
    rows = {k: v for k, v in seen.items() if v >= cutoff}
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(f'{path.name}.{os.getpid()}.tmp')
    tmp.write_text(json.dumps({'seen': rows}, ensure_ascii=False, sort_keys=True), encoding='utf-8')
    tmp.replace(path)
    return rows
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