akiiwa-games/AgentCompass / skills/agent-compass
agent-compass
FlaggedChoose 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.
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
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| 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: 471k | Updated | Claude CodeCodex | Verified | Install |
| 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: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| 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 available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |