SLOPSHOPPER

sg-omniroute

Snow Gloves OmniRoute ledger: records tokens, cache use and model per request, draws a meter above the prompt, and /omniroute and /combo show the ledger and…

newpanebandcommandprocess
v0.1.0no licenseupdated 2026-10-10Sheshiyer/snow-gloves-os/mods/sg-omniroute
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · sg-omniroute
│ ┃ OmniRoute ✕ › fix the failing auth test and add an audit log call │ ┃ OmniRoute ledger: 0 requests r: refresh │ ┃ No requests recorded yet. ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /omniroute │ │ omniroute · ctx 49% · five_hour 31% · $0.42 ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
omniroute · ctx 49% · five_hour 31% · $0.42 ⟨Claude Code's own drawing⟩
Pane · OmniRoute
OmniRoute ledger: 0 requests r: refresh No requests recorded yet.
Pane · Combos
Combos: 0 r: reload Combos unavailable: dev
README

<img src="docs/assets/snowgloves-hero.png" width="100%" alt="Snow Gloves OS — Hand-In-Glove Business Operations Platform" />

Snow Gloves OS

Hand-In-Glove Business Operations Platform

<!-- og:image: docs/assets/snowgloves-og.png (upload via repo Settings → Social preview) -->

<!-- readme-gen:start:badges -->

Version Status Release License Hermes

<!-- readme-gen:end:badges -->

<!-- readme-gen:start:tech-stack --> <img src="https://skillicons.dev/icons?i=py,bash,yaml,rust,tauri,github,githubactions&theme=dark" alt="Tech Stack" /> <!-- readme-gen:end:tech-stack -->

<!-- readme-gen:start:social -->

Stars Last Commit Issues

<!-- readme-gen:end:social -->

Run a business as if a senior team were watching it 24/7. Snow Gloves OS is a reusable, tenant-scoped operations platform. It wraps your tools (G-Stack connectors), your knowledge (NVIDIA embeddings), your judgement (an interpretation layer), and your actions (Hermes + Paperclip orchestration), so events don't get dropped, decisions are auditable, and risky actions are gated. It is agent-agnostic: you pick the runtime (Claude Code, Codex, Cursor, OpenCode, Grok, Hermes, OpenClaw, or any other agent), and Snow Gloves renders its skills, MCP servers, and rules into that runtime's own format.

Docs for new users: snow-gloves-wiki — how to use the app and the ecosystem (install, pick a runtime, onboard, modules, a quiet week). Slides, audio, and video live there. The modules dashboard is the catalog, not the human guide.

The Infrastructure cockpit connects the playable Infra Block city to catalog, agent routing, runtime adapters, connector gates, scoped tenant metadata, wing profiles, activity records and acceptance evidence. Run python3 scripts/infra_cockpit.py and npm --prefix apps/infra-block run dev, then open http://127.0.0.1:18760/. The workspace supports source inspection and gate-checked proposal exports. Private instance metadata requires an explicit --data-root; execution and enablement remain outside this read-only interface.

<img src="https://capsule-render.vercel.app/api?type=rect&color=gradient&customColorList=12,13,14&height=2" width="100%" />

✨ Highlights

<table> <tr> <td width="50%" valign="top">

🧤 Hand-In-Glove

Seven specialized agents (CEO, CTO, Chief of Staff, Librarian, Interpreter, Dispatcher, Sentinel) work as one operations team, each with IDENTITY · SOUL · TOOLS · SKILLS · HEARTBEAT · MEMORY · EVOLUTION.

</td> <td width="50%" valign="top">

🧭 Skill Orchestration

A dedicated Chief of Staff routes four native snowgloves: skills via glob-matched hooks so CEO/CTO stay strategic. inference-sh and Explee are catalog packs, not core. Enable a module and it is callable across agents.

</td> </tr> <tr> <td width="50%" valign="top">

🗂 Modules & Catalog

132 catalog cards (skills, MCP servers, plugins, playbooks, connectors) harvested from X, Instagram, Field Theory, founders-kit, and marketingskills — including optional inference-sh and Explee packs. Every card is a pointer with a disposition: add, pointer, hold, or refuse.

