relay-opencode 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -2
  3. package/dist/artificial-analysis.d.ts +50 -0
  4. package/dist/artificial-analysis.js +153 -0
  5. package/dist/chat-facts.d.ts +26 -0
  6. package/dist/chat-facts.js +96 -0
  7. package/dist/contract.d.ts +2727 -0
  8. package/dist/contract.js +111 -0
  9. package/dist/costs.d.ts +14 -0
  10. package/dist/costs.js +47 -0
  11. package/dist/decider.d.ts +73 -0
  12. package/dist/decider.js +199 -0
  13. package/dist/gui-experimental.cjs +92 -0
  14. package/dist/gui-styles.d.ts +5 -0
  15. package/dist/gui-styles.js +95 -0
  16. package/dist/index.d.ts +6 -0
  17. package/dist/index.js +62 -0
  18. package/dist/intelligence.d.ts +38 -0
  19. package/dist/intelligence.js +123 -0
  20. package/dist/inventory.d.ts +34 -0
  21. package/dist/inventory.js +28 -0
  22. package/dist/ranking.d.ts +31 -0
  23. package/dist/ranking.js +78 -0
  24. package/dist/relay-auto.d.ts +39 -0
  25. package/dist/relay-auto.js +96 -0
  26. package/dist/relay-command.d.ts +74 -0
  27. package/dist/relay-command.js +211 -0
  28. package/dist/relay-store.d.ts +124 -0
  29. package/dist/relay-store.js +196 -0
  30. package/dist/relay-view.d.ts +124 -0
  31. package/dist/relay-view.js +189 -0
  32. package/dist/review-helper.d.ts +8 -0
  33. package/dist/review-helper.js +68 -0
  34. package/dist/router.d.ts +122 -0
  35. package/dist/router.js +209 -0
  36. package/dist/rpc.d.ts +2725 -0
  37. package/dist/rpc.js +116 -0
  38. package/dist/settings.d.ts +16 -0
  39. package/dist/settings.js +22 -0
  40. package/dist/standings.d.ts +18 -0
  41. package/dist/standings.js +34 -0
  42. package/dist/tui.d.ts +3 -0
  43. package/dist/tui.js +26 -0
  44. package/dist/usage-log.d.ts +135 -0
  45. package/dist/usage-log.js +210 -0
  46. package/dist/usage-view.d.ts +70 -0
  47. package/dist/usage-view.js +104 -0
  48. package/package.json +46 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Muhammad Asad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,123 @@
