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

View on GitHub
"""One state per account, read by dispatch and by every account list.

`ready`          the usage reading is good.
`plan_inactive`  the plan is free, expired, cancelled or unpaid, or a launch reported that: excluded at once.
`usage_failing`  the reading failed (any error, no reading): listed at once, dispatch carries a warning, and the
                 account is excluded once its last good reading is older than `exclude_after_hours` (default 6).
`auth_failed`    the provider refused the credentials (401/403): excluded at once.

A good reading returns the account to `ready`; nobody has to clear anything. Only provider and collector facts decide
a state, never task text. A launch's subscription error is latched in <state dir>/plan-inactive.json until a good
reading newer than the latch; no remote error text is stored.
"""
from __future__ import annotations

from datetime import datetime, timedelta, timezone
import json
import os
from pathlib import Path
import re

READY, PLAN_INACTIVE, USAGE_FAILING, AUTH_FAILED = 'ready', 'plan_inactive', 'usage_failing', 'auth_failed'
# Antigravity only: two Google accounts take turns in agy's single keyring slot (antigravity_plan), so no reading can be
# attributed to one account. Not dispatchable, like every state but ready and usage_failing in grace.
AGY_ACCOUNT_FLAPPING = 'agy_account_flapping'
# One dollar account still has old meter fields. Listed, not dispatchable, and not a fleet-wide failure.
LEGACY_METER = 'legacy_meter'
AGY_FLAPPING_FIX = ("close every agy session still signed in to the other Google account (each refreshes its own token "
                    "into the shared keyring slot), then sign in to agy once with the account you want")
DEFAULT_EXCLUDE_AFTER_HOURS = 6.0
LATCH_RETRY_HOURS = 6.0
EXCLUDE_AFTER_ENV = 'AGENTCOMPASS_USAGE_FAILING_EXCLUDE_HOURS'
# Twice the longest polling cadence the router accepts (usage_cache.POLL_MAX_SECONDS): a reading this old without an
# error means nothing is reading the account any more.
READING_TOO_OLD_SECONDS = 2 * 3600
# States an account list must keep showing even when the account cannot take work.
LISTED_STATES = (READY, PLAN_INACTIVE, USAGE_FAILING, AUTH_FAILED, AGY_ACCOUNT_FLAPPING, LEGACY_METER)
# Plan names that mean the subscription gives no quota, whichever source reported them.
INACTIVE_PLANS = frozenset(('free', 'free tier', 'expired', 'cancelled', 'canceled', 'inactive', 'lapsed', 'none',
                            'past due', 'payment failed', 'unpaid'))
# Words that name the vendor or product in a plan label, not the plan: "Antigravity Free Tier" is `free tier`.
PLAN_VENDOR_WORDS = frozenset(('antigravity', 'chatgpt', 'claude', 'google', 'ai', 'openai', 'plan', 'grok', 'xai'))
# Families whose account is a paid subscription: a free plan there is a lapse. OpenCode's free models are its product.
SUBSCRIPTION_FAMILIES = ('claude', 'codex', 'antigravity', 'pi', 'omp')
LATCH_FILE = 'plan-inactive.json'
# What the Paseo bridge reports (lastErrorClass, failure_class) or a provider's own error code. Structured fields decide
# when present; the text pattern is only for a report with none. A model-level refusal ("your plan does not include this
# model") never matches: the account still runs its other models.
INACTIVE_ERROR_CODES = frozenset(('subscription_inactive', 'subscription_expired', 'subscription_canceled',
                                  'subscription_cancelled', 'plan_expired', 'plan_inactive', 'payment_required',
                                  'payment_failed'))
_LAUNCH_ERROR = re.compile(
    r'subscription(?:_| (?:has |is |was )?)(?:expired|cancel+ed|inactive|lapsed)|'
    r'plan (?:has |is )?(?:expired|cancel+ed|inactive)|'
    r'payment[_ ](?:required|failed)|past[_ ]due|'
    r'订阅(?:已)?(?:过期|到期|失效|取消)', re.I)


ONLINE_PLAN_SOURCES = ('usage_api', 'usage_api_shared', 'profile_api', 'account-tier', 'settings_api', 'user_api')
_POOL_SUFFIX = re.compile(r'\s*×\s*\d+\s*$')


def _time(value):
    try:
        moment = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
    except (TypeError, ValueError):
        return None
    return moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)


def strip_pool_count(label):
    return _POOL_SUFFIX.sub('', str(label or ''))


def plan_words(label):
    return ' '.join(re.findall(r'[a-z0-9]+', str(label or '').replace('×', 'x').lower()))


def plan_without_vendor(label):
    return ' '.join(word for word in plan_words(label).split() if word not in PLAN_VENDOR_WORDS)


def plan_reported(label):
    """Whether a plan label names a tier: an empty label, 'unknown' or a bare 'subscription' reports none."""
    return plan_without_vendor(str(label or '').strip()) not in ('', 'unknown', 'subscription')


def plan_is_inactive(family, plan):
    if family not in SUBSCRIPTION_FAMILIES:
        return False
    if plan_without_vendor(plan) in INACTIVE_PLANS:
        return True
    stripped = strip_pool_count(plan)
    return stripped != str(plan or '') and plan_without_vendor(stripped) in INACTIVE_PLANS


def reading(row, now):
    """(problem, last good reading's time) of a usage-cache row; problem None means the reading is good."""
    row = row if isinstance(row, dict) else {}
    windows = row.get('windows') if isinstance(row.get('windows'), list) else []
    numeric = any(isinstance(w, dict) and isinstance(w.get('used_pct'), (int, float)) for w in windows)
    fetched = _time(row.get('fetched_at'))
    last = fetched.isoformat() if fetched and numeric else None
    if not row:
        return 'no_reading', None
    if row.get('error'):
        return f"read_failed: {row['error']}", last
    if row.get('available') is False:
        return 'read_failed: provider unavailable', last
    if not numeric:
        return 'no_reading: usage came back empty', None
    if fetched is None:
        return 'no_reading: reading has no time', None
    if (now - fetched).total_seconds() > READING_TOO_OLD_SECONDS:
        return 'reading_too_old', last
    return None, last


def exclude_after_hours(environ=None, override_doc=None):
    """Hours a failing reading may stay dispatchable: the environment, then accounts-override `scoring`, then 6."""
    candidates = ((os.environ if environ is None else environ).get(EXCLUDE_AFTER_ENV),
                  ((override_doc or {}).get('scoring') or {}).get('usage_failing_exclude_hours'))
    for value in candidates:
        try:
            hours = float(value)
        except (TypeError, ValueError):
            continue
        if hours >= 0:
            return hours
    return DEFAULT_EXCLUDE_AFTER_HOURS


def failing(row, problem, last_success, previous, now, hours, cached_at=None):
    """Set `usage_failing` on an inventory row. With no good reading on file the clock starts at the first failure seen."""
    since = previous.get('failing_since') if isinstance(previous, dict) and previous.get('status') == USAGE_FAILING else None
    cached_time = _time(cached_at)
    since = since if _time(since) else (cached_time.isoformat() if cached_time else now.isoformat())
    anchor = _time(last_success) or _time(since)
    row.update(status=USAGE_FAILING, reason=problem, failing_since=since, exclude_after_hours=hours,
               usage_excluded=(now - anchor).total_seconds() >= hours * 3600)


def dispatchable(row):
    """True while the account may take work: `ready`, or `usage_failing` still inside its grace period."""
    if not isinstance(row, dict):
        return False
    return row.get('status') == READY or (row.get('status') == USAGE_FAILING and not row.get('usage_excluded'))


def unavailable_text(row):
    """The exclusion reason of an account this module excluded; None for every other state."""
    status = row.get('status')
    if status == PLAN_INACTIVE:
        return f"plan inactive ({row.get('reason')}); renew the subscription or sign in to a paid account"
    if status == USAGE_FAILING and row.get('usage_excluded'):
        return (f"usage reading failing ({row.get('reason')}), last good reading "
                f"{row.get('last_success_at') or 'never'}, over the {row.get('exclude_after_hours'):g}h limit; "
                "run `agentcompass usage` or fix the account")
    if status == AUTH_FAILED:
        return f"credentials rejected ({row.get('reason')}); sign in again in the account's own CLI"
    if status == AGY_ACCOUNT_FLAPPING:
        return f"keyring account flapping ({row.get('reason')}); {AGY_FLAPPING_FIX}"
    if status == LEGACY_METER:
        return str(row.get('reason') or '旧的额度字段残留。运行 agentcompass setup 清掉旧字段。')
    return None


def warning(name, row):
    """The lines `plan`/`roll` show for one account; empty when nothing needs saying."""
    status = row.get('status')
    lines = []
    if status == USAGE_FAILING:
        state = 'excluded from dispatch' if row.get('usage_excluded') else (
            f"still dispatchable, excluded once the last good reading is {row.get('exclude_after_hours'):g}h old")
        lines.append(f"{name}: usage_failing ({row.get('reason')}), last good reading "
                     f"{row.get('last_success_at') or 'never'}; {state}")
    elif status == PLAN_INACTIVE:
        lines.append(f"{name}: plan_inactive ({row.get('reason')}); excluded from dispatch")
    elif status == AUTH_FAILED:
        lines.append(f"{name}: auth_failed ({row.get('reason')}); excluded from dispatch")
    elif status == AGY_ACCOUNT_FLAPPING:
        lines.append(f"{name}: agy_account_flapping ({row.get('reason')}); excluded from dispatch until one account "
                     f"stays signed in. Fix: {AGY_FLAPPING_FIX}")
    elif status == LEGACY_METER:
        lines.append(f"{name}: {row.get('reason') or LEGACY_METER}")
    if row.get('data_error'):
        lines.append(f"{name}: data error: {row['data_error']}")
    return lines


def _free_pool_warning(name, spec):
    if not isinstance(spec, dict) or not (spec.get('capacity_unknown') and spec.get('five_axis_free_pool')):
        return None
    local = spec.get('local_spend_usd')
    if isinstance(local, dict) and local.get('used_usd') is not None:
        spend_note = f"; local lower-bound spend U >= ${local['used_usd']:.2f} ({local['tokens']:,} tokens from {local['source']})"
    elif isinstance(local, (int, float)) and not isinstance(local, bool) and local > 0:
        spend_note = f" (local opencode.db lower-bound spend U ~${float(local):.2f})"
    else:
        spend_note = ''
    gap = spec.get('local_spend_gap')
    if gap:
        shown = ', '.join(str(m) for m in gap[:5]) + (f' and {len(gap) - 5} more' if len(gap) > 5 else '')
        spend_note += f"; no public list price for {shown}, so their local spend is not counted"
    return f"{name}: capacity_unknown — quota unknown, spend unpriced{spend_note}; out of automatic routing (use --model to run)"


def _mode_b_plan_warning(name, spec):
    if not isinstance(spec, dict) or not spec.get('capacity_unknown') or spec.get('five_axis_free_pool'):
        return None
    reason = spec.get('plan_unknown_reason') or (spec.get('plan_unknown') if not spec.get('plan_priced_as') else None)
    if not reason:
        return None
    return f"{name}: capacity_unknown — plan unknown ({reason}); out of automatic routing (use --model to run)"


def warnings(inventory, specs=None, allowed=None):
    """Every account's state and plan warning, for `plan`/`roll`. `allowed(name)` skips accounts this host does not use."""
    found = []
    rows = (inventory or {}).get('accounts') or {}
    for name, row in rows.items():
        if not isinstance(row, dict) or (allowed is not None and not allowed(name)):
            continue
        found.extend(warning(name, row))
        spec = (specs or {}).get(name) or {}
        if spec.get('plan_unknown') and spec.get('plan_priced_as'):
            found.append(f"{name}: plan {spec['plan_unknown']!r} is not a known plan; priced at the conservative "
                         f"{spec.get('plan_priced_as')} capacity")
        else:
            plan_warn = _mode_b_plan_warning(name, spec)
            if plan_warn:
                found.append(plan_warn)
        free_warn = _free_pool_warning(name, spec)
        if free_warn:
            found.append(free_warn)
    for name, spec in (specs or {}).items():
        if name in rows or not isinstance(spec, dict) or (allowed is not None and not allowed(name)):
            continue
        plan_warn = _mode_b_plan_warning(name, spec)
        if plan_warn:
            found.append(plan_warn)
        free_warn = _free_pool_warning(name, spec)
        if free_warn:
            found.append(free_warn)
    return found


def latch_path(state_dir=None):
    root = state_dir or os.environ.get('ROUTER_STATE_DIR') or Path.home() / '.agent-compass'
    return Path(root) / LATCH_FILE


def _read_latches(path):
    try:
        document = json.loads(Path(path).read_text(encoding='utf-8'))
    except (OSError, ValueError):
        return {'accounts': {}}
    return document if isinstance(document, dict) and isinstance(document.get('accounts'), dict) else {'accounts': {}}