</td> <td width="50%" valign="top">

🔀 Runtime Adapters

One adapter.yaml per runtime says where skills, MCP config, and rules live and which question tool drives plan mode. The founder picks the runtime; nothing is hard-wired to one agent.

</td> </tr> <tr> <td width="50%" valign="top">

🔌 G-Stack Connector Fabric

Composio-like scoped connectors (Gmail, Calendar, Drive, Slack, PMS, Accounting, HRIS). Per-capability risk + approval flags. Webhooks signed and verified.

</td> <td width="50%" valign="top">

🧠 NVIDIA Embeddings

Tenant-isolated vector index (nv-embedqa-e5-v5, 1024-dim). Plug into NVIDIA NIM with NVIDIA_API_KEY, or run offline with the deterministic stub backend.

</td> </tr> <tr> <td width="50%" valign="top">

🛰️ Hermes Event Bus

Minimal HTTP listener on port 4100 (scripts/hermes.py). POST /publish, GET /events, POST /test/e2e for end-to-end smoke. Every event is append-logged to _audit/hermes-events.jsonl.

</td> <td width="50%" valign="top">

🛡️ Sentinel Drift Sweep

Daily aggregation of hook usage, fallbacks, escalations, and top skills per agent. Auto-appended to each agent's EVOLUTION.md for self-improving loops.

</td> </tr> </table>

<img src="https://capsule-render.vercel.app/api?type=rect&color=gradient&customColorList=12,13,14&height=2" width="100%" />

🚀 Quick Start

git clone https://github.com/Sheshiyer/snow-gloves-os.git
cd snow-gloves-os
./scripts/install.sh              # deps + print next steps (does not go live)
make doctor                       # pre-flight
make smoke                        # bus up, test event, stub embed, Sentinel
make walk                         # machine-check CoS graph + native inner loops
make graph-upgrade                # learning-edge dry-run (constraints; hooks gated)
make onboard-prompt R=claude      # print the plan-mode interview for your runtime
make test                         # pytest

Fleet: three Mac minis

Snow Gloves runs on three office Mac minis by function (marketing, design, coding) over Tailscale. The Coding Mac hosts OmniRoute :20128 and Hermes :4100 for the whole fleet. A brand (tenant) is enabled on a wing (node), and make fleet-render W=<wing> T=<tenant> R=<runtime> writes that brand's modules and the wing's MCPs into the runtime's own files. Start with docs/fleet/README.md; make fleet-doctor tells a mini whether it is wired as its wing says.

New Mac Mini (use the product, do not compile Tauri): docs/MAC-MINI-SETUP.md. Emulate the desktop wizard on a dev Mac with make app-install then make app-dev — apps/onboarding/README.md. The fleet inventory is fleet.yaml in your private data checkout (template: fleet.example.yaml), and each wing's machine profile lives in nodes/ (nodes/<wing>/node.yaml; templates here, the instance copy in the data checkout wins).

Private data

This repository is the platform. Instance data (brand tenants, the fleet inventory and wing profiles, receipts, decisions, planning state) lives in a separate private checkout, snow-gloves-ops. Point the scripts at it:

export SNOWGLOVES_DATA=/path/to/snow-gloves-ops   # tenants/, fleet.yaml, nodes/, _audit/

Unset, everything resolves to this checkout and its public fixtures (_demo, acme, tryambakam-noesis), which the local validation commands use; make smoke and make walk always use the fixtures. The resolver is scripts/lib/paths.py; scripts/onboard.py, node_profile.py, graph_upgrade.py and upgrade.py also take --data DIR. Never commit tenants, fleet.yaml, receipts or planning state here.

Planned fresh-node CLI onboarding: layered setup plan and Claude start prompt. This covers an always-on Mac mini workspace, developer tooling, Temperance/OmniRoute, secrets, and selected brand capabilities. It is a planning candidate; the node bootstrap CLI is not implemented yet.