1
- # Temporary Holding Version
1
+ # Relay
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Relay picks the model for each message in OpenCode.** You choose models for three kinds of work, Plan, Execute and Review, once. Then you type `/relay <message>`, or turn Relay on for a chat. A small decision model reads the message, picks the kind of work and the model that fits it, switches the chat to that model, and sends your message.
4
+
5
+ <table>
6
+ <tr>
7
+ <td valign="top"><img src="docs/images/relay-panel.png" width="360" alt="The Relay panel: Plan and Execute, each with two models, their effort, price, intelligence index and a use-it-for line"></td>
8
+ <td valign="top"><img src="docs/images/model-table.png" width="360" alt="Adding a model: a searchable table of the models OpenCode offers, with price, context and intelligence index, sorted by index"><br><br><img src="docs/images/recent-choices.png" width="360" alt="Recent choices: each decision with its mode, model, how sure the decider was, and what the reply took"></td>
9
+ </tr>
10
+ </table>
11
+
12
+ <sub>The Relay panel with example settings and example Recent choices. The models, prices and index numbers are what OpenCode and Relay listed on 18 Nov 2026.</sub>
13
+
14
+ > Relay is early. It is built for OpenCode 2.3 and runs in OpenCode Desktop 2.4.1 on Windows. See [what has been tested](docs/status.md).
15
+
16
+ ## Why use it
17
+
18
+ - **The right model for each message.** A strong model for planning, a cheap one for small edits, a careful one for reviews. Relay switches for you.
19
+ - **Your own words decide.** Give each model a "use it for" line, such as "small, quick edits". Or write no lines, and Relay chooses by itself: the strongest model for big or tricky work, the cheapest for small work.
20
+ - **Mix providers.** Each kind of work can use a different provider. In testing, Claude (through a Claude login) planning and reviewing with a cheap OpenCode Go model building passed all six test exercises, and Go paid 89% less than with one Go model for each kind of work ([results](docs/status.md)).
21
+ - **See what you spend.** The **Relay usage** tab shows every reply of every chat: cost, tokens, a chart by day, totals by model, and filters.
22
+ - **Your message is safe.** It is sent once and unchanged. If choosing fails, it still goes to the chat's current model. Relay never stores its text.
23
+
24
+ ## Install
25
+
26
+ You need OpenCode 2.3 or newer: OpenCode Desktop or the terminal app.
27
+
28
+ 1. Open OpenCode's global config file:
29
+ - macOS and Linux: `~/.config/opencode/opencode.json`
30
+ - Windows: `C:\Users\<you>\.config\opencode\opencode.json`
31
+
32
+ If there is an `opencode.jsonc` there instead, use that. If neither exists, create `opencode.json` containing `{}`.
33
+ 2. Add Relay to the `plugins` list. Keep any plugins that are already in it. Use the newest version, which `npm view relay-opencode version` prints. Pinning it makes updates predictable.
34
+
35
+ ```json
36
+ {
37
+ "plugins": ["relay-opencode@0.2.0"]
38
+ }
39
+ ```
40
+
41
+ 3. Quit OpenCode completely and open it again. The first start downloads Relay from npm, so it can take a minute or two.
42
+ 4. Type `/` in a chat. `/relay` should be in the list.
43
+
44
+ Other ways to install, from source or as a fixed copy, are in the [guide](docs/guide.md#install-from-source).
45
+
46
+ ## Install with an AI agent
47
+
48
+ Give your coding agent (OpenCode, Claude Code, Cursor or another) this repository's link and this request:
49
+
50
+ > Install the OpenCode plugin from https://github.com/AsadKhalil/relay-opencode. Follow the section "Instructions for AI agents" in its README exactly, then tell me what you did and what I need to do next.
51
+
52
+ ### Instructions for AI agents
53
+
54
+ Follow these steps in order. Stop and ask the user when a step says so. Never print, copy or change API keys, tokens, passwords or login files.
55
+
56
+ 1. **Check OpenCode.** Run `opencode --version`.
57
+ - If it prints 2.3.0 or newer, go on.
58
+ - If the command is not found, look for OpenCode Desktop. On Windows it is `%LOCALAPPDATA%\Programs\ai.opencode.desktop\OpenCode.exe`, and its command-line binary is in `%APPDATA%\ai.opencode.desktop\cli\<version>-x64\opencode-cli.exe`. On macOS it is `/Applications/OpenCode.app`. If you find it, go on.
59
+ - If OpenCode is missing or older than 2.3.0, stop and ask the user to install or update it from https://opencode.ai.
60
+ 2. **Find the newest Relay version.** Run `npm view relay-opencode version`. Call the result `<version>`. If npm is not available, or it prints nothing or something that is not a plain version like `0.2.0` (for example `0.0.0-stage`, a placeholder npm shows while a release is held for review), use `latest` as `<version>`.
61
+ 3. **Find the config file.** The global config folder is `~/.config/opencode` (Windows: `%USERPROFILE%\.config\opencode`). Use `opencode.jsonc` if it exists there, else `opencode.json`. Never create a second config file next to an existing one. If neither exists, create `opencode.json` with the content `{}` and skip step 4.
62
+ 4. **Back it up.** Copy the file to `opencode.json.before-relay` (or `opencode.jsonc.before-relay`) in the same folder. If that name is taken, an earlier backup holds the original, so keep it and use `.before-relay-2` (then `-3`, and so on).
63
+ 5. **Add Relay.** Edit the file's text in place: never rewrite it from parsed JSON, which would drop the comments, trailing commas and formatting of a `.jsonc` file. Change only the `plugins` list:
64
+ - If `plugins` is missing, add `"plugins": ["relay-opencode@<version>"]` as a new top-level key.
65
+ - If an entry is exactly `"relay-opencode"` or starts with `"relay-opencode@"`, replace that one entry with `"relay-opencode@<version>"`.
66
+ - If an entry is a folder path ending in `relay-opencode` (an install from source or a fixed copy), stop and ask the user whether to replace it.
67
+ - Otherwise append `"relay-opencode@<version>"` and keep every other entry as it is.
68
+ - The key is `plugins` (plural): never add a second `plugins` key or a singular `plugin` key, and do not touch any other key, such as `permissions`.
69
+ 6. **Check the file.** For `.json`, it must parse: `node -e "JSON.parse(require('fs').readFileSync(process.argv[1],'utf8'))" <path>`. For `.jsonc`, a strict JSON check fails even on a good file, so check instead that the comments are still there and the brackets balance, or use a JSONC parser. If the file is broken, restore the backup and stop.
70
+ 7. **Restart OpenCode.** If you run inside OpenCode yourself, do not restart it: tell the user to quit OpenCode completely and open it again. Otherwise ask the user to restart it the same way. Do not end OpenCode's processes yourself.
71
+ 8. **Verify** after the restart. The first start downloads Relay, which can take a minute or two.
72
+ - In OpenCode's log (`~/.local/share/opencode/log/opencode.log`; Windows: `%USERPROFILE%\.local\share\opencode\log\opencode.log`) there is a `loading plugin` line naming `relay-opencode`, and no `failed to load plugin` line for it.
73
+ - Or ask the user to type `/` in a chat: `/relay` is listed.
74
+ 9. **Tell the user what to do next.** Relay's settings are made in OpenCode Desktop's Relay panel, and an agent cannot click there:
75
+ 1. Open a chat, open the command palette (**Ctrl+K** on Windows and Linux) and run **Open Relay**.
76
+ 2. Under **Plan**, **Execute** and **Review**, press **+ Add a model** and pick models.
77
+ 3. Press **+ Choose a decider** and pick a decision model.
78
+ 4. Type `/relay on` in a chat, or use the Relay pill above the chat box.
79
+
80
+ To remove Relay, delete its entry from `plugins` and restart OpenCode. Relay's saved settings stay in OpenCode's storage and come back if it is added again.
81
+
82
+ ## Update
83
+
84
+ - **Installed by name from npm:** change the version in `plugins` to the new one (`npm view relay-opencode version` prints it), then quit and reopen OpenCode. With an unpinned `"relay-opencode"`, OpenCode can keep an older copy in `~/.cache/opencode/npm/`.
85
+ - **From source or as a fixed copy:** see [the guide](docs/guide.md#update).
86
+
87
+ Your settings are kept across updates.
88
+
89
+ ## Set up (once, in Desktop)
90
+
91
+ 1. Open a chat, press **Ctrl+K** and run **Open Relay**. The Relay panel opens beside the chat.
92
+ 2. Under **Plan**, **Execute** and **Review**, press **+ Add a model** and pick models from the table. When a mode has more than one model, give each a short "use it for" line, or leave the lines empty and let Relay choose by itself.
93
+ 3. Press **+ Choose a decider** and pick a decision model. OpenCode lists free ones, such as `opencode/jev-1.13-free`, when they are offered.
94
+ 4. Type a sample message in the test box and press **Try** to see what Relay would pick.
95
+
96
+ The settings are shared by all your projects. The terminal app has no settings screen, so set them up in Desktop. The [guide](docs/guide.md#set-up) explains each setting.
97
+
98
+ ## Use
99
+
100
+ | You type | What happens |
101
+ |---|---|
102
+ | `/relay <message>` | Relay picks the mode and the model for this one message, switches the chat, and sends it. |
103
+ | `/relay on` | Every message you send in this chat goes through Relay, without typing `/relay`. |
104
+ | `/relay off` | This chat goes back to normal. |
105
+ | **Open Relay usage** (Ctrl+K) | The Relay usage tab: cost, tokens and records of every chat. |
106
+ | `/relay-stats` | In the terminal app: the totals Relay counted of its own messages before the usage tab. |
107
+
108
+ - **The Relay pill** above the chat box in Desktop shows whether Relay is on for that chat. Click it to turn Relay on or off.
109
+ - **Plan and Review** use OpenCode's `plan` agent, which is meant for reading and planning. Only **Execute** uses `build`, which can change files.
110
+ - **When the decider is not sure** (under 60%), `/relay` uses Plan. With `/relay on`, the chat stays as it is.
111
+
112
+ ## Learn more
113
+
114
+ - [Guide](docs/guide.md): each setting, the usage tab, the pill, Recent choices, other ways to install, and what to do if **Open Relay** is missing.
115
+ - [When Relay saves money](docs/saving-money.md): a switch to another model has a price, and Relay moves a chat only when it pays.
116
+ - [What leaves your machine](docs/privacy.md)
117
+ - [Prices and the intelligence index](docs/data-sources.md): where the numbers come from.
118
+ - [What has been tested, and known limits](docs/status.md)
119
+ - [Contributing and releasing](CONTRIBUTING.md) · [Change log](docs/implementation-progress.md) · [Findings on real OpenCode](docs/compatibility.md)
120
+
121
+ ## License
122
+
123
+ [MIT](LICENSE)
@@ -0,0 +1,50 @@
1
+ import type { Prices } from './relay-store.js';
2
+ export declare const AA_LIST_URL = "https://artificialanalysis.ai/api/v2/language/models/free";
3
+ export declare const AA_SOURCE = "Artificial Analysis Intelligence Index, from Artificial Analysis";
4
+ /** Artificial Analysis asks for this credit wherever its data is shown. */
5
+ export declare const AA_CREDIT = "Prices and index: Artificial Analysis (artificialanalysis.ai)";
6
+ /** `index` is the Intelligence Index and `coding` the Coding Index; either can be missing. */
7
+ export type AaModel = {
8
+ slug: string;
9
+ name: string;
10
+ creator: string;
11
+ released: string | null;
12
+ index: number | null;
13
+ coding: number | null;
14
+ prices: Prices;
15
+ };
16
+ type Store = {
17
+ get(key: string): Promise<unknown>;
18
+ set(key: string, value: unknown): Promise<void>;
19
+ remove(key: string): Promise<void>;
20
+ };
21
+ /** One page of the list: its models, and whether another page follows. An entry with no slug or name is left out. */
22
+ export declare function parseAaPage(body: unknown): {
23
+ models: AaModel[];
24
+ more: boolean;
25
+ };
26
+ /** Every page of the list (five at most). An error names what went wrong, never the key. */
27
+ export declare function fetchAaModels(key: string, fetcher?: typeof fetch, ms?: number): Promise<AaModel[]>;
28
+ /** The stored list, with no request: what the idle hook reads. */
29
+ export declare function storedAaModels(store: Pick<Store, 'get'>): Promise<AaModel[]>;
30
+ /** The list: the stored copy while it is under a day old, else a fresh fetch, stored; when that fails, the older copy with a note. */
31
+ export declare function loadAaModels(store: Pick<Store, 'get' | 'set'>, key: string, fetcher: typeof fetch, now: number): Promise<{
32
+ models: AaModel[];
33
+ fetchedAt: string | null;
34
+ note: string | null;
35
+ }>;
36
+ /**
37
+ * The listed model that is `model` at its effort: an exact match of the id or name, as `modelKey` writes them, with the effort first and then
38
+ * without it. A key that two different models share matches nothing.
39
+ */
40
+ export declare function aaFor(model: {
41
+ providerID: string;
42
+ id: string;
43
+ name: string;
44
+ variant: string | null;
45
+ }, models: readonly AaModel[]): AaModel | null;
46
+ /** The saved key, or null. */
47
+ export declare function getPriceKey(store: Pick<Store, 'get'>): Promise<string | null>;
48
+ /** Saves the key, or with null removes it and the list fetched with it. The refusal never repeats what was typed. */
49
+ export declare function setPriceKey(store: Store, key: string | null): Promise<void>;
50
+ export {};
@@ -0,0 +1,153 @@
1
+ import { usdString } from './costs.js';
2
+ import { modelKey } from './intelligence.js';
3
+ // Artificial Analysis's free model list: each model's prices and intelligence index, with a key the owner saves in the panel. The key is sent
4
+ // only to this address, in `x-api-key`, and never shown, returned, recorded or written into a note. Read with the owner's test key on 19 Nov
5
+ // 2026: 763 models in four pages of 200, one entry for each effort (`claude-sonnet-5-5` is Max, `claude-sonnet-5-5-high` is High).
6
+ export const AA_LIST_URL = 'https://artificialanalysis.ai/api/v2/language/models/free';
7
+ export const AA_SOURCE = 'Artificial Analysis Intelligence Index, from Artificial Analysis';
8
+ /** Artificial Analysis asks for this credit wherever its data is shown. */
9
+ export const AA_CREDIT = 'Prices and index: Artificial Analysis (artificialanalysis.ai)';
10
+ const MAX_PAGES = 5, MAX_CHARS = 8_000_000, DAY_MS = 24 * 3600_000;
11
+ const LIST_KEY = 'relay/aa-models', PRICE_KEY = 'relay/aa-key';
12
+ const price = (value) => typeof value === 'number' ? usdString(value) : null;
13
+ const text = (value) => typeof value === 'string' ? value : null;
14
+ const score = (value) => typeof value === 'number' && Number.isFinite(value) ? value : null;
15
+ /** One page of the list: its models, and whether another page follows. An entry with no slug or name is left out. */
16
+ export function parseAaPage(body) {
17
+ const page = body;
18
+ const data = Array.isArray(page?.data) ? page.data : [];
19
+ const models = data.flatMap(item => {
20
+ const model = item;
21
+ if (!model || typeof model.slug !== 'string' || typeof model.name !== 'string')
22
+ return [];
23
+ const pricing = model.pricing ?? {};
24
+ return [{
25
+ slug: model.slug, name: model.name, creator: text(model.model_creator?.name) ?? '', released: text(model.release_date),
26
+ index: score(model.evaluations?.artificial_analysis_intelligence_index), coding: score(model.evaluations?.artificial_analysis_coding_index),
27
+ prices: { inputPerMillion: price(pricing.price_1m_input_tokens), outputPerMillion: price(pricing.price_1m_output_tokens), cacheReadPerMillion: price(pricing.price_1m_cache_hit_tokens), cacheWritePerMillion: price(pricing.price_1m_cache_write_tokens) },
28
+ }];
29
+ });
30
+ return { models, more: page?.pagination?.has_more === true };
31
+ }
32
+ const refusals = { 401: 'the key was refused', 403: 'the key may not read this list', 429: "today's 100 requests are used up" };
33
+ /** Every page of the list (five at most). An error names what went wrong, never the key. */
34
+ export async function fetchAaModels(key, fetcher = fetch, ms = 15_000) {
35
+ const models = [];
36
+ for (let page = 1; page <= MAX_PAGES; page++) {
37
+ const response = await fetcher(`${AA_LIST_URL}?page=${page}`, { headers: { 'x-api-key': key, accept: 'application/json' }, signal: AbortSignal.timeout(ms) });
38
+ if (!response.ok)
39
+ throw new Error(refusals[response.status] ?? `Artificial Analysis answered ${response.status}`);
40
+ const body = await response.text();
41
+ if (body.length > MAX_CHARS)
42
+ throw new Error('the list is too big');
43
+ let parsed;
44
+ try {
45
+ parsed = JSON.parse(body);
46
+ }
47
+ catch {
48
+ throw new Error('the reply is not a model list');
49
+ }
50
+ const found = parseAaPage(parsed);
51
+ models.push(...found.models);
52
+ if (!found.more)
53
+ break;
54
+ }
55
+ if (!models.length)
56
+ throw new Error('the list has no models');
57
+ return models;
58
+ }
59
+ const storedModel = (value) => {
60
+ const model = value, prices = model?.prices;
61
+ if (!model || typeof model.slug !== 'string' || typeof model.name !== 'string' || !prices || typeof prices !== 'object')
62
+ return null;
63
+ return {
64
+ // A copy stored before the Coding index was kept has none, until the next daily load.
65
+ slug: model.slug, name: model.name, creator: text(model.creator) ?? '', released: text(model.released), index: score(model.index), coding: score(model.coding),
66
+ prices: { inputPerMillion: text(prices.inputPerMillion), outputPerMillion: text(prices.outputPerMillion), cacheReadPerMillion: text(prices.cacheReadPerMillion), cacheWritePerMillion: text(prices.cacheWritePerMillion) },
67
+ };
68
+ };
69
+ async function stored(store) {
70
+ const value = await store.get(LIST_KEY);
71
+ if (!value || typeof value.fetchedAt !== 'string' || !Number.isFinite(Date.parse(value.fetchedAt)) || !Array.isArray(value.models))
72
+ return null;
73
+ return { fetchedAt: value.fetchedAt, models: value.models.map(storedModel).filter(model => model !== null) };
74
+ }
75
+ /** The stored list, with no request: what the idle hook reads. */
76
+ export async function storedAaModels(store) {
77
+ try {
78
+ return (await stored(store))?.models ?? [];
79
+ }
80
+ catch {
81
+ return [];
82
+ }
83
+ }
84
+ /** The list: the stored copy while it is under a day old, else a fresh fetch, stored; when that fails, the older copy with a note. */
85
+ export async function loadAaModels(store, key, fetcher, now) {
86
+ let saved = null;
87
+ try {
88
+ saved = await stored(store);
89
+ }
90
+ catch { /* read as no copy */ }
91
+ if (saved && now - Date.parse(saved.fetchedAt) < DAY_MS)
92
+ return { ...saved, note: null };
93
+ try {
94
+ const models = await fetchAaModels(key, fetcher), fetchedAt = new Date(now).toISOString();
95
+ try {
96
+ await store.set(LIST_KEY, { fetchedAt, models });
97
+ }
98
+ catch { /* shown anyway, fetched again next time */ }
99
+ return { models, fetchedAt, note: null };
100
+ }
101
+ catch (error) {
102
+ const reason = error instanceof Error && !error.message.includes(key) ? error.message : 'the request failed';
103
+ return saved ? { ...saved, note: `could not refresh the list from Artificial Analysis: ${reason}` } : { models: [], fetchedAt: null, note: `could not load the list from Artificial Analysis: ${reason}` };
104
+ }
105
+ }
106
+ // The subscription login's models are named by family only; Claude Code picks the version, so the newest in the list stands for it.
107
+ const FAMILIES = new Set(['sonnet', 'haiku', 'opus', 'fable']);
108
+ /**
109
+ * The listed model that is `model` at its effort: an exact match of the id or name, as `modelKey` writes them, with the effort first and then
110
+ * without it. A key that two different models share matches nothing.
111
+ */
112
+ export function aaFor(model, models) {
113
+ const table = new Map();
114
+ for (const listed of models)
115
+ for (const name of [listed.slug, listed.name]) {
116
+ const key = modelKey(name), found = table.get(key);
117
+ if (key && found !== null)
118
+ table.set(key, found && found.slug !== listed.slug ? null : listed);
119
+ }
120
+ let ids = [model.id, model.name];
121
+ if (model.providerID === 'claude-agent' && FAMILIES.has(model.id)) {
122
+ const base = new RegExp(`^claude-${model.id}-[\\d-]+$`);
123
+ const newest = models.filter(listed => listed.creator === 'Anthropic' && base.test(listed.slug)).sort((a, b) => (b.released ?? '').localeCompare(a.released ?? '') || a.slug.length - b.slug.length)[0];
124
+ if (!newest)
125
+ return null;
126
+ ids = [newest.slug];
127
+ }
128
+ const keys = [...(model.variant ? ids.map(id => modelKey(`${id}-${model.variant}`)) : []), ...ids.map(modelKey)];
129
+ for (const key of keys) {
130
+ const found = table.get(key);
131
+ if (found)
132
+ return found;
133
+ }
134
+ return null;
135
+ }
136
+ const KEY_SHAPE = /^\S{8,200}$/;
137
+ /** The saved key, or null. */
138
+ export async function getPriceKey(store) {
139
+ const value = await store.get(PRICE_KEY);
140
+ return typeof value === 'string' && KEY_SHAPE.test(value) ? value : null;
141
+ }
142
+ /** Saves the key, or with null removes it and the list fetched with it. The refusal never repeats what was typed. */
143
+ export async function setPriceKey(store, key) {
144
+ if (key === null) {
145
+ await store.remove(PRICE_KEY);
146
+ await store.remove(LIST_KEY);
147
+ return;
148
+ }
149
+ const trimmed = key.trim();
150
+ if (!KEY_SHAPE.test(trimmed))
151
+ throw new Error('That does not look like an Artificial Analysis key: it should be one word of 8 to 200 characters.');
152
+ await store.set(PRICE_KEY, trimmed);
153
+ }
@@ -0,0 +1,26 @@
1
+ import { type AaModel } from './artificial-analysis.js';
2
+ import type { ListedModel } from './inventory.js';
3
+ import { type Reply } from './relay-store.js';
4
+ import type { ChatFacts } from './router.js';
5
+ /** The chat's newest anchors, oldest first: at most `count`, however long the chat. */
6
+ export declare function newestAnchors(messages: unknown, count: number): {
7
+ id: string;
8
+ created: number;
9
+ summary: boolean;
10
+ }[];
11
+ /** The agent that answered an anchor: its first answer's, or `compaction` for a summary; null with no answer. */
12
+ export declare function agentOf(messages: unknown, anchorID: string): string | null;
13
+ /**
14
+ * What the reply to one message took, or null while it cannot be read: no such message, no answer to it yet, or an answer with no counts.
15
+ * `models` gives the prices of the model that answered. When it lists no price for that model, Artificial Analysis's `borrowed` list does,
16
+ * if it has the model; otherwise the prices are unknown.
17
+ */
18
+ export declare function replyOf(messages: unknown, messageID: string, models?: readonly (Pick<ListedModel, 'providerID' | 'id' | 'cost'> & {
19
+ name?: string;
20
+ })[] | null, borrowed?: readonly AaModel[] | null): Reply | null;
21
+ /**
22
+ * The chat's size (what its latest finished answer read and wrote) and each model's latest finished answer, newest first. A finished
23
+ * compaction starts the chat again: nothing is held by any model then, and the size counts as nothing until the next answer. The host
24
+ * lists a compacted chat from the compaction's own entry on (2.3.0); the reset here covers a host that still lists what came before.
25
+ */
26
+ export declare function chatFacts(messages: unknown, now: number): ChatFacts;
@@ -0,0 +1,96 @@
1
+ import { aaFor } from './artificial-analysis.js';
2
+ import { formatUsd, parseUsd, pricesAt, usdString } from './costs.js';
3
+ import { hostVariant, modelName } from './relay-store.js';
4
+ const list = (messages) => Array.isArray(messages) ? messages.filter(message => message && typeof message === 'object') : [];
5
+ /** A finished compaction: the host's summary of a long chat. It is a request of its own, and the chat is listed from it on. */
6
+ const isSummary = (message) => message.type === 'compaction' && message.status === 'completed';
7
+ /** What a usage record hangs on: a person's message (or a helper's task), or a finished compaction. */
8
+ const isAnchor = (message) => message.type === 'user' || isSummary(message);
9
+ /** The answers to an anchor: its requests up to the next anchor. A summary's own request comes first. */
10
+ function answersTo(all, anchorID) {
11
+ const at = all.findIndex(message => isAnchor(message) && message.id === anchorID);
12
+ if (at < 0)
13
+ return null;
14
+ const rest = all.slice(at + 1), next = rest.findIndex(isAnchor), anchor = all[at];
15
+ // The host keeps one assistant message for each request to the model (a reply with one tool call gave two, on 2.3.0).
16
+ const answers = (next < 0 ? rest : rest.slice(0, next)).filter(message => message.type === 'assistant');
17
+ return { anchor, answers: isSummary(anchor) ? [{ ...anchor, type: 'assistant' }, ...answers] : answers };
18
+ }
19
+ /** The chat's newest anchors, oldest first: at most `count`, however long the chat. */
20
+ export function newestAnchors(messages, count) {
21
+ return list(messages).flatMap(message => isAnchor(message) && typeof message.id === 'string' && typeof message.time?.created === 'number' && Number.isFinite(message.time.created)
22
+ ? [{ id: message.id, created: message.time.created, summary: isSummary(message) }] : []).slice(-count);
23
+ }
24
+ /** The agent that answered an anchor: its first answer's, or `compaction` for a summary; null with no answer. */
25
+ export function agentOf(messages, anchorID) {
26
+ const found = answersTo(list(messages), anchorID);
27
+ if (!found)
28
+ return null;
29
+ if (isSummary(found.anchor))
30
+ return 'compaction';
31
+ const agent = found.answers[0]?.agent;
32
+ return typeof agent === 'string' && agent ? agent : null;
33
+ }
34
+ const count = (value) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
35
+ /**
36
+ * What one answer read and wrote, or null when it carries no counts (an answer that was stopped). The host's `input` leaves out the tokens
37
+ * read from a cache, and tokens written to a cache were read new, so both of those are "fresh".
38
+ */
39
+ const counts = (message) => message.type === 'assistant' && message.tokens
40
+ ? { fresh: count(message.tokens.input) + count(message.tokens.cache?.write), cached: count(message.tokens.cache?.read), output: count(message.tokens.output) } : null;
41
+ /**
42
+ * What the reply to one message took, or null while it cannot be read: no such message, no answer to it yet, or an answer with no counts.
43
+ * `models` gives the prices of the model that answered. When it lists no price for that model, Artificial Analysis's `borrowed` list does,
44
+ * if it has the model; otherwise the prices are unknown.
45
+ */
46
+ export function replyOf(messages, messageID, models = null, borrowed = null) {
47
+ // A finished compaction's id works too: its own request, then the rest of the reply it cut (2026-11-24 usage records).
48
+ const found = answersTo(list(messages), messageID);
49
+ if (!found)
50
+ return null;
51
+ const { anchor, answers } = found, first = answers[0], read = first && counts(first);
52
+ if (!read)
53
+ return null;
54
+ const asked = anchor.time?.created, word = first.time?.firstToken;
55
+ const { providerID, id, variant } = first.model ?? {}, named = typeof providerID === 'string' && typeof id === 'string';
56
+ const listed = named ? models?.find(model => model.providerID === providerID && model.id === id) : undefined;
57
+ const add = (pick) => answers.reduce((sum, answer) => sum + (answer.tokens ? count(pick(answer.tokens)) : 0), 0);
58
+ const costs = answers.map(answer => usdString(answer.cost));
59
+ // shortcut: the prices for the size of the first request. Later requests of a long reply can cross a price step; the host's own cost below counts each request at its own step.
60
+ const prices = listed ? pricesAt(listed.cost, read.fresh + read.cached) : null, own = prices && listedPrice(prices) ? prices : null;
61
+ const effort = hostVariant(typeof variant === 'string' ? variant : undefined);
62
+ // Only a model the list was read for and shows no price at all borrows one: $0 can mean free, and an unread list says nothing.
63
+ const unlisted = models !== null && (!prices || Object.values(prices).every(price => price === null));
64
+ const lent = unlisted && named && borrowed ? aaFor({ providerID, id, name: listed?.name ?? id, variant: effort }, borrowed)?.prices ?? null : null;
65
+ return {
66
+ requests: answers.length, fresh: read.fresh, cached: read.cached, costUsd: usdString(first.cost), seconds: typeof asked === 'number' && typeof word === 'number' && word >= asked ? Math.round((word - asked) / 100) / 10 : null,
67
+ model: named ? modelName({ providerID, id, variant: effort }) : null,
68
+ total: {
69
+ input: add(tokens => tokens.input), output: add(tokens => tokens.output), reasoning: add(tokens => tokens.reasoning), cacheRead: add(tokens => tokens.cache?.read), cacheWrite: add(tokens => tokens.cache?.write),
70
+ costUsd: costs.every((cost) => cost !== null) ? formatUsd(costs.reduce((sum, cost) => sum + parseUsd(cost), 0n)) : null,
71
+ },
72
+ prices: own ?? lent ?? prices, pricesFrom: own ? 'opencode' : lent ? 'artificial-analysis' : null,
73
+ };
74
+ }
75
+ /** Whether OpenCode lists a price: $0 for both input and output can mean "not listed". */
76
+ const listedPrice = (prices) => [prices.inputPerMillion, prices.outputPerMillion].some(price => price !== null && price !== '0');
77
+ /**
78
+ * The chat's size (what its latest finished answer read and wrote) and each model's latest finished answer, newest first. A finished
79
+ * compaction starts the chat again: nothing is held by any model then, and the size counts as nothing until the next answer. The host
80
+ * lists a compacted chat from the compaction's own entry on (2.3.0); the reset here covers a host that still lists what came before.
81
+ */
82
+ export function chatFacts(messages, now) {
83
+ let answered = [];
84
+ for (const message of list(messages)) {
85
+ if (message.type === 'compaction' && message.status === 'completed') {
86
+ answered = [];
87
+ continue;
88
+ }
89
+ const read = counts(message), { created, completed: done } = message.time ?? {}, { providerID, id } = message.model ?? {};
90
+ if (!read || typeof done !== 'number' || typeof providerID !== 'string' || typeof id !== 'string')
91
+ continue;
92
+ // The age runs from the start of the request, as Anthropic counts a cache's lifetime: the time an answer takes counts against it.
93
+ answered = [{ providerID, id, tokens: read.fresh + read.cached + read.output, agoMs: Math.max(0, now - (typeof created === 'number' ? created : done)) }, ...answered.filter(other => other.providerID !== providerID || other.id !== id)];
94
+ }
95
+ return { tokens: answered[0]?.tokens ?? 0, answered };
96
+ }