def error_means_inactive(error=None, code=None, status=None):
    if code or status:
        return status == 402 or str(code or '').strip().lower() in INACTIVE_ERROR_CODES
    return isinstance(error, str) and bool(_LAUNCH_ERROR.search(error))


def usage_refused_plan(row):
    """The usage API's own status or error code says the subscription has lapsed. Its text is not consulted."""
    return error_means_inactive(None, row.get('error_code'), row.get('error_status'))


def usage_refused_credentials(row, collector_words=()):
    """A 401/403 on the usage API. `collector_words` read a cached row written before the status was recorded."""
    status = row.get('error_status')
    return status in (401, 403) if status else row.get('error') in collector_words


def _latch_context(account, state_dir=None):
    root = Path(state_dir or os.environ.get('ROUTER_STATE_DIR') or Path.home() / '.agent-compass')
    found_key, found_plan = None, None
    for candidate, section in (
        (os.environ.get('ROUTER_USAGE_CACHE'), 'providers'),
        (root / 'usage-cache.json', 'providers'),
        (root / 'provider-inventory.json', 'accounts'),
    ):
        if not candidate:
            continue
        try:
            doc = json.loads(Path(candidate).read_text(encoding='utf-8'))
            row = (doc.get(section) or {}).get(account) or {}
            key = row.get('credential_key')
            if not found_key and isinstance(key, str) and key:
                found_key = key
            if not found_plan:
                if section == 'accounts' and row.get('plan_source') in ONLINE_PLAN_SOURCES and isinstance(row.get('plan'), str):
                    found_plan = row['plan']
                elif section == 'providers' and row.get('backend_kind') != 'gateway' and isinstance(row.get('plan_label'), str) and row['plan_label'].strip():
                    found_plan = row['plan_label'].strip()
        except (OSError, ValueError, AttributeError):
            continue
    if not found_plan and account == 'antigravity':
        try:
            tier_doc = json.loads((root / 'antigravity-plan.json').read_text(encoding='utf-8'))
            for key in ('tier_id', 'plan'):
                if isinstance(tier_doc.get(key), str) and tier_doc[key].strip():
                    found_plan = tier_doc[key].strip()
                    break
        except (OSError, ValueError, AttributeError):
            pass
    return found_key, found_plan


def record_launch_error(account, error=None, *, code=None, status=None, at=None, source=None, state_dir=None,
                        credential_key=None, online_plan=None):
    """Latch `plan_inactive` when a launch reports the subscription has lapsed. Returns True when it did."""
    if not error_means_inactive(error, code, status):
        return False
    import override_store
    path = latch_path(state_dir)
    at = at or datetime.now(timezone.utc).isoformat()
    ctx_key, ctx_plan = _latch_context(account, state_dir)
    key = credential_key or ctx_key
    plan = online_plan if online_plan is not None else ctx_plan
    with override_store.locked(path):
        document = _read_latches(path)
        held = _time((document['accounts'].get(account) or {}).get('observed_at'))
        if held and _time(at) and held >= _time(at):
            return False
        entry = {'observed_at': at, 'source': source}
        if key:
            entry['credential_key'] = key
        if isinstance(plan, str) and plan:
            entry['online_plan'] = plan
        document['accounts'][account] = entry
        override_store.write(path, document)
    return True


def seal_latch_credential(account, credential_key, *, online_plan=None, state_dir=None, expected_observed_at=None):
    if not isinstance(account, str) or not account or not isinstance(credential_key, str) or not credential_key:
        return False
    import override_store
    path = latch_path(state_dir)
    if not path.exists():
        return False
    with override_store.locked(path):
        document = _read_latches(path)
        row = document['accounts'].get(account)
        if not isinstance(row, dict) or row.get('credential_key'):
            return False
        if expected_observed_at is not None and row.get('observed_at') != expected_observed_at:
            return False
        row['credential_key'] = credential_key
        if isinstance(online_plan, str) and online_plan and not row.get('online_plan'):
            row['online_plan'] = online_plan
        override_store.write(path, document)
    return True


def latched(state_dir=None):
    return _read_latches(latch_path(state_dir))['accounts']