TargetPurpose
make installBootstrap (paperclipai + python deps)
make doctorPre-flight diagnostic
make onboardInteractive tenant + sources prompt (legacy flow)
make onboard-prompt R=<runtime>Print the plan-mode interview prompt for a runtime
make catalog / make catalog-checkRebuild catalog/modules.json + registry.yaml / fail if stale
make legacy-checkFail if pre-Hermes bus names remain (skips .bak-*)
make siteBuild the static dashboard site (npm run build:site)
make hermesForeground Hermes listener on :4100
make smokeHermes → e2e → bridge dry-run → embed stub → sentinel
make walkRoute fixtures through CoS; native produce/check/correct; receipt JSON
make tuiOnboarding TUI (agent vs manual; --headless for agents)
make graph-upgrade [T=<slug>] [WRITE=1]Learning edge dry-run (or apply constraints; hook diffs need approval)
make embed T=<tenant>Run NVIDIA embed worker (QUIET=1 for cron)
make sentinelDaily drift sweep
make release-dry V=x.y.zPreview a platform version bump
make release V=x.y.zBump every version file, rebuild catalog, commit, tag (no push)
make release-push V=x.y.zPush HEAD + tag; signing and publication require explicit manual steps
make release-checkVerify all version files agree with VERSION
make upgrade [T=<slug>] [WRITE=1]Dry-run (or apply) tenant platform migrations
make kill-hermesFree port 4100
make fleet-doctor [W=<wing>] / fleet-render W= T= R= / fleet-enable W= T= / fleet-connect W= / fleet-kit-export / fleet-remote-access W=Three-mini fleet: wing diagnostics, brand x wing x runtime render, enable, Tailscale shell, gateway kit, remote-access plan (docs/fleet/README.md)
make app-install / app-dev / app-buildTauri onboarding app: npm install, tauri dev (GUI), release bundle

<img src="https://capsule-render.vercel.app/api?type=rect&color=gradient&customColorList=12,13,14&height=2" width="100%" />

<!-- readme-gen:start:architecture -->

🏗 Architecture

