relay-opencode 0.1.0 → 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.
- package/README.md +82 -115
- package/dist/artificial-analysis.d.ts +50 -0
- package/dist/artificial-analysis.js +153 -0
- package/dist/chat-facts.d.ts +19 -3
- package/dist/chat-facts.js +67 -12
- package/dist/contract.d.ts +1172 -6
- package/dist/contract.js +57 -3
- package/dist/costs.d.ts +7 -0
- package/dist/costs.js +22 -0
- package/dist/decider.d.ts +24 -0
- package/dist/decider.js +104 -14
- package/dist/gui-experimental.cjs +32 -6
- package/dist/gui-styles.d.ts +1 -1
- package/dist/gui-styles.js +29 -3
- package/dist/index.js +9 -3
- package/dist/intelligence.d.ts +4 -0
- package/dist/intelligence.js +10 -0
- package/dist/ranking.d.ts +31 -0
- package/dist/ranking.js +78 -0
- package/dist/relay-auto.d.ts +23 -4
- package/dist/relay-auto.js +53 -11
- package/dist/relay-command.d.ts +0 -5
- package/dist/relay-command.js +15 -13
- package/dist/relay-store.d.ts +64 -4
- package/dist/relay-store.js +94 -9
- package/dist/relay-view.d.ts +37 -1
- package/dist/relay-view.js +68 -8
- package/dist/review-helper.d.ts +1 -1
- package/dist/review-helper.js +26 -7
- package/dist/router.d.ts +30 -5
- package/dist/router.js +54 -10
- package/dist/rpc.d.ts +1168 -6
- package/dist/rpc.js +59 -16
- package/dist/standings.d.ts +18 -0
- package/dist/standings.js +34 -0
- package/dist/tui.d.ts +3 -0
- package/dist/tui.js +26 -0
- package/dist/usage-log.d.ts +135 -0
- package/dist/usage-log.js +210 -0
- package/dist/usage-view.d.ts +70 -0
- package/dist/usage-view.js +104 -0
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -1,155 +1,122 @@
|
|
|
1
1
|
# Relay
|
|
2
2
|
|
|
3
|
-
**Relay picks the
|
|
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
4
|
|
|
5
|
-
>
|
|
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>
|
|
6
11
|
|
|
7
|
-
The
|
|
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).
|
|
8
15
|
|
|
9
16
|
## Why use it
|
|
10
17
|
|
|
11
|
-
- **The right model
|
|
12
|
-
- **Your own words decide.**
|
|
13
|
-
- **
|
|
14
|
-
- **
|
|
15
|
-
- **Your message is safe.** It is sent once and unchanged. If
|
|
16
|
-
- **Measured, not promised.** On 30 labelled example messages, the decision model picked the right kind of work 30 times out of 30, and the expected model 29 times (the labels were written by the author). No cost saving has been measured yet; [When Relay saves money](#when-relay-saves-money) says what to expect.
|
|
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.
|
|
17
23
|
|
|
18
24
|
## Install
|
|
19
25
|
|
|
20
|
-
You need OpenCode 2.3
|
|
21
|
-
|
|
22
|
-
1. Get Relay and build it:
|
|
26
|
+
You need OpenCode 2.3 or newer: OpenCode Desktop or the terminal app.
|
|
23
27
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
npm ci
|
|
28
|
-
npm run build
|
|
29
|
-
```
|
|
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`
|
|
30
31
|
|
|
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.
|
|
32
34
|
|
|
33
35
|
```json
|
|
34
36
|
{
|
|
35
|
-
"plugins": ["
|
|
37
|
+
"plugins": ["relay-opencode@0.2.0"]
|
|
36
38
|
}
|
|
37
39
|
```
|
|
38
40
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
3. Restart OpenCode. (Desktop usually picks up a change to this file by itself within a minute.)
|
|
42
|
-
4. Check: type `/` in a chat. `/relay` should be in the list.
|
|
43
|
-
|
|
44
|
-
To update later: `git pull`, `npm ci`, `npm run build`, then restart OpenCode.
|
|
45
|
-
|
|
46
|
-
## Set up (once, in OpenCode Desktop)
|
|
47
|
-
|
|
48
|
-
1. Open a chat, open the command palette (Ctrl+K) and run **Open Relay**. The Relay panel opens beside the chat.
|
|
49
|
-
2. Add models to **Plan**, **Execute** and **Review**: press **+ Add a model** under a mode. A table lists the models OpenCode offers you, with the price per million tokens (input / output), the context size and the intelligence index. Type in the search box to find one by its name or its provider, narrow the table to one provider, or sort it by price (cheapest first), by context (largest first) or by index (highest first). Press **Add** on a row. Each chosen model has a menu for its effort (low, high and so on) when the model offers them. The prices come from OpenCode's own model catalog, which OpenCode fills from [models.dev](https://models.dev); Relay asks nothing of its own. "not listed" means OpenCode has no price for that model (on 17 Nov 2026 every model of the `claude-agent` provider), and "$0 or not listed" means the catalog says 0, which can be either. The index is the Artificial Analysis Intelligence Index, taken from OpenRouter's public model list. For a model with efforts, it is the score at its highest effort, and a lower effort scores less (GPT-6.2 Sol: 57 at max, 41 at low). The price per token is the same at every effort, but a higher effort writes more tokens, so each reply costs more. "—" means Relay could not match the model. Hover over a number to see which model it came from. See [data sources](docs/data-sources.md). When a mode has more than one model, write a short "use it for" line for each, for example "hard design and architecture" or "small, quick edits".
|
|
50
|
-
3. Choose a **decider**: press **+ Choose a decider** and **Use** on a row. The table lists only the decision models OpenCode offers you; `opencode/jev-1.13-free` is free. **Change the decider** opens it again, and × removes the decider. Until you choose one, the panel and the pill warn you: without a decider, Relay switches nothing.
|
|
51
|
-
4. Type a sample message in the test box and press **Try** to see what Relay would pick.
|
|
52
|
-
|
|
53
|
-
**Recent choices** at the bottom of the panel lists the last 20 decisions, for chats and helpers, and updates by itself. Once the chat has answered a message, its row also says what the first request of the reply took: the tokens read new, the tokens read from a cache, the cost OpenCode worked out (when the model has a listed price), the seconds until the first word, and how many requests the whole reply made. A switch to another model shows up there as a large "read new" number.
|
|
54
|
-
|
|
55
|
-
The settings are shared by all your projects. The terminal app has no settings screen, so set them up in Desktop.
|
|
56
|
-
|
|
57
|
-
**If Open Relay is missing:** it shows only while a chat is open. Then check Settings → Extensions → Plugins: `relay-opencode` should be listed with **Reload** and a switch. If that list stays empty, or Desktop says it can't reach your computer, OpenCode's background service is not running properly and Desktop shows no plugin panels. Quit Desktop, end `opencode-cli.exe` (the one started with `serve --service`) in Task Manager, and start Desktop again.
|
|
58
|
-
|
|
59
|
-
## Use
|
|
60
|
-
|
|
61
|
-
| You type | What happens |
|
|
62
|
-
|---|---|
|
|
63
|
-
| `/relay <message>` | Relay picks the mode and the model for this one message, switches the chat, and sends it. |
|
|
64
|
-
| `/relay on` | Every message you send in this chat goes through Relay, without typing `/relay`. |
|
|
65
|
-
| `/relay off` | This chat goes back to normal. |
|
|
66
|
-
|
|
67
|
-
- In Desktop, the **Relay pill** above the chat box shows whether Relay is on for that chat. Click it to turn Relay on or off there, and to see the last choice. With no decider chosen it reads **Relay on · no decider**, and its menu opens the Relay panel.
|
|
68
|
-
- OpenCode shows a "Switched to …" line in the chat when Relay changes the model, and Desktop's model picker follows Relay's choice.
|
|
69
|
-
- Plan and Review use OpenCode's `plan` agent, which is meant for reading and planning, not editing. Only Execute uses `build`, which can change files.
|
|
70
|
-
- When the decision model is not sure (under 60%), `/relay` uses Plan. With `/relay on`, the chat stays as it is.
|
|
71
|
-
- In a long chat, a move to a cheaper model of the same mode is made only when it pays, and a model the chat no longer fits is not used. See [When Relay saves money](#when-relay-saves-money).
|
|
72
|
-
- In the terminal app, `/relay`, `/relay on` and `/relay off` work the same way. There is no pill there, and `/relay on` prints nothing.
|
|
73
|
-
|
|
74
|
-
## When Relay saves money
|
|
75
|
-
|
|
76
|
-
No saving has been measured yet. This section is arithmetic on list prices, plus what one check on an isolated OpenCode with mock models showed. The working is in `docs/research/2026-11-17-relay-cost-and-model-choice.md`.
|
|
77
|
-
|
|
78
|
-
**A switch to another model has a price.** A provider keeps a cache of the chat for each model. A model that has not seen the chat reads all of it at full price on its first request, and the model you left loses its cache after a few minutes (five with Anthropic, unless a longer time is set). A change of mode on the same model has no such price. In the check, a move between Plan and Execute, the review rules and another effort all left the start of the request as it was; only a change of model did not (18 Nov 2026, OpenCode 2.3.0 with a mock model, so what was seen is the request, not a real cache).
|
|
79
|
-
|
|
80
|
-
So Relay saves when there is little to read again, or when the other model is far cheaper:
|
|
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.
|
|
81
43
|
|
|
82
|
-
|
|
83
|
-
- a provider that has no cache;
|
|
84
|
-
- a model about seven times cheaper or more. On paper that pays within one to four requests.
|
|
44
|
+
Other ways to install, from source or as a fixed copy, are in the [guide](docs/guide.md#install-from-source).
|
|
85
45
|
|
|
86
|
-
|
|
46
|
+
## Install with an AI agent
|
|
87
47
|
|
|
88
|
-
|
|
48
|
+
Give your coding agent (OpenCode, Claude Code, Cursor or another) this repository's link and this request:
|
|
89
49
|
|
|
90
|
-
|
|
91
|
-
- **The whole chat must fit.** A chat is moved to a model only when the chat so far, with the attached files, fits that model with the room OpenCode keeps free before it compacts a chat.
|
|
92
|
-
- **Recent choices shows what each reply took**, so you can see what a switch cost.
|
|
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.
|
|
93
51
|
|
|
94
|
-
|
|
52
|
+
### Instructions for AI agents
|
|
95
53
|
|
|
96
|
-
|
|
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.
|
|
97
55
|
|
|
98
|
-
|
|
99
|
-
-
|
|
100
|
-
-
|
|
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.
|
|
101
79
|
|
|
102
|
-
|
|
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.
|
|
103
81
|
|
|
104
|
-
|
|
82
|
+
## Update
|
|
105
83
|
|
|
106
|
-
|
|
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).
|
|
107
86
|
|
|
108
|
-
|
|
87
|
+
Your settings are kept across updates.
|
|
109
88
|
|
|
110
|
-
|
|
89
|
+
## Set up (once, in Desktop)
|
|
111
90
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
- **Ran in a full OpenCode Desktop setup (Windows, Ollama Cloud models, 16 Nov 2026):** the Modes tab and its Try box; `/relay` placing messages on the Plan, Execute and Review models; the pill and `/relay on` turning the switch on and off; plain messages with the switch on (placed) and off (left alone); a helper that checks work starting on the Review model. This check found and fixed one bug: after a Plan answer, a clear "fix …" request was judged unsure and stayed on Plan.
|
|
117
|
-
- **Ran in a full OpenCode Desktop setup with Claude models (Windows, 17 Nov 2026):** six plain messages with Relay on, each answered by its mode's model (Sonnet for Plan and Review, Haiku or Sonnet for Execute by their "use it for" lines); a review cycle that found a planted bug on the first check and approved the fix on the second; `/relay` with an @-mentioned file and an @-mentioned picture; a pasted picture with Relay on; a busy chat; and the panel's prices, Cheapest first, Recent choices and warning. It found and fixed two problems with Desktop: its model picker did not follow Relay's switches, and pasted pictures were not counted.
|
|
118
|
-
- **The install steps above, followed from a fresh clone of this repository in a throwaway OpenCode profile (Windows, 17 Nov 2026):** OpenCode loaded Relay and `/relay on` worked in a new chat.
|
|
119
|
-
- **Not yet run in a full setup:** the interactive terminal app, and Relay with a real decision model on macOS and Linux.
|
|
120
|
-
- **The model table (17 Nov 2026), in a plain browser page that runs the panel's real code with a fake OpenCode:** search, the provider filter, the three orders, Add, adding a model again with another effort, and the effort menu all did what they should. Not yet seen in Desktop itself.
|
|
121
|
-
- **The decider's table, and checks from helpers that name a model (17 Nov 2026):** the decider is picked from the same kind of table, checked in the same plain page. A helper whose task is a check now goes to the Review model even when the calling model names another; tests cover it, and it has not run in a live chat yet.
|
|
122
|
-
- **The intelligence index (18 Nov 2026):** a real OpenCode 2.3.0 with no login fetched OpenRouter's list through Relay, matched 4 of its 11 free models, and used its stored copy on the next call. The tables were checked in the plain page. Not yet seen in Desktop.
|
|
123
|
-
- **What a reply took, the whole chat's fit, and stay or go (18 Nov 2026):** ran on a real OpenCode 2.3.0, isolated, with mock models and a mock decision model, on Windows. `/relay` switched the agent and the model. Each record got what its reply took once the chat had answered, also for a plain message with Relay on and for a reply of two requests. A model the chat no longer fitted was not offered. A step down that did not pay left the chat on its model, with the reason in the record. Every amount was what the mock reported, so no real cost and no real cache has been seen. Not yet run: real models, the paid stages of the cost test, the new line in Desktop's panel, and macOS and Linux.
|
|
124
|
-
- **Renamed on 17 Nov 2026:** the package, the plugin id and the GitHub repository are now `relay-opencode` (they were `feature-pilot` and `orchestrator-plugin`; the old repository address forwards to the new one). The renamed package passed the isolated real-host check on Windows.
|
|
125
|
-
- **Removed on 17 Nov 2026:** the older feature pipeline in the side panel (the Run, Spend and More tabs). Anything it saved is left in place and ignored.
|
|
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.
|
|
126
95
|
|
|
127
|
-
|
|
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.
|
|
128
97
|
|
|
129
|
-
|
|
98
|
+
## Use
|
|
130
99
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
- Desktop sends its own agent with every message, and a plugin cannot change it. So the message after a one-off `/relay` to Plan or Review runs on Build, with the model Relay picked. With `/relay on`, every message is placed again.
|
|
139
|
-
- A helper that continues an earlier helper keeps that helper's model.
|
|
140
|
-
- Plan and Review rely on OpenCode's `plan` agent not editing. Another plugin can change that: in the live check, with the Plannotator plugin installed, a Plan turn submitted a plan and then edited a file.
|
|
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. |
|
|
141
107
|
|
|
142
|
-
|
|
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.
|
|
143
111
|
|
|
144
|
-
|
|
112
|
+
## Learn more
|
|
145
113
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
```
|
|
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)
|
|
153
120
|
|
|
154
121
|
## License
|
|
155
122
|
|
|
@@ -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
|
+
}
|
package/dist/chat-facts.d.ts
CHANGED
|
@@ -1,7 +1,23 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type AaModel } from './artificial-analysis.js';
|
|
2
|
+
import type { ListedModel } from './inventory.js';
|
|
3
|
+
import { type Reply } from './relay-store.js';
|
|
2
4
|
import type { ChatFacts } from './router.js';
|
|
3
|
-
/**
|
|
4
|
-
export declare function
|
|
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;
|
|
5
21
|
/**
|
|
6
22
|
* The chat's size (what its latest finished answer read and wrote) and each model's latest finished answer, newest first. A finished
|
|
7
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
|
package/dist/chat-facts.js
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { aaFor } from './artificial-analysis.js';
|
|
2
|
+
import { formatUsd, parseUsd, pricesAt, usdString } from './costs.js';
|
|
3
|
+
import { hostVariant, modelName } from './relay-store.js';
|
|
2
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
|
+
}
|
|
3
34
|
const count = (value) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
|
|
4
35
|
/**
|
|
5
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
|
|
@@ -7,19 +38,42 @@ const count = (value) => typeof value === 'number' && Number.isFinite(value) &&
|
|
|
7
38
|
*/
|
|
8
39
|
const counts = (message) => message.type === 'assistant' && message.tokens
|
|
9
40
|
? { fresh: count(message.tokens.input) + count(message.tokens.cache?.write), cached: count(message.tokens.cache?.read), output: count(message.tokens.output) } : null;
|
|
10
|
-
/**
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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)
|
|
14
50
|
return null;
|
|
15
|
-
const
|
|
16
|
-
// The host keeps one assistant message for each request to the model (a reply with one tool call gave two, on 2.3.0).
|
|
17
|
-
const answers = (next < 0 ? rest : rest.slice(0, next)).filter(message => message.type === 'assistant'), first = answers[0], read = first && counts(first);
|
|
51
|
+
const { anchor, answers } = found, first = answers[0], read = first && counts(first);
|
|
18
52
|
if (!read)
|
|
19
53
|
return null;
|
|
20
|
-
const asked =
|
|
21
|
-
|
|
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
|
+
};
|
|
22
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');
|
|
23
77
|
/**
|
|
24
78
|
* The chat's size (what its latest finished answer read and wrote) and each model's latest finished answer, newest first. A finished
|
|
25
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
|
|
@@ -32,10 +86,11 @@ export function chatFacts(messages, now) {
|
|
|
32
86
|
answered = [];
|
|
33
87
|
continue;
|
|
34
88
|
}
|
|
35
|
-
const read = counts(message), done = message.time
|
|
89
|
+
const read = counts(message), { created, completed: done } = message.time ?? {}, { providerID, id } = message.model ?? {};
|
|
36
90
|
if (!read || typeof done !== 'number' || typeof providerID !== 'string' || typeof id !== 'string')
|
|
37
91
|
continue;
|
|
38
|
-
|
|
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)];
|
|
39
94
|
}
|
|
40
95
|
return { tokens: answered[0]?.tokens ?? 0, answered };
|
|
41
96
|
}
|