def clear_latch(account, *, state_dir=None, expected_observed_at=None, launched_at=None):
    if not isinstance(account, str) or not account:
        return False
    import override_store
    path = latch_path(state_dir)
    if not path.exists():
        return False
    with override_store.locked(path):
        document = _read_latches(path)
        row = document['accounts'].get(account)
        if not isinstance(row, dict):
            return False
        if expected_observed_at is not None and row.get('observed_at') != expected_observed_at:
            return False  # A newer launch failure outranks this recovery.
        if launched_at is not None:
            launched, observed = _time(launched_at), _time(row.get('observed_at'))
            if not (launched and observed and launched > observed):
                return False
        del document['accounts'][account]
        override_store.write(path, document)
    return True


USAGE_RETRY_SECONDS = 300


def usage_refused_retry_at(cached, poll=None, attempt=None, now=None):
    """Next poll/retry timestamp for a usage-API plan refusal (402 or inactive error code)."""
    if not isinstance(cached, dict):
        return None
    observed = _time(cached.get('error_at') or cached.get('fetched_at'))
    if observed is None and isinstance(attempt, dict) and isinstance(attempt.get('at'), (int, float)) and not isinstance(attempt.get('at'), bool):
        observed = datetime.fromtimestamp(attempt['at'], tz=timezone.utc)
    if observed is None and isinstance(poll, dict) and isinstance(poll.get('at'), (int, float)) and not isinstance(poll.get('at'), bool):
        observed = datetime.fromtimestamp(poll['at'], tz=timezone.utc)
    if observed is None:
        observed = _time(now) if isinstance(now, str) else now
    if not isinstance(observed, datetime):
        return None
    seconds = None
    ckey = cached.get('credential_key')
    if isinstance(attempt, dict) and (not ckey or attempt.get('credential_key') == ckey):
        cand = attempt.get('retry_seconds')
        if isinstance(cand, (int, float)) and not isinstance(cand, bool) and cand > 0:
            seconds = cand
    if seconds is None and isinstance(poll, dict):
        cand = poll.get('seconds')
        if isinstance(cand, (int, float)) and not isinstance(cand, bool) and cand > 0:
            seconds = cand
    if seconds is None:
        seconds = USAGE_RETRY_SECONDS
    return (observed + timedelta(seconds=seconds)).isoformat()


def usage_refused_reason(cached, retry_at=None, poll=None, attempt=None, now=None):
    detail = (cached.get('error_code') or cached.get('error_status')) if isinstance(cached, dict) else None
    when = retry_at or usage_refused_retry_at(cached, poll=poll, attempt=attempt, now=now)
    suffix = f' (auto-retry at {when})' if when else ''
    return f'usage API refused: {detail}{suffix}'


def latch_retry_at(latch):
    observed = _time((latch or {}).get('observed_at'))
    return (observed + timedelta(hours=LATCH_RETRY_HOURS)).isoformat() if observed else None


def latch_reason(latch):
    retry_at = latch_retry_at(latch) or f'after {LATCH_RETRY_HOURS:g}h'
    return (f'a launch reported the subscription inactive (auto-retry at {retry_at}, '
            'or clear with `account_state.py --clear <account>`)')


def latch_outlived(latch, last_good, row=None, now=None):
    """Unlock when the 6h re-probe timer expires, the credential changed, or an online plan source reports a different active plan."""
    observed = _time((latch or {}).get('observed_at'))
    if not observed:
        return False
    current_now = _time(now) if isinstance(now, str) else now
    if current_now and (current_now - observed).total_seconds() >= LATCH_RETRY_HOURS * 3600:
        return True
    if not isinstance(row, dict):
        return False
    latched_key, current_key = (latch or {}).get('credential_key'), row.get('credential_key')
    if latched_key and current_key and latched_key != current_key:
        return True
    fetched = _time(last_good)
    if not (fetched and fetched > observed):
        return False
    family = row.get('quota_family') or row.get('family')
    plan = row.get('plan')
    plan_read = _time(row.get('plan_read_at'))
    prior_plan = (latch or {}).get('online_plan')
    return bool(row.get('plan_source') in ONLINE_PLAN_SOURCES and plan
                and not plan_is_inactive(family, plan) and plan_read and plan_read > observed
                and (not prior_plan or plan_without_vendor(plan) != plan_without_vendor(prior_plan)))


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--clear', metavar='ACCOUNT', help='Clear one latched launch failure by hand')
    args = parser.parse_args()
    if args.clear:
        clear_latch(args.clear)
    print(json.dumps(latched(), ensure_ascii=False, indent=2))
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