graph TD
  subgraph Runtime layer
    Ext[3rd-party app] -- signed webhook --> GS[G-Stack /webhook]
    GS -- normalized envelope --> Her[Hermes :4100]
    Her --> CoS[Chief of Staff<br/>skill-hooks.yaml]
    CoS -->|strategy| CEO
    CoS -->|technical| CTO
    CoS --> Lib[Librarian]
    CoS --> Int[Interpreter]
    CoS --> Dis[Dispatcher]
    CoS --> Sen[Sentinel]
    Dis --> PB[Paperclip Bridge<br/>:3100/api/tasks]
    Lib --> EW[NVIDIA Embed Worker]
    EW --> VI[(tenant vector-index.jsonl)]
    Her -- audit --> Log[(_audit/hermes-events.jsonl)]
    Log --> SS[Sentinel Sweep<br/>daily]
    SS --> Evo[(agents/*/EVOLUTION.md)]
  end

  subgraph Catalog and adapter layer
    Cards[catalog/cards/*.md] --> BC[build_catalog.py]
    Agents[agents/*/MANIFEST.yaml] --> BC
    Ad[adapters/*/adapter.yaml] --> BC
    BC --> MJ[(catalog/modules.json)]
    MJ --> Prompt[onboard.py --prompt runtime]
    Prompt --> Harvest[snowgloves-harvest.md]
    Harvest --> Apply[onboard.py --apply-harvest]
    Apply --> En[(tenants/slug/enabled.yaml<br/>runtime.yaml)]
    En --> Render[onboard.py --render-adapter]
    Ad --> Render
    Render --> RT[Runtime files:<br/>skills, MCP config, rules block]
    MJ --> Dash[Tauri dashboard + Pages site]
    En --> Gate[connector-gate]
  end

Four reusable engines

EngineOwnsFiles
ConnectorG-Stack fabric, scopes, webhooksconnectors/g-stack/, skills/connector-gate/
KnowledgeIngest, chunk, embed, retrievescripts/ingest.py, scripts/embed_worker.py
InterpretationSkill routing, escalationworkflows/skill-hooks.yaml, agents/chief-of-staff/
OrchestrationEvent bus + Paperclip bridgescripts/hermes.py, scripts/paperclip_bridge.py

More detail: docs/architecture-overview.md.

<!-- readme-gen:end:architecture -->

🗂 Modules & Catalog

catalog/cards/<id>.md holds one card per third-party skill, MCP server, plugin, connector, or playbook. A card is a pointer, never a copy of upstream code. scripts/build_catalog.py compiles the cards, the agent manifests, the adapters, and the G-Stack connectors into catalog/registry.yaml and catalog/modules.json (schema snowgloves.modules.v1). Run make catalog-check locally to reject stale generated output.

DispositionCountMeaning
add61Tenant can enable it
pointer45Tenant can enable it as a reference; the host already provides it
hold14Visible, not enableable until the founder picks it and it passes review
refuse12Visible, never enableable

By category: skills 79, playbook 36, plugin 13, mcp 3, connector 1. Optional packs inference-sh-agent-skills and explee-skills are add cards, not core hooks. Card schema: docs/catalog.md. Harvest notes: docs/research/2026-09-29-ecosystem-review.md.

🔀 Runtime Adapters & Onboarding

Snow Gloves does not assume an agent. Each runtime has adapters/<runtime>/adapter.yaml (schema snowgloves.adapter.v1): skill, MCP, and rules paths; file formats; the runtime's question tool; and how to enter plan mode. Shipped adapters: hermes, claude, codex, cursor, opencode, grok, openclaw, muse, generic. Fields nobody has confirmed against the real runtime are marked verify: true and reported on every render. The Muse adapter is a guess throughout.

Onboarding is a plan-mode interview run inside the project the founder has been building:

make onboard-prompt R=cursor                                        # 1. interview → snowgloves-harvest.md
python3 scripts/onboard.py --apply-harvest snowgloves-harvest.md --tenant acme   # 2. apply
python3 scripts/onboard.py --list --category skills                 # 3. adjust
python3 scripts/onboard.py --enable ms-copywriting --tenant acme
python3 scripts/onboard.py --render-adapter cursor --tenant acme    # 4. render (dry run)
python3 scripts/onboard.py --render-adapter cursor --tenant acme --write

The agent asks one decision at a time, takes options only from modules.json, and writes FILL: instead of guessing. See docs/onboarding.md and docs/adapters.md.

🖥 Dashboard

The native Tauri v2 app in apps/onboarding/ gains a Modules dashboard and a guided onboarding flow. Both read the same catalog/modules.json plus each tenant's enabled.yaml. The same data is published as a static site, built with make site (npm run build:site) previously published by GitHub Pages. Automatic publishing is retired; this URL retains its last published content until a separate local publisher is selected:

https://sheshiyer.github.io/snow-gloves-os/

make app-install   # one-time: npm install
make app-dev       # launch in dev mode (hot-reload frontend)
make app-build     # produce a signable release bundle
make site          # build the static Pages site locally

See its README for the IPC surface and capability list.

📦 Release & Upgrade

The root VERSION file (currently 0.2.1) is the platform version. The app's package.json, tauri.conf.json, Cargo.toml, both lockfiles, and distribution.yaml are kept in lockstep with it, and catalog/modules.json embeds it.

make release-dry V=0.2.1    # show every file that would change
make release V=0.2.1        # bump, rebuild catalog, finalize CHANGELOG, commit, tag v0.2.1
make release-push V=0.2.1   # push only; no automatic signing or publication
make upgrade                # dry-run tenant migrations to VERSION
make upgrade T=acme WRITE=1 # apply, rebuild catalog, re-render acme's adapters

The retired hosted release built signed Tauri installers and attached source, catalog, adapter, and checksum assets. Those publication jobs are no longer active. make app-build remains the local app build entry point; signing, cross-platform builds, updater latest.json, and publication require a separately reviewed local procedure. v0.2.0 is a reinstall for 0.1.x (new bundle id). See docs/RELEASING.md and docs/UPGRADING.md.

<!-- readme-gen:start:tree -->

📂 Project Structure

📦 snow-gloves-os
├── 📄 VERSION                  # platform version (0.2.1)
├── 📄 distribution.yaml        # what the platform owns vs what tenants own
├── 📂 .local-jobs/             # explicit local checks; schedules disabled
├── 📂 .specify/                # Spec-Kit templates + workflows
├── 📂 .planning/               # GSD state: local symlink into the private data checkout (gitignored)
├── 📂 agents/                  # 7 agents, each with 8+ md files + MANIFEST
├── 📂 adapters/                # one adapter.yaml per runtime (9)
├── 📂 catalog/                 # SCHEMA.md · cards/ (132) · registry.yaml · modules.json (generated)
├── 📂 prompts/                 # onboard-interview.md (plan-mode interview template)
├── 📂 migrations/              # v0_1_to_v0_2.py (bus rename to Hermes)
├── 📂 apps/onboarding/         # Tauri v2 app: onboarding + Modules dashboard, Pages site
├── 📂 connectors/g-stack/      # Capability registry + auth + webhooks
├── 📂 scripts/                 # hermes · ingest · embed · bridge · sentinel · build_catalog · onboard · release · upgrade
├── 📂 skills/                  # registry.yaml (4 native skills) · connector-gate · sg-onboard · tn-seed · gtm-brief-synthesis
├── 📂 workflows/               # skill-hooks.yaml — Chief of Staff graph
├── 📂 specs/                   # Spec-Kit features
├── 📂 docs/                    # architecture, catalog, adapters, onboarding, releasing, upgrading, research, runbooks
├── 📂 tenants/                 # Fixture tenants only; real tenants live in $SNOWGLOVES_DATA/tenants
├── 📂 nodes/                   # Wing profile templates (marketing, design, coding)
├── 📄 fleet.example.yaml       # Fleet inventory template (the real fleet.yaml is private)
├── 📂 tests/                   # pytest suite
├── 📂 _audit/                  # Append-only event log
├── 📄 config/snowgloves.yaml   # Runtime config (ports, embeddings, scopes)
└── 📄 Makefile                 # make smoke runs the whole loop

<!-- readme-gen:end:tree -->

<img src="https://capsule-render.vercel.app/api?type=rect&color=gradient&customColorList=12,13,14&height=2" width="100%" />

<!-- readme-gen:start:health -->

📊 Project Health

CategoryStatusScore
Spec coverage████████████████████100%
Agents wired████████████████████100%
End-to-end smoke████████████████████100%
Local validation (pytest, version + catalog, make walk, smoke; execution is opt-in)████████████████████100%
Catalog (132 cards, --check in CI)████████████████████100%
Runtime adapters (9 shipped; several fields still verify: true)██████████░░░░░░░░░░50%
Release + upgrade tooling (v0.2.1 stable)████████████████░░░░80%
Real NVIDIA NIM integration████░░░░░░░░░░░░░░░░20%
Live Paperclip wiring████░░░░░░░░░░░░░░░░20%
Production hardening████░░░░░░░░░░░░░░░░20%

Overall: 70% — Stable v0.2.1 platform. Before a live pilot: confirm unverified adapter fields, and wire real connectors, NIM, and Paperclip.

<!-- readme-gen:end:health -->

Open items

  • Bundle id (decided). The app id is com.tryambakam.snowgloves.onboarding (was com.thoughtseed.snowgloves.onboarding). v0.2.0 is a new app: existing 0.1.x users must reinstall from the DMG/MSI; OTA will not find 0.2.0.
  • distribution.yaml lacks hermes_requires. Nothing declares which Hermes version or port a distribution needs yet. Do not set it in this release.
  • Unverified adapter fields. Muse is a guess throughout; the OpenClaw question tool and plan mode, and Codex /plan, are unconfirmed. See docs/adapters.md.

🧪 Spec-Driven Development

This repo uses GitHub Spec-Kit. Available slash commands (in Copilot/Codex chat):

/speckit.constitution    /speckit.specify    /speckit.clarify
/speckit.plan            /speckit.tasks      /speckit.analyze
/speckit.checklist       /speckit.implement  /speckit.taskstoissues

Active feature: specs/001-hand-in-glove-platform.

📜 Constitution

7 principles govern every change:

  1. Spec before code
  2. Tenant isolation first
  3. Interpretation before automation
  4. Approval-gated risk
  5. Auditability by default
  6. Wiki as human control surface
  7. Portable domain packs

See .specify/memory/constitution.md.

<!-- readme-gen:start:footer -->

<img src="https://capsule-render.vercel.app/api?type=waving&color=gradient&customColorList=12,13,14&height=110&section=footer" width="100%" />

Built with ❤️ by Mage Narayan · Tryambakam Noesis

<!-- readme-gen:end:footer -->

Source 3 files
hooks/register.tsx 150 lines
1// sg-omniroute: a ledger of what each model request cost. A turn.step hook records the tokens, cache use
2// and model of every request (the main conversation and each subagent apart); a band above the prompt
3// shows context, rate limits, cache share and cost; /omniroute opens the ledger and /combo lists the
4// gateway's combos. Read-only toward OmniRoute: the combos come from its database opened read-only by
5// scripts/sg_mods.py, and the mod never touches its key or changes the session's model.
6import { atom, read, update } from 'claude-code'
7import type { EngineInterface, PluginOptions, Register } from 'claude-code'
8
9import type { Row } from '../types'
10import { addRow, comboLine, combosFrom, ledgerText, meterText, platformRootFrom, rowLine, rowOf, totalLine, totalsByModel } from './lib'
11
12const PANE = 'sg-omniroute'
13const COMBO_PANE = 'sg-omniroute-combos'
14const RUN_TIMEOUT_MS = 15_000
15
16const rows = atom({ plugin: 'sg-omniroute', key: 'rows' } as const, [])
17const combos = atom({ plugin: 'sg-omniroute', key: 'combos' } as const, [])
18const comboError = atom({ plugin: 'sg-omniroute', key: 'comboError' } as const, null)
19const meter = atom({ plugin: 'sg-omniroute', key: 'meter' } as const, null)
20
21let pluginOptions: PluginOptions = {}
22
23async function loadCombos($: EngineInterface) {
24  try {
25    const root = String(pluginOptions.platformRoot || '') || platformRootFrom($.plugin.root)
26    const venv = root + '/.venv/bin/python'
27    const python = (await $.fs.exists(venv)) ? venv : 'python3'
28    const argv = [python, root + '/scripts/sg_mods.py', 'combos']
29    const db = String(pluginOptions.combosDb || '')
30    if (db) argv.push('--db', db)
31    const run = await $.process.run(argv, { cwd: root, timeoutMs: RUN_TIMEOUT_MS })
32    const list = combosFrom(run.stdout)
33    if (list === null) {
34      await update($, comboError, () => run.stdout.trim() || run.stderr.trim().split('\n').pop() || 'exit ' + run.exitCode)
35      return
36    }
37    await update($, combos, () => list)
38    await update($, comboError, () => null)
39  } catch (err) {
40    await update($, comboError, () => String(err instanceof Error ? err.message : err)).catch(() => undefined)
41  }
42}
43
44async function refreshMeter($: EngineInterface) {
45  try {
46    const held: Row[] = await read($, rows)
47    const usage = await $.session.usage()
48    await update($, meter, () => meterText(usage, held))
49  } catch {
50    // the meter keeps its last text
51  }
52}
53
54export const register: Register = (on, options) => {
55  pluginOptions = options
56
57  on('session.start', async ($, e, next) => {
58    await $.command.register({ name: 'omniroute', description: 'Per-request token, cache and model ledger', immediate: true })
59    await $.command.register({ name: 'combo', description: "List the OmniRoute gateway's combos", immediate: true })
60    return next(e)
61  })
62
63  // The ledger only watches: the request and its result go through as they came
64  on('turn.step', async function* ($, e, next) {
65    const result = yield* next(e)
66    try {
67      const row = rowOf(result.turnId, result.index, e.agentId, e.model, result.usage)
68      if (row) {
69        await update($, rows, (old: Row[]) => addRow(old, row))
70        await refreshMeter($)
71      }
72    } catch {
73      // a ledger failure never touches the turn
74    }
75    return result
76  })
77
78  on('command.run', { command: 'omniroute' }, async ($) => {
79    const drawn = (await $.session.surfaces()).length > 0
80    await refreshMeter($)
81    const placed = drawn ? await $.ui.open({ id: PANE, title: 'OmniRoute', focus: true, closeOnEscape: true }) : null
82    if (placed && placed.isPlaced) return {}
83    return { text: ledgerText(await read($, rows)) }
84  })
85
86  on('command.run', { command: 'combo' }, async ($) => {
87    await loadCombos($)
88    const drawn = (await $.session.surfaces()).length > 0
89    const placed = drawn ? await $.ui.open({ id: COMBO_PANE, title: 'Combos', focus: true, closeOnEscape: true }) : null
90    if (placed && placed.isPlaced) return {}
91    const reason = await read($, comboError)
92    if (reason !== null) return { text: 'Combos unavailable: ' + reason }
93    const list = await read($, combos)
94    return { text: list.length ? list.map(comboLine).join('\n') : 'OmniRoute has no combos.' }
95  })
96
97  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
98    const text = await read($, meter)
99    if (e.props.hasSurvey || text === null) return next(e)
100    const { Box, Text } = $.ui.resolve(e)
101    const theirs = await next(e)
102    return (
103      <Box flexDirection="column">
104        <Text dimColor wrap="truncate-end">{text}</Text>
105        {theirs}
106      </Box>
107    )
108  })
109
110  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
111    const { Box, Button, Text } = $.ui.resolve(e)
112    const held: Row[] = await read($, rows)
113    const totals = totalsByModel(held)
114    return (
115      <Box flexDirection="column">
116        <Box flexDirection="row" columnGap={2}>
117          <Text bold>{'OmniRoute ledger: ' + held.length + ' requests'}</Text>
118          <Button key="refresh" label="refresh" hotkey="r" plain onPress={() => refreshMeter($)} />
119        </Box>
120        {held.length === 0 && <Text dimColor>No requests recorded yet.</Text>}
121        {totals.map((t) => (
122          <Text key={'total-' + t.model} wrap="truncate-end">{totalLine(t)}</Text>
123        ))}
124        {held.length > 0 && <Text bold>Latest</Text>}
125        {held.slice(-15).reverse().map((r) => (
126          <Text key={'row-' + r.turnId + '-' + r.index + '-' + r.agent} dimColor wrap="truncate-end">{rowLine(r)}</Text>
127        ))}
128      </Box>
129    )
130  })
131
132  on('ui.render', { component: 'Pane', requestId: COMBO_PANE }, async ($, e) => {
133    const { Box, Button, Text } = $.ui.resolve(e)
134    const list = await read($, combos)
135    const reason = await read($, comboError)
136    return (
137      <Box flexDirection="column">
138        <Box flexDirection="row" columnGap={2}>
139          <Text bold>{'Combos: ' + list.length}</Text>
140          <Button key="reload" label="reload" hotkey="r" plain onPress={() => loadCombos($)} />
141        </Box>
142        {reason !== null && <Text color="red">{'Combos unavailable: ' + reason}</Text>}
143        {list.map((c) => (
144          <Text key={'combo-' + c.name} wrap="truncate-end">{comboLine(c)}</Text>
145        ))}
146      </Box>
147    )
148  })
149}
150
hooks/lib.ts 97 lines
1// Pure helpers for sg-omniroute. No $ here.
2import type { Combo, Row } from '../types'
3
4export const KEEP = 200
5
6export function platformRootFrom(pluginRoot: string): string {
7  return pluginRoot.split('/').slice(0, -2).join('/')
8}
9
10type Usage = { model?: string; input_tokens?: number; output_tokens?: number; cache_read_input_tokens?: number; cache_creation_input_tokens?: number }
11
12// A ledger row from a finished step; null when the step made no request.
13export function rowOf(turnId: string, index: number, agentId: string | undefined, fallbackModel: string, usage: Usage | null | undefined): Row | null {
14  if (!usage) return null
15  return {
16    turnId,
17    index,
18    agent: agentId || 'main',
19    model: usage.model || fallbackModel,
20    input: usage.input_tokens || 0,
21    output: usage.output_tokens || 0,
22    cacheRead: usage.cache_read_input_tokens || 0,
23    cacheWrite: usage.cache_creation_input_tokens || 0,
24  }
25}
26
27export function addRow(rows: Row[], row: Row): Row[] {
28  return [...rows, row].slice(-KEEP)
29}
30
31// Share of the prompt the cache served: read / (read + written + uncached).
32export function cacheRatio(rows: Row[]): number | null {
33  const read = rows.reduce((n, r) => n + r.cacheRead, 0)
34  const all = rows.reduce((n, r) => n + r.cacheRead + r.cacheWrite + r.input, 0)
35  return all > 0 ? read / all : null
36}
37
38export type ModelTotal = { model: string; requests: number; input: number; output: number; cacheRead: number; cacheWrite: number }
39
40export function totalsByModel(rows: Row[]): ModelTotal[] {
41  const by = new Map<string, ModelTotal>()
42  for (const r of rows) {
43    const t = by.get(r.model) || { model: r.model, requests: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
44    t.requests += 1
45    t.input += r.input
46    t.output += r.output
47    t.cacheRead += r.cacheRead
48    t.cacheWrite += r.cacheWrite
49    by.set(r.model, t)
50  }
51  return [...by.values()].sort((a, b) => b.requests - a.requests)
52}
53
54export const kilo = (n: number) => (n >= 10_000 ? Math.round(n / 1000) + 'k' : n >= 1000 ? (n / 1000).toFixed(1) + 'k' : String(n))
55
56export function rowLine(r: Row): string {
57  return r.agent + '  ' + r.model + '  in ' + kilo(r.input) + '  out ' + kilo(r.output) + '  cache r' + kilo(r.cacheRead) + ' w' + kilo(r.cacheWrite)
58}
59
60export function totalLine(t: ModelTotal): string {
61  return t.model + '  ' + t.requests + ' req  in ' + kilo(t.input) + '  out ' + kilo(t.output) + '  cache r' + kilo(t.cacheRead) + ' w' + kilo(t.cacheWrite)
62}
63
64type RateLimit = { kind: string; percentUsed: number }
65export function meterText(usage: { context?: { percent?: number }; rateLimits?: RateLimit[]; cost?: { usd: number } } | null, rows: Row[]): string | null {
66  if (!usage) return null
67  const parts: string[] = []
68  if (typeof usage.context?.percent === 'number') parts.push('ctx ' + Math.round(usage.context.percent) + '%')
69  for (const l of usage.rateLimits || []) parts.push(l.kind + ' ' + Math.round(l.percentUsed) + '%')
70  const ratio = cacheRatio(rows)
71  if (ratio !== null) parts.push('cache ' + Math.round(ratio * 100) + '%')
72  if (typeof usage.cost?.usd === 'number') parts.push('$' + usage.cost.usd.toFixed(2))
73  return parts.length ? 'omniroute · ' + parts.join(' · ') : null
74}
75
76export function combosFrom(stdout: string): Combo[] | null {
77  try {
78    const data = JSON.parse(stdout)
79    return Array.isArray(data?.combos) ? data.combos : null
80  } catch {
81    return null
82  }
83}
84
85export function comboLine(c: Combo): string {
86  return c.name + '  ' + c.strategy + '  ' + c.members.length + ' members: ' + c.members.join(', ')
87}
88
89export function ledgerText(rows: Row[]): string {
90  if (!rows.length) return 'No requests recorded yet.'
91  const ratio = cacheRatio(rows)
92  return [
93    rows.length + ' requests' + (ratio === null ? '' : ', cache served ' + Math.round(ratio * 100) + '% of the prompt'),
94    ...totalsByModel(rows).map(totalLine),
95  ].join('\n')
96}
97
types/index.d.ts 25 lines
1// One model request of a turn, from turn.step's result.
2export type Row = {
3  turnId: string
4  index: number
5  agent: string
6  model: string
7  input: number
8  output: number
9  cacheRead: number
10  cacheWrite: number
11}
12// One OmniRoute combo as scripts/sg_mods.py combos lists it.
13export type Combo = { name: string; strategy: string; members: string[] }
14
15declare module 'claude-code' {
16  interface PluginState {
17    'sg-omniroute': {
18      rows: Row[]
19      combos: Combo[]
20      comboError: string | null
21      meter: string | null
22    }
23  }
24}
25