pi-provimux 105.0.3 → 105.0.5
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/CHANGELOG.md +53 -0
- package/README.md +100 -19
- package/extensions/answered-footer.ts +133 -0
- package/extensions/index.ts +24 -12
- package/extensions/lib.ts +45 -3
- package/extensions/sources.ts +11 -0
- package/extensions/upstreams.ts +110 -23
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,58 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 105.0.5
|
|
4
|
+
|
|
5
|
+
Two changes: Provimux's models now go by the provider id `provimux`, and the footer names the route that answered.
|
|
6
|
+
|
|
7
|
+
- **The provider id is `provimux`** (was `cliproxyapi`). pi's `/model` shows `[provimux]`, and the models are
|
|
8
|
+
`provimux/<id>`. One provider is registered, under that id. The old id is not registered next to it, sessions are
|
|
9
|
+
not moved, and its `auth.json` entry is not read.
|
|
10
|
+
- **A setup made by an earlier `/login` keeps working from `cliproxyapi.json`.** That `/login` wrote
|
|
11
|
+
`"providerId": "cliproxyapi"` without anyone choosing it, so the value now reads as the default, `provimux`, as
|
|
12
|
+
`"providerName": "CLIProxyAPI"` already does. The file's `apiKey` and `baseUrl` are used as before, with no new
|
|
13
|
+
`/login`. Any other id in the file is kept. So is any value of `CLIPROXYAPI_PROVIDER_ID`, `cliproxyapi`
|
|
14
|
+
included.
|
|
15
|
+
- **What an existing setup must do:**
|
|
16
|
+
- pick the models again as `provimux/<id>`. In `settings.json`, `"defaultProvider": "cliproxyapi"` silently starts
|
|
17
|
+
pi on another model: set `"defaultProvider": "provimux"` with `"defaultModel": "<id>"`, or highlight the model in
|
|
18
|
+
`/model` and press Ctrl+S (Enter only switches the live model). An `enabledModels` entry `"cliproxyapi/<id>"`
|
|
19
|
+
matches nothing: change it to `"provimux/<id>"` by hand. `--model cliproxyapi/<id>` must become
|
|
20
|
+
`--model provimux/<id>` or `--provider provimux --model <id>`;
|
|
21
|
+
- rename a `providers.cliproxyapi` block in `models.json` (headers, `modelOverrides` such as thinking levels,
|
|
22
|
+
windows, prices) to `providers.provimux`; under the old name it applies to nothing. pi-cache-keeper moves its
|
|
23
|
+
own values there by itself at its next start and leaves only fields you set by hand under the old id;
|
|
24
|
+
- log in with the account login, not the API-key login (see below). A setup whose key is only in `auth.json`
|
|
25
|
+
under `cliproxyapi` (no `apiKey` in `cliproxyapi.json`, no `CLIPROXYAPI_API_KEY`) needs one `/login provimux`;
|
|
26
|
+
- an old session recorded on `cliproxyapi/<id>` does not get its model back when resumed. pi warns
|
|
27
|
+
`Could not restore model cliproxyapi/<id>. Using …` and goes on with the model it would start with. Pick
|
|
28
|
+
`provimux/<id>` with `/model`;
|
|
29
|
+
- `CLIPROXYAPI_PROVIDER_ID=cliproxyapi` keeps the old id for anyone who wants it, with its stored login.
|
|
30
|
+
- **Logins work as in 105.0.4.** Use `/login provimux` with **Sign in with an account**, or `apiKey` and
|
|
31
|
+
`baseUrl` in `cliproxyapi.json`. pi's **Sign in with an API key**, offered when the file or
|
|
32
|
+
`CLIPROXYAPI_API_KEY` already holds a key, still does not survive a restart (`Provider is not configured`), as in
|
|
33
|
+
105.0.4. A key in `cliproxyapi.json` (or `CLIPROXYAPI_API_KEY`) wins over a key saved by a later `/login` that
|
|
34
|
+
does not rewrite the file; the account login rewrites it.
|
|
35
|
+
- **The footer says which route answered.** After each answer on a Provimux model, the footer shows `answered:
|
|
36
|
+
Anthropic sub`, `answered: Devin sub`, `answered: Anthropic api`, `answered: OpenRouter api` …, in the words of the
|
|
37
|
+
model names. It only ever shows the route that produced the answer you see: it is read from the answer's
|
|
38
|
+
`X-CPA-AUTH-*` headers (on the Codex WebSocket, the `cpa_auth_*` fields of its `response.created`), from the attempt
|
|
39
|
+
that answered when pi tried again (an attempt that names nobody is unnamed), and only a turn that completed with
|
|
40
|
+
something in it changes it (a failed, aborted or empty one leaves it as it was). It needs no other extension; the
|
|
41
|
+
credential list and its priorities play no part, so any install's routes, in any order, are named as they answer.
|
|
42
|
+
Only the session's own turns count: pi's cache warmer and other extensions' requests never change it. An answer a
|
|
43
|
+
proxy that lists its credentials would not name shows `answered: unknown`, from the first turn on (a failed lookup
|
|
44
|
+
of that list changes nothing); plain CLIProxyAPI shows nothing, and so does a model of another provider. On by
|
|
45
|
+
default; `"answered": false` in `cliproxyapi.json` turns it off.
|
|
46
|
+
- **Unchanged:** the files `cliproxyapi.json` and `cliproxyapi-models.json`, the `CLIPROXYAPI_*` environment
|
|
47
|
+
variables, the internal API name `cliproxyapi-codex-responses`, and `/provimux-refresh`.
|
|
48
|
+
|
|
49
|
+
## 105.0.4
|
|
50
|
+
|
|
51
|
+
- **`/cliproxyapi-refresh` is gone.** Only `/provimux-refresh` reloads the model list; pi no longer shows two
|
|
52
|
+
refresh commands. Everything else of 105.0.3 stays: the provider id `cliproxyapi`, the `CLIPROXYAPI_*`
|
|
53
|
+
environment variables, `cliproxyapi.json` and `cliproxyapi-models.json`, `/login cliproxyapi` (and
|
|
54
|
+
`/login CLIProxyAPI`, the same id), and a stored `"providerName": "CLIProxyAPI"` read as Provimux.
|
|
55
|
+
|
|
3
56
|
## 105.0.3
|
|
4
57
|
|
|
5
58
|
The command and the login now say Provimux. The old names keep working.
|
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
**Provimux's extension for [pi](https://pi.dev).** It adds [Provimux](https://github.com/ngvoicu/provimux) as a
|
|
4
4
|
provider in pi, and works the same with plain [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI).
|
|
5
5
|
|
|
6
|
-
Every model your Provimux or CLIProxyAPI serves appears in pi's `/model`, under the provider `
|
|
6
|
+
Every model your Provimux or CLIProxyAPI serves appears in pi's `/model`, under the provider `provimux`. With
|
|
7
7
|
Provimux, each model's name also says which accounts serve it (a subscription login or an API key, and whose), and
|
|
8
8
|
other pi extensions learn which one answered. With CLIProxyAPI, those parts stay quiet and everything else works.
|
|
9
9
|
|
|
@@ -79,18 +79,19 @@ It needs pi 0.99.0 or newer: the Codex WebSocket reports which kind of account a
|
|
|
79
79
|
|
|
80
80
|
### Coming from pi-cliproxyapi-provider
|
|
81
81
|
|
|
82
|
-
pi-provimux keeps
|
|
83
|
-
|
|
84
|
-
`cliproxyapi-models.json`. Two names changed, and the old ones still work:
|
|
82
|
+
pi-provimux keeps the `CLIPROXYAPI_*` environment variables and the files `cliproxyapi.json` and
|
|
83
|
+
`cliproxyapi-models.json`. Three names changed:
|
|
85
84
|
|
|
86
85
|
| Was | Now | The old one |
|
|
87
86
|
| --- | --- | --- |
|
|
88
|
-
|
|
|
89
|
-
|
|
|
87
|
+
| The provider id `cliproxyapi` | `provimux` (since 105.0.5) | Not registered any more. See [The provider id `provimux`](#the-provider-id-provimux-since-10505). |
|
|
88
|
+
| `/cliproxyapi-refresh` | `/provimux-refresh` | Gone since 105.0.4: use `/provimux-refresh`. |
|
|
89
|
+
| The login shown as **CLIProxyAPI** | **Provimux** | `/login provimux` or `/login Provimux`. |
|
|
90
90
|
|
|
91
|
-
A `cliproxyapi.json` written by an earlier `/login` holds `"providerName": "CLIProxyAPI"
|
|
92
|
-
|
|
93
|
-
|
|
91
|
+
A `cliproxyapi.json` written by an earlier `/login` holds `"providerName": "CLIProxyAPI"` and
|
|
92
|
+
`"providerId": "cliproxyapi"`. Nobody chose those values, so both are read as the defaults: the login shows as
|
|
93
|
+
Provimux, and the models are listed under `provimux`. A name or an id you set yourself, in the file or through
|
|
94
|
+
`CLIPROXYAPI_PROVIDER_NAME` / `CLIPROXYAPI_PROVIDER_ID`, is kept.
|
|
94
95
|
|
|
95
96
|
Remove the old package first, so that only one of them registers the provider:
|
|
96
97
|
|
|
@@ -99,9 +100,56 @@ pi remove npm:@router-for-me/pi-cliproxyapi-provider # or the source you insta
|
|
|
99
100
|
pi install npm:pi-provimux
|
|
100
101
|
```
|
|
101
102
|
|
|
103
|
+
### The provider id `provimux` (since 105.0.5)
|
|
104
|
+
|
|
105
|
+
pi shows a model as `<provider id>/<model id>`. Up to 105.0.4 that was `cliproxyapi/<model>`; from 105.0.5 it is
|
|
106
|
+
`provimux/<model>`. Only the id changes: the files, the environment variables and your saved settings stay. Nothing
|
|
107
|
+
migrates, and the old id is not kept as a second provider. What that means for a setup made before 105.0.5:
|
|
108
|
+
|
|
109
|
+
- **The models now show as `provimux/<id>`** in `/model`, `--list-models` and pi's RPC model list.
|
|
110
|
+
- **Your connection keeps working when it is in `cliproxyapi.json`.** An earlier `/login` wrote
|
|
111
|
+
`"providerId": "cliproxyapi"`, `apiKey` and `baseUrl` there. That id is read as the default, `provimux`, and the
|
|
112
|
+
key and address are used as before. You do not need a new `/login`.
|
|
113
|
+
- **A key that is only in pi's `auth.json`, under `cliproxyapi`, is not read.** No `apiKey` in `cliproxyapi.json`
|
|
114
|
+
and no `CLIPROXYAPI_API_KEY`: run `/login provimux` once. pi then stores the login under `provimux`. You can
|
|
115
|
+
delete the old `cliproxyapi` entry from `auth.json`.
|
|
116
|
+
- **Settings that name the old id match nothing.** In `~/.pi/agent/settings.json`:
|
|
117
|
+
- `"defaultProvider": "cliproxyapi"`: pi starts on another model, with no warning. Set `"defaultProvider":
|
|
118
|
+
"provimux"` and keep `"defaultModel": "<id>"` (the id alone, not `provimux/<id>`). Or, in `/model`, highlight
|
|
119
|
+
the model and press **Ctrl+S**: that saves it as the default. **Enter** only switches the model you are using
|
|
120
|
+
now, and the next start goes back to the saved default.
|
|
121
|
+
- an `enabledModels` entry `"cliproxyapi/<id>"`: pi prints `No models match pattern "cliproxyapi/<id>"`. Change
|
|
122
|
+
it to `"provimux/<id>"` by hand; Ctrl+S does not touch this list.
|
|
123
|
+
- **A session recorded on `cliproxyapi/<id>` does not get its model back** when you resume it. pi says
|
|
124
|
+
`Could not restore model cliproxyapi/<id>. Using <provider>/<model>` and goes on with the model it would start
|
|
125
|
+
with. That can be another Provimux model, or another provider's model if you have logged in to one. Pick
|
|
126
|
+
`provimux/<id>` with `/model` (Enter) before you send anything. pi 1.6.0 and newer also print that warning in
|
|
127
|
+
`-p`, JSON and RPC mode; older pi shows it only in the TUI.
|
|
128
|
+
- **`--model cliproxyapi/<id>` is not found.** Write `--model provimux/<id>`, or `--provider provimux --model <id>`
|
|
129
|
+
(`--provider` alone is refused: pi needs `--model` with it).
|
|
130
|
+
- **`models.json` settings under `providers.cliproxyapi` apply to nothing.** pi keys them by provider id. Rename
|
|
131
|
+
the block in `~/.pi/agent/models.json` to `providers.provimux`. Left under the old id, everything in it is lost
|
|
132
|
+
for the `provimux` models: extra `headers` (a request that needs one then fails, for example with HTTP 401),
|
|
133
|
+
`modelOverrides` such as a `thinkingLevelMap` that adds a level (pi then offers and sends only the catalog's
|
|
134
|
+
levels), a `contextWindow`, `maxTokens` or prices.
|
|
135
|
+
- **pi-cache-keeper's values move by themselves.** pi-cache-keeper writes its `modelOverrides` (input window,
|
|
136
|
+
output limit, cache lifetimes, prices) under the provider id of each model pi lists. At its first start next to
|
|
137
|
+
105.0.5 it writes them under `providers.provimux`, and it takes its own values out of `providers.cliproxyapi`
|
|
138
|
+
(the models are gone). A field you set yourself is never touched, so it stays under `cliproxyapi`: move it by
|
|
139
|
+
hand. A block that ends up empty is removed.
|
|
140
|
+
- **To keep the old id**, set `CLIPROXYAPI_PROVIDER_ID=cliproxyapi` in the environment pi runs in. The models are
|
|
141
|
+
then listed under `cliproxyapi` as before, and the login stored under `cliproxyapi` in `auth.json` is used again.
|
|
142
|
+
Set in the environment, it is your choice and is kept. In `cliproxyapi.json`, `"providerId": "cliproxyapi"` means
|
|
143
|
+
the default, because that is what the old `/login` wrote; any other id there is kept. So keep the variable set:
|
|
144
|
+
`/login` writes the id it used into `cliproxyapi.json`, and there `cliproxyapi` reads as `provimux`.
|
|
145
|
+
|
|
102
146
|
## Login-style setup (recommended)
|
|
103
147
|
|
|
104
|
-
This plugin needs both **baseUrl** and **apiKey**. pi's built-in `/login` only supports multi-field prompts on the account/OAuth path, so Provimux appears under **Sign in with an account
|
|
148
|
+
This plugin needs both **baseUrl** and **apiKey**. pi's built-in `/login` only supports multi-field prompts on the account/OAuth path, so Provimux appears under **Sign in with an account**.
|
|
149
|
+
|
|
150
|
+
When `cliproxyapi.json` or `CLIPROXYAPI_API_KEY` already holds a key and no account login is stored, pi also offers **Sign in with an API key**. Do not use it: it stores only the key, in `auth.json`, and it does not survive a restart. The next start says `Provider is not configured: provimux`, and a saved default or a resumed session moves to another provider if you have one (105.0.4 does the same under `cliproxyapi`). Use **Sign in with an account**, or put `apiKey` and `baseUrl` in `cliproxyapi.json`. If you already used it, remove the `provimux` entry from `auth.json` (`/logout`) and log in with an account.
|
|
151
|
+
|
|
152
|
+
**Which key wins.** The extension reads the address and the key from the `CLIPROXYAPI_*` variables first, then `cliproxyapi.json`, then the login in `auth.json` (see [Resolution order](#environment-overrides)). So a key in `cliproxyapi.json` wins over a key saved by a later `/login` that does not rewrite the file, as the API-key login does not. The account login writes its address and key into `cliproxyapi.json` as well, so after it the two agree. Change the key or the proxy with an account `/login`. If you change them in `cliproxyapi.json` or the environment while an account login is stored, the model list follows the new values but requests still carry the stored login's key: run `/login` again, or remove the `provimux` entry from `auth.json`.
|
|
105
153
|
|
|
106
154
|
### Preferred: /login shortcuts
|
|
107
155
|
|
|
@@ -112,10 +160,10 @@ This plugin needs both **baseUrl** and **apiKey**. pi's built-in `/login` only s
|
|
|
112
160
|
or, by the provider id:
|
|
113
161
|
|
|
114
162
|
```text
|
|
115
|
-
/login
|
|
163
|
+
/login provimux
|
|
116
164
|
```
|
|
117
165
|
|
|
118
|
-
(
|
|
166
|
+
(pi ignores case, so both name the same provider.) These shortcuts jump straight into the multi-field baseUrl + API key prompts, unless pi also offers the API-key method (above): then it asks which one first, and you choose **Sign in with an account**.
|
|
119
167
|
|
|
120
168
|
### Menu path
|
|
121
169
|
|
|
@@ -143,7 +191,7 @@ On success:
|
|
|
143
191
|
- `baseUrl` / `apiKey` are written to `~/.pi/agent/cliproxyapi.json`
|
|
144
192
|
- pi also stores the returned credential in `~/.pi/agent/auth.json`
|
|
145
193
|
|
|
146
|
-
Re-run `/login Provimux` or `/login
|
|
194
|
+
Re-run `/login Provimux` or `/login provimux` anytime to reconfigure. The built-in `/logout` command only removes credentials saved in `auth.json`; it does not erase `cliproxyapi.json`. Remove or update that file if you also need to clear the provider configuration.
|
|
147
195
|
|
|
148
196
|
## Non-interactive configuration
|
|
149
197
|
|
|
@@ -168,11 +216,12 @@ Optional fields:
|
|
|
168
216
|
| ------- | --------- | ------------- |
|
|
169
217
|
| `baseUrl` | `http://127.0.0.1:8317` | Provimux or CLIProxyAPI address |
|
|
170
218
|
| `apiKey` | _(required unless set via /login or env)_ | Bearer token / CPA API key |
|
|
171
|
-
| `providerId` | `
|
|
219
|
+
| `providerId` | `provimux` | Provider id shown in `/model` (`cliproxyapi`, the default before 105.0.5, written here by `/login`, reads as the default) |
|
|
172
220
|
| `providerName` | `Provimux` | Display name in `/login` and UI (`CLIProxyAPI`, the default before 105.0.3, written here by `/login`, reads as the default) |
|
|
173
221
|
| `fast` | `false` | Persisted speed preference: `false` (off), `true` (Fast), or `"ultrafast"` (Ultra Fast) |
|
|
174
222
|
| `pause` | `false` | Persisted request-pause preference; provider requests wait until it is cleared |
|
|
175
223
|
| `tps` | `true` | Show the elapsed time footer and TPS summary in the TUI; see [Elapsed time and TPS](#elapsed-time-and-tps-tui) |
|
|
224
|
+
| `answered` | `true` | Show in the footer which route answered the last turn; see [Which route answered, in the footer](#which-route-answered-in-the-footer) |
|
|
176
225
|
| `claudeMessages` | `"auto"` | When Claude models use Claude's own format: `"auto"`, `true` (always) or `false` (never); see [Claude Messages format](#claude-messages-format) |
|
|
177
226
|
|
|
178
227
|
### Environment overrides
|
|
@@ -264,8 +313,8 @@ Use `/provimux-refresh` to force an immediate remote refresh of the model catalo
|
|
|
264
313
|
|
|
265
314
|
### Refresh commands
|
|
266
315
|
|
|
267
|
-
- `/provimux-refresh`
|
|
268
|
-
- `/login Provimux` / `/login
|
|
316
|
+
- `/provimux-refresh` — force an immediate remote refresh of the model catalog, rewrite the cache, and update registered models. Use this after adding or removing models on the proxy without restarting pi.
|
|
317
|
+
- `/login Provimux` / `/login provimux` — re-entering credentials always forces a fresh models query and rewrites the cache.
|
|
269
318
|
|
|
270
319
|
Delete `~/.pi/agent/cliproxyapi-models.json` to clear the cache manually.
|
|
271
320
|
|
|
@@ -283,7 +332,7 @@ From CPA catalog entry → pi model:
|
|
|
283
332
|
| `supports_reasoning_effort_updates` | `compat.supportsMidConvoEffort` |
|
|
284
333
|
| `visibility: "hide"` | skipped |
|
|
285
334
|
|
|
286
|
-
Unsupported pi thinking levels are set to `null` so they are hidden in the UI. A level the model lacks asked on the command line of a one-shot run (`pi -p --thinking low`, `--model
|
|
335
|
+
Unsupported pi thinking levels are set to `null` so they are hidden in the UI. A level the model lacks asked on the command line of a one-shot run (`pi -p --thinking low`, `--model provimux/<model>:low`, or `--models provimux/<model>:low` when that pattern selects the model; also `--mode json`) is refused: nothing is sent, the error names the levels the model has, and pi exits with 1. The flags are read as pi reads them: a suffix that is part of a model's id (`--model provimux/local-assistant:high`, for a model listed as `local-assistant:high`) asks for no level. Elsewhere (the level picker, a saved default level, `--thinking` in an interactive or RPC session) pi moves the level to the nearest one the model has, and the request names that level, never the missing one. When available, prices are matched against canonical model entries in `models.dev`; `cost.tiers[].tier.size` becomes pi's `inputTokensAbove`, including thresholds such as `272000`. The legacy `context_over_200k` field is used only when no explicit tiers are present. Ambiguous reseller prices are not selected arbitrarily and fall back to zero. These are catalog/list prices, not a guarantee of CPA's own markup or billing.
|
|
287
336
|
|
|
288
337
|
## GPT Responses prompt caching
|
|
289
338
|
|
|
@@ -353,6 +402,38 @@ pi shows a model's name in `/model` beside its id and searches it, and its model
|
|
|
353
402
|
also match names: `openrouter` now matches every model that comes from OpenRouter, not only ids that contain the
|
|
354
403
|
word.
|
|
355
404
|
|
|
405
|
+
## Which route answered, in the footer
|
|
406
|
+
|
|
407
|
+
Provimux can serve one model name through several routes (subscription logins, API keys, OpenRouter …). After each
|
|
408
|
+
answer on a Provimux model, the footer says which one answered it, in the words of the model names:
|
|
409
|
+
|
|
410
|
+
```
|
|
411
|
+
answered: Anthropic sub
|
|
412
|
+
answered: Devin sub
|
|
413
|
+
answered: Anthropic api
|
|
414
|
+
answered: OpenRouter api
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
It only ever shows the route that produced the answer you see.
|
|
418
|
+
|
|
419
|
+
- It is read from the answer itself: the `X-CPA-AUTH-*` response headers, or on the Codex WebSocket the `cpa_auth_*`
|
|
420
|
+
fields of the turn's `response.created`. No other extension is needed.
|
|
421
|
+
- When pi tries a request again (an HTTP 429, or a Codex WebSocket continuation replayed on a fresh socket), only
|
|
422
|
+
what the attempt that answered said counts: an attempt that names nobody is unnamed, whatever an earlier one said.
|
|
423
|
+
- Only an answer changes it: a turn that completed (or calls tools) with something in it. A failed, aborted or empty
|
|
424
|
+
turn leaves it as it was.
|
|
425
|
+
- Whatever routes an install has and however it orders them, the footer names the one that answered: the credential
|
|
426
|
+
list and its priorities play no part, and a route that is not in the list is named all the same.
|
|
427
|
+
- Only the session's own turns count: pi's cache warmer and other extensions' requests, which can run at the same
|
|
428
|
+
time, never change it.
|
|
429
|
+
- `answered: unknown`: the proxy names answers (its model list lists credentials, as Provimux's does; a lookup of the
|
|
430
|
+
list that fails changes nothing), but not this one (Provimux leaves an answer unnamed when plugin code took part in it; an older Provimux names only the kind).
|
|
431
|
+
- Nothing from a proxy that names no answer (plain CLIProxyAPI), and nothing while a model of another provider is
|
|
432
|
+
selected or answers, even for a Provimux answer that ends after the switch.
|
|
433
|
+
|
|
434
|
+
Set `"answered": false` in `~/.pi/agent/cliproxyapi.json` to turn it off (takes effect on the next start or
|
|
435
|
+
`/reload`).
|
|
436
|
+
|
|
356
437
|
## Where each model comes from (for other extensions)
|
|
357
438
|
|
|
358
439
|
Through CLIProxyAPI pi sees one provider, but each model is served by a subscription login or an API key of some lab,
|
|
@@ -436,8 +517,8 @@ How the routes are made:
|
|
|
436
517
|
|
|
437
518
|
If you previously maintained a static provider such as `cpa-responses` in `~/.pi/agent/models.json`:
|
|
438
519
|
|
|
439
|
-
1. Install this package and run `/login Provimux` or `/login
|
|
440
|
-
2.
|
|
520
|
+
1. Install this package and run `/login Provimux` or `/login provimux` (or set `cliproxyapi.json`).
|
|
521
|
+
2. Set `defaultProvider` to `provimux` with `defaultModel` `<model-id>`, and write `enabledModels` entries as `provimux/<model-id>` (or set `providerId` to `cpa-responses` for a drop-in id).
|
|
441
522
|
3. Remove the hand-maintained models array once the dynamic list looks correct.
|
|
442
523
|
|
|
443
524
|
## Elapsed time and TPS (TUI)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The footer says which route answered the session's last turn: `answered: Anthropic sub`, `answered: Devin sub`,
|
|
3
|
+
* `answered: OpenRouter api`.
|
|
4
|
+
*
|
|
5
|
+
* Through Provimux one model name can be served by several routes (subscription logins, API keys, OpenRouter …), and
|
|
6
|
+
* each answer names the credential that served it (`X-CPA-AUTH-*` headers, or the `cpa_auth_*` fields of a Codex
|
|
7
|
+
* WebSocket turn's response.created). Each request keeps what the attempt that answered said with the message it ends
|
|
8
|
+
* with (`answerOf`); pi hands only the session's own turns to `message_end`, so pi's cache warmer and other
|
|
9
|
+
* extensions' requests, which overlap the turns, never change what the footer says.
|
|
10
|
+
*
|
|
11
|
+
* The footer only ever shows the route that produced the answer the user sees:
|
|
12
|
+
* - Only an answer: a turn that completed (`stop`, or `toolUse`) with something in it. A failed, aborted or empty turn
|
|
13
|
+
* leaves the footer as it was, whatever its attempt said.
|
|
14
|
+
* - The answer names a credential: `answered: <service> <sub|api>`, in the words of the model names (`sourceLabel`).
|
|
15
|
+
* - It names nobody, from a proxy that names answers (its model list lists credentials, or it named an answer before
|
|
16
|
+
* in this session), or gives only the kind: `answered: unknown`.
|
|
17
|
+
* - It names nobody, from a proxy that names no answer (plain CLIProxyAPI): nothing.
|
|
18
|
+
* - Another provider's model (selected, or answering a turn): nothing; a turn of this provider that ends after another
|
|
19
|
+
* provider's model was selected leaves it so.
|
|
20
|
+
*
|
|
21
|
+
* Works on its own: no other extension has to ask for the routes (`model-upstreams:request`).
|
|
22
|
+
*/
|
|
23
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
24
|
+
import { answerLabel } from "./sources.ts";
|
|
25
|
+
import { answerOf, type Statement } from "./upstreams.ts";
|
|
26
|
+
|
|
27
|
+
export const ANSWERED_STATUS_KEY = "provimux-answered";
|
|
28
|
+
|
|
29
|
+
const text = (value: unknown) => (typeof value === "string" && value.trim() ? value.trim() : undefined);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The footer's words for what an answer said; undefined for nothing. `namesAnswers`: whether the proxy is known to
|
|
33
|
+
* name what answers (an answer that names nobody is then one it would not name).
|
|
34
|
+
*/
|
|
35
|
+
export function answeredStatus(said: Statement, namesAnswers: boolean): string | undefined {
|
|
36
|
+
const kind = text(said.kind)?.toLowerCase();
|
|
37
|
+
if (kind !== "oauth" && kind !== "apikey") return namesAnswers ? "answered: unknown" : undefined;
|
|
38
|
+
const provider = text(said.provider);
|
|
39
|
+
// Only the kind (an older Provimux): which service is not said.
|
|
40
|
+
if (!provider) return "answered: unknown";
|
|
41
|
+
const host = text(said.host);
|
|
42
|
+
return `answered: ${answerLabel({ provider, kind, ...(host ? { host } : {}) })}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface AnsweredMessage {
|
|
46
|
+
role?: unknown;
|
|
47
|
+
provider?: unknown;
|
|
48
|
+
stopReason?: unknown;
|
|
49
|
+
content?: unknown;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A block the user sees: text or thinking with something in it, a tool call, anything else pi shows. */
|
|
53
|
+
function shown(block: unknown): boolean {
|
|
54
|
+
if (!block || typeof block !== "object") return false;
|
|
55
|
+
const { type, text: said, thinking } = block as { type?: unknown; text?: unknown; thinking?: unknown };
|
|
56
|
+
if (type === "text") return !!text(said);
|
|
57
|
+
if (type === "thinking") return !!text(thinking);
|
|
58
|
+
return typeof type === "string";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** An answer the user sees: completed, or calling tools, with something in it. */
|
|
62
|
+
export function isAnswer(message: AnsweredMessage): boolean {
|
|
63
|
+
if (message.stopReason !== "stop" && message.stopReason !== "toolUse") return false;
|
|
64
|
+
return Array.isArray(message.content) && message.content.some(shown);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Shows what answered each of the session's turns on this provider's models. `provider`: the provider's id, or what
|
|
69
|
+
* tells its ids (one extension can register more than one). `namesAnswers`: what else is known of the proxy (the
|
|
70
|
+
* announcer's credential list, and answers of other requests that named a credential).
|
|
71
|
+
*/
|
|
72
|
+
export function registerAnsweredFooter(
|
|
73
|
+
pi: ExtensionAPI,
|
|
74
|
+
provider: string | ((provider: string | undefined) => boolean),
|
|
75
|
+
namesAnswers: () => boolean = () => false,
|
|
76
|
+
) {
|
|
77
|
+
const isOwn = typeof provider === "string" ? (id: string | undefined) => id === provider : provider;
|
|
78
|
+
/** A turn of this session named a credential: the proxy names answers. */
|
|
79
|
+
let namedBefore = false;
|
|
80
|
+
|
|
81
|
+
const show = (ctx: ExtensionContext | undefined, status: string | undefined) => {
|
|
82
|
+
try {
|
|
83
|
+
if (!ctx?.hasUI) return;
|
|
84
|
+
ctx.ui.setStatus(ANSWERED_STATUS_KEY, status === undefined ? undefined : ctx.ui.theme.fg("dim", status));
|
|
85
|
+
} catch {
|
|
86
|
+
// A context from a session that is gone: its footer is too.
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/** Whether the session's model is now one of this provider's: an answer that ends later shows on no other. */
|
|
91
|
+
const ownModel = (ctx: ExtensionContext) => {
|
|
92
|
+
try {
|
|
93
|
+
return isOwn(ctx.model?.provider);
|
|
94
|
+
} catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
pi.on("message_end", (event, ctx) => {
|
|
100
|
+
const message = event.message as AnsweredMessage;
|
|
101
|
+
if (message.role !== "assistant") return;
|
|
102
|
+
// No answer the user sees (failed, aborted, empty): what answered last still stands.
|
|
103
|
+
if (!isAnswer(message)) return;
|
|
104
|
+
if (typeof message.provider !== "string" || !isOwn(message.provider) || !ownModel(ctx)) {
|
|
105
|
+
show(ctx, undefined);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const said = answerOf(message);
|
|
109
|
+
// An answer nothing was heard about: nothing to say.
|
|
110
|
+
if (!said) {
|
|
111
|
+
show(ctx, undefined);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const kind = text(said.kind)?.toLowerCase();
|
|
115
|
+
if (kind === "oauth" || kind === "apikey") namedBefore = true;
|
|
116
|
+
show(ctx, answeredStatus(said, namedBefore || namesAnswers()));
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
pi.on("model_select", (event, ctx) => {
|
|
120
|
+
if (!isOwn(event.model.provider)) show(ctx, undefined);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
// A new session has had no answer yet.
|
|
124
|
+
pi.on("session_start", (_event, ctx) => {
|
|
125
|
+
namedBefore = false;
|
|
126
|
+
show(ctx, undefined);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
130
|
+
namedBefore = false;
|
|
131
|
+
show(ctx, undefined);
|
|
132
|
+
});
|
|
133
|
+
}
|
package/extensions/index.ts
CHANGED
|
@@ -2,12 +2,11 @@
|
|
|
2
2
|
* Provimux dynamic model provider for pi (works with a Provimux or a plain CLIProxyAPI server).
|
|
3
3
|
*
|
|
4
4
|
* Supports login-style setup via `/login`:
|
|
5
|
-
* 1. Provider is registered as OAuth-only so `/login Provimux` / `/login
|
|
5
|
+
* 1. Provider is registered as OAuth-only so `/login Provimux` / `/login provimux`
|
|
6
6
|
* skip the API-key vs account selector and go straight to multi-field prompts
|
|
7
7
|
* (pi only supports multi-field prompts on the account/OAuth path). pi matches the
|
|
8
|
-
* reference against the id and the display name ignoring case
|
|
9
|
-
*
|
|
10
|
-
* 2. Preferred shortcuts: `/login Provimux` or `/login cliproxyapi`.
|
|
8
|
+
* reference against the id and the display name ignoring case.
|
|
9
|
+
* 2. Preferred shortcuts: `/login Provimux` or `/login provimux`.
|
|
11
10
|
* 3. Setup prompts for baseUrl + apiKey.
|
|
12
11
|
* 4. Final login step validates credentials via /v1/models?client_version=pi
|
|
13
12
|
* (HTTP 200 = success even if the catalog is empty; otherwise re-prompt).
|
|
@@ -29,6 +28,7 @@ import type {
|
|
|
29
28
|
StreamFunction,
|
|
30
29
|
} from "@earendil-works/pi-ai";
|
|
31
30
|
import { type ExtensionAPI, type ExtensionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
31
|
+
import { registerAnsweredFooter } from "./answered-footer.ts";
|
|
32
32
|
import { ProactiveCompactionController } from "./auto-compact.ts";
|
|
33
33
|
import {
|
|
34
34
|
CLIPROXYAPI_CODEX_API,
|
|
@@ -53,6 +53,7 @@ import {
|
|
|
53
53
|
loadConfiguredDefaultSettings,
|
|
54
54
|
type MappedModels,
|
|
55
55
|
type PiProviderModel,
|
|
56
|
+
resolveAnsweredDefault,
|
|
56
57
|
resolveClaudeMessagesDefault,
|
|
57
58
|
resolveConnection,
|
|
58
59
|
resolveEndpoints,
|
|
@@ -689,9 +690,8 @@ export function registerFastCommands(options: {
|
|
|
689
690
|
pi.registerCommand("ultrafast", createCommand("ultrafast", "Ultra Fast", "ultrafast"));
|
|
690
691
|
}
|
|
691
692
|
|
|
692
|
-
/** The refresh command
|
|
693
|
+
/** The refresh command. The original extension's name for it, `/cliproxyapi-refresh`, is gone since 105.0.4. */
|
|
693
694
|
export const REFRESH_COMMAND = "provimux-refresh";
|
|
694
|
-
export const LEGACY_REFRESH_COMMAND = "cliproxyapi-refresh";
|
|
695
695
|
|
|
696
696
|
export function registerRefreshCommand(options: {
|
|
697
697
|
pi: ExtensionAPI;
|
|
@@ -788,11 +788,6 @@ export function registerRefreshCommand(options: {
|
|
|
788
788
|
description: "Force refresh Provimux models from the remote catalog.",
|
|
789
789
|
handler: refreshHandler(REFRESH_COMMAND),
|
|
790
790
|
});
|
|
791
|
-
// The original extension's name for it, kept for people coming from pi-cliproxyapi-provider.
|
|
792
|
-
pi.registerCommand(LEGACY_REFRESH_COMMAND, {
|
|
793
|
-
description: `Old name of /${REFRESH_COMMAND}: force refresh Provimux models from the remote catalog.`,
|
|
794
|
-
handler: refreshHandler(LEGACY_REFRESH_COMMAND),
|
|
795
|
-
});
|
|
796
791
|
}
|
|
797
792
|
|
|
798
793
|
export { CLIPROXYAPI_CODEX_API } from "./codex-stream.ts";
|
|
@@ -845,7 +840,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
845
840
|
);
|
|
846
841
|
};
|
|
847
842
|
try {
|
|
848
|
-
|
|
843
|
+
// pi checks this list against the model being called, and only this provider's models use this stream.
|
|
844
|
+
const streams = await loadCliproxyCodexStreams([identity.providerId], {
|
|
849
845
|
resolveServiceTier: (model) =>
|
|
850
846
|
model.provider === identity.providerId ? fastMode.getServiceTierFor(model.id) : undefined,
|
|
851
847
|
});
|
|
@@ -956,7 +952,11 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
956
952
|
}, DEFAULT_AUTO_RECOVERY_DELAY_MS);
|
|
957
953
|
};
|
|
958
954
|
|
|
955
|
+
/** The last model list (fetched, or the cache it was saved to) listed credentials: the proxy names what answers. */
|
|
956
|
+
let listsCredentials = false;
|
|
959
957
|
const handleRefreshOutcome = (loaded: MappedModels): void => {
|
|
958
|
+
// Only a credential lookup that answered (or the cache it was saved to) changes what is known.
|
|
959
|
+
if (typeof loaded.listsCredentials === "boolean") listsCredentials = loaded.listsCredentials;
|
|
960
960
|
const staleModels = loaded.models.filter((m) => m.stale);
|
|
961
961
|
latestStaleModelIds = staleModels.map((m) => m.id);
|
|
962
962
|
|
|
@@ -991,6 +991,16 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
991
991
|
resolveConnection(agentDir, identity.providerId),
|
|
992
992
|
);
|
|
993
993
|
upstreams.register();
|
|
994
|
+
// The footer says which route answered each of the session's turns: on by default, `"answered": false` turns it off.
|
|
995
|
+
let answeredEnabled = true;
|
|
996
|
+
try {
|
|
997
|
+
answeredEnabled = resolveAnsweredDefault(agentDir);
|
|
998
|
+
} catch (error) {
|
|
999
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1000
|
+
logWarn(`invalid answered configuration (${message}); using answered=true`);
|
|
1001
|
+
}
|
|
1002
|
+
if (answeredEnabled)
|
|
1003
|
+
registerAnsweredFooter(pi, identity.providerId, () => listsCredentials || upstreams.namesAnswers());
|
|
994
1004
|
// The Claude Messages models are sent by pi-ai's own implementation: their requests get their own callbacks there.
|
|
995
1005
|
try {
|
|
996
1006
|
const { getApiProvider } = await import("@earendil-works/pi-ai/compat");
|
|
@@ -1090,6 +1100,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
1090
1100
|
});
|
|
1091
1101
|
|
|
1092
1102
|
if (fromCache) {
|
|
1103
|
+
// Only a credential lookup that answered (or the cache it was saved to) changes what is known.
|
|
1104
|
+
if (typeof loaded.listsCredentials === "boolean") listsCredentials = loaded.listsCredentials;
|
|
1093
1105
|
const cachedStaleModels = loaded.models.filter((m) => m.stale);
|
|
1094
1106
|
if (cachedStaleModels.length > 0) {
|
|
1095
1107
|
latestStaleModelIds = cachedStaleModels.map((m) => m.id);
|
package/extensions/lib.ts
CHANGED
|
@@ -24,8 +24,14 @@ export interface PiProviderModelCompat {
|
|
|
24
24
|
/** pi API id used for Claude models when the Claude Messages format is enabled. */
|
|
25
25
|
export const ANTHROPIC_MESSAGES_API = "anthropic-messages";
|
|
26
26
|
|
|
27
|
-
export const DEFAULT_PROVIDER_ID = "
|
|
27
|
+
export const DEFAULT_PROVIDER_ID = "provimux";
|
|
28
28
|
export const DEFAULT_PROVIDER_NAME = "Provimux";
|
|
29
|
+
/**
|
|
30
|
+
* The provider id before 105.0.5. `/login` writes the id into `cliproxyapi.json`, so a setup made then holds it
|
|
31
|
+
* without anyone having chosen it: read from the file, it means the default. Set by `CLIPROXYAPI_PROVIDER_ID`, it
|
|
32
|
+
* is a choice and is kept. Nothing registers it, moves sessions from it, or reads its `auth.json` entry.
|
|
33
|
+
*/
|
|
34
|
+
export const LEGACY_DEFAULT_PROVIDER_ID = "cliproxyapi";
|
|
29
35
|
/**
|
|
30
36
|
* The display name before 105.0.3. `/login` writes the name into `cliproxyapi.json`, so a setup made then holds it
|
|
31
37
|
* without anyone having chosen it: read from the file, it means the default. Set by `CLIPROXYAPI_PROVIDER_NAME`, it
|
|
@@ -57,6 +63,7 @@ export interface CliproxyConfigFile {
|
|
|
57
63
|
fast?: FastPreference;
|
|
58
64
|
pause?: boolean;
|
|
59
65
|
tps?: boolean;
|
|
66
|
+
answered?: boolean;
|
|
60
67
|
claudeMessages?: boolean | "auto";
|
|
61
68
|
}
|
|
62
69
|
|
|
@@ -166,6 +173,11 @@ export interface MappedModels {
|
|
|
166
173
|
modelsUrl: string;
|
|
167
174
|
fastMode?: boolean;
|
|
168
175
|
claudeMessages?: ClaudeMessagesMode | boolean;
|
|
176
|
+
/**
|
|
177
|
+
* The proxy listed the credentials that serve its models (`?include=accounts`): it names what answers. false: its
|
|
178
|
+
* list was read and listed none; absent: not known (the lookup failed, or a cache from before this was kept).
|
|
179
|
+
*/
|
|
180
|
+
listsCredentials?: boolean;
|
|
169
181
|
}
|
|
170
182
|
|
|
171
183
|
export interface ModelsCacheFile extends MappedModels {
|
|
@@ -418,7 +430,13 @@ export function resolveIdentity(agentDir: string): ResolvedIdentity {
|
|
|
418
430
|
}
|
|
419
431
|
|
|
420
432
|
return {
|
|
421
|
-
providerId: firstNonEmpty(
|
|
433
|
+
providerId: firstNonEmpty(
|
|
434
|
+
process.env.CLIPROXYAPI_PROVIDER_ID,
|
|
435
|
+
typeof file.providerId === "string" && file.providerId.trim() === LEGACY_DEFAULT_PROVIDER_ID
|
|
436
|
+
? undefined
|
|
437
|
+
: file.providerId,
|
|
438
|
+
DEFAULT_PROVIDER_ID,
|
|
439
|
+
)!,
|
|
422
440
|
providerName: firstNonEmpty(
|
|
423
441
|
process.env.CLIPROXYAPI_PROVIDER_NAME,
|
|
424
442
|
typeof file.providerName === "string" && file.providerName.trim() === LEGACY_DEFAULT_PROVIDER_NAME
|
|
@@ -500,6 +518,18 @@ export function resolveTpsDefault(agentDir: string): boolean {
|
|
|
500
518
|
return file.tps;
|
|
501
519
|
}
|
|
502
520
|
|
|
521
|
+
/** Resolve whether the footer says which route answered, from cliproxyapi.json, defaulting to true. */
|
|
522
|
+
export function resolveAnsweredDefault(agentDir: string): boolean {
|
|
523
|
+
const file = loadConfigFile(agentDir);
|
|
524
|
+
if (file.answered === undefined) {
|
|
525
|
+
return true;
|
|
526
|
+
}
|
|
527
|
+
if (typeof file.answered !== "boolean") {
|
|
528
|
+
throw new Error(`${CONFIG_FILE_NAME} field "answered" must be a boolean`);
|
|
529
|
+
}
|
|
530
|
+
return file.answered;
|
|
531
|
+
}
|
|
532
|
+
|
|
503
533
|
/** Resolve the request pause preference from cliproxyapi.json, defaulting to false. */
|
|
504
534
|
export function resolvePauseDefault(agentDir: string): boolean {
|
|
505
535
|
const file = loadConfigFile(agentDir);
|
|
@@ -1091,6 +1121,8 @@ export interface ModelSources {
|
|
|
1091
1121
|
owners: Map<string, string>;
|
|
1092
1122
|
/** Model id → the credentials that serve it; absent when CPA does not list them. */
|
|
1093
1123
|
accounts: Map<string, Account[]>;
|
|
1124
|
+
/** The list was read (HTTP 200 with a list): only then does it say whether CPA lists credentials. */
|
|
1125
|
+
read?: boolean;
|
|
1094
1126
|
}
|
|
1095
1127
|
|
|
1096
1128
|
/**
|
|
@@ -1112,6 +1144,7 @@ export async function fetchModelSources(
|
|
|
1112
1144
|
});
|
|
1113
1145
|
if (!response.ok) return sources;
|
|
1114
1146
|
const data = asRecord(await response.json())?.data;
|
|
1147
|
+
if (!Array.isArray(data)) return sources;
|
|
1115
1148
|
for (const item of Array.isArray(data) ? data : []) {
|
|
1116
1149
|
const record = asRecord(item);
|
|
1117
1150
|
const id = typeof record?.id === "string" ? record.id.trim() : "";
|
|
@@ -1121,6 +1154,7 @@ export async function fetchModelSources(
|
|
|
1121
1154
|
const accounts = parseAccounts(record?.accounts);
|
|
1122
1155
|
if (accounts.length > 0) sources.accounts.set(id, accounts);
|
|
1123
1156
|
}
|
|
1157
|
+
sources.read = true;
|
|
1124
1158
|
} catch {
|
|
1125
1159
|
// Without the list every model stays on the Codex format, and no name says where a model comes from.
|
|
1126
1160
|
}
|
|
@@ -1198,6 +1232,8 @@ export async function loadMappedModels(
|
|
|
1198
1232
|
modelsUrl: endpoints.modelsUrl,
|
|
1199
1233
|
...(pricingEnabled ? { fastMode: effectiveFastMode } : {}),
|
|
1200
1234
|
...(claudeWanted ? { claudeMessages: claudeMode } : {}),
|
|
1235
|
+
// Said only by a list that was read: a failed lookup says nothing either way.
|
|
1236
|
+
...(sources.read ? { listsCredentials: sources.accounts.size > 0 } : {}),
|
|
1201
1237
|
};
|
|
1202
1238
|
}
|
|
1203
1239
|
|
|
@@ -1334,8 +1370,14 @@ export async function resolveMappedModels(
|
|
|
1334
1370
|
Date.now(),
|
|
1335
1371
|
options.staleTtlMs,
|
|
1336
1372
|
);
|
|
1373
|
+
// Only a credential lookup that answered changes what is known; a failed one keeps what the cache knew.
|
|
1374
|
+
const listsCredentials = fresh.listsCredentials ?? existingCache?.listsCredentials;
|
|
1375
|
+
delete merged.listsCredentials;
|
|
1376
|
+
if (listsCredentials !== undefined) merged.listsCredentials = listsCredentials;
|
|
1337
1377
|
if (!options.signal?.aborted && (options.shouldCommit?.() ?? true)) {
|
|
1338
|
-
|
|
1378
|
+
// On disk only a list that names credentials is recorded; none listed reads as not known, as before.
|
|
1379
|
+
const { listsCredentials: _known, ...rest } = merged;
|
|
1380
|
+
saveModelsCache(agentDir, listsCredentials ? merged : rest);
|
|
1339
1381
|
}
|
|
1340
1382
|
return { loaded: merged, fromCache: false };
|
|
1341
1383
|
}
|
package/extensions/sources.ts
CHANGED
|
@@ -106,6 +106,17 @@ function sourcesOf(accounts: Account[]): Source[] {
|
|
|
106
106
|
return sources;
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
/**
|
|
110
|
+
* What answered a request, in the words of `sourceLabel`: "Anthropic sub", "Devin sub", "OpenRouter api". From the
|
|
111
|
+
* credential the answer names: its provider (any letter case), its kind and, for an API key with a base URL, its host.
|
|
112
|
+
*/
|
|
113
|
+
export function answerLabel(credential: { provider: string; kind: string; host?: string }): string {
|
|
114
|
+
const kind = credential.kind.trim().toLowerCase();
|
|
115
|
+
const host = credential.host?.trim().toLowerCase();
|
|
116
|
+
const [source] = sourcesOf([{ provider: credential.provider, kind, priority: 0, ...(host ? { host } : {}) }]);
|
|
117
|
+
return `${source!.service} ${source!.kind}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
109
120
|
/**
|
|
110
121
|
* Where a model comes from, for its name: "Anthropic sub, fallback api". First what CLIProxyAPI may answer with (the
|
|
111
122
|
* credentials at the highest priority, joined by "or" when they differ), then what it falls back to, highest priority
|
package/extensions/upstreams.ts
CHANGED
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
* Requests overlap (pi's cache warmer next to the turn it warms, an extension's own call with the session's callbacks),
|
|
25
25
|
* and pi's events say nothing of which request they belong to. So what a request's answer says is kept by that request
|
|
26
26
|
* alone: each call of the provider's stream gets its own callbacks (`answeredOptions`), which hold its headers and its
|
|
27
|
-
* one report, and mark the stream event it is told with. The session's handler only reads that mark.
|
|
27
|
+
* one report, and mark the stream event it is told with. The session's handler only reads that mark. They also keep
|
|
28
|
+
* what the answer said with the message the request ends with (`answerOf`), for the footer (answered-footer.ts).
|
|
28
29
|
*
|
|
29
30
|
* An upstream is `{ provider, model?, subscription? }`: the pi provider the model would come from if used directly
|
|
30
31
|
* (anthropic, openai-codex, openai, meta, openrouter, google) or a providers.dev provider pi has none for (devin,
|
|
@@ -266,7 +267,7 @@ export async function fetchModelAccounts(
|
|
|
266
267
|
}
|
|
267
268
|
|
|
268
269
|
/** What an answer says answered it, as given: the kind, provider and host (any may be absent or not a string). */
|
|
269
|
-
interface Statement {
|
|
270
|
+
export interface Statement {
|
|
270
271
|
kind: unknown;
|
|
271
272
|
provider: unknown;
|
|
272
273
|
host: unknown;
|
|
@@ -285,6 +286,39 @@ function statements(): WeakMap<object, Statement> {
|
|
|
285
286
|
return global[STATEMENTS_KEY];
|
|
286
287
|
}
|
|
287
288
|
|
|
289
|
+
/**
|
|
290
|
+
* Where a message carries what its answer said: an own property under a symbol shared by every copy of this module,
|
|
291
|
+
* set on the message pi's agent loop takes from the request's stream and hands to `message_end`. Only the session's
|
|
292
|
+
* own turns get there, never pi's cache warmer or another extension's request. An own enumerable property: a shallow
|
|
293
|
+
* copy (`{ ...message }`, as another extension's `message_end` handler may return) keeps it; JSON (the session file)
|
|
294
|
+
* drops it.
|
|
295
|
+
*/
|
|
296
|
+
const ANSWER = Symbol.for("pi-provimux.answer");
|
|
297
|
+
|
|
298
|
+
/** What the answer a message came from said answered it; undefined when it is not a message of this provider's stream. */
|
|
299
|
+
export function answerOf(message: unknown): Statement | undefined {
|
|
300
|
+
if (!isRecord(message)) return undefined;
|
|
301
|
+
const said = (message as Record<symbol, unknown>)[ANSWER];
|
|
302
|
+
return isRecord(said) ? (said as unknown as Statement) : undefined;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Keeps what a request's answer said with the message its stream ends with (`answerOf`). */
|
|
306
|
+
function keepWithMessage(stream: unknown, said: (message: Record<string, unknown>) => Statement | undefined): void {
|
|
307
|
+
const result = (stream as { result?: unknown } | null | undefined)?.result;
|
|
308
|
+
if (typeof result !== "function") return;
|
|
309
|
+
try {
|
|
310
|
+
Promise.resolve((result as () => unknown).call(stream)).then(
|
|
311
|
+
(message) => {
|
|
312
|
+
const statement = isRecord(message) ? said(message) : undefined;
|
|
313
|
+
if (statement && isRecord(message)) (message as Record<symbol, unknown>)[ANSWER] = statement;
|
|
314
|
+
},
|
|
315
|
+
() => {},
|
|
316
|
+
);
|
|
317
|
+
} catch {
|
|
318
|
+
// A stream without a result to wait for: nothing to keep.
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
288
322
|
/** The callbacks one request is sent with, as `onResponse` and `onProviderStreamEvent` take them. */
|
|
289
323
|
export interface AnswerCallbacks<TModel = unknown> {
|
|
290
324
|
onResponse?: (response: { status: number; headers: Record<string, string> }, model: TModel) => unknown;
|
|
@@ -299,49 +333,97 @@ export interface AnswerCallbacks<TModel = unknown> {
|
|
|
299
333
|
* called as they were, with the same arguments; nothing else changes.
|
|
300
334
|
*/
|
|
301
335
|
export function answeredOptions<T extends AnswerCallbacks<never> | undefined>(options: T): T {
|
|
336
|
+
return keptOptions(options).options;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** What an attempt that named nobody said: an unnamed answer. */
|
|
340
|
+
const UNNAMED: Statement = { kind: undefined, provider: undefined, host: undefined };
|
|
341
|
+
|
|
342
|
+
/** Codex events that end an attempt without an answer: what it said goes with it. */
|
|
343
|
+
const FAILED_ATTEMPT = new Set(["response.failed", "response.incomplete", "error"]);
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* `answeredOptions`, and what the answer the request ends with said (for its message): only what the attempt that
|
|
347
|
+
* answered said itself. pi-ai can try a request again inside one call (an HTTP 429; a Codex WebSocket continuation the
|
|
348
|
+
* proxy lost, replayed on a fresh socket), each attempt may be served by another route, and an attempt starts unnamed.
|
|
349
|
+
* - Over HTTP: the last response's own headers.
|
|
350
|
+
* - Without headers (the Codex WebSocket): the response.created's fields of the response the message comes from. An
|
|
351
|
+
* attempt that failed takes what it said with it, and a response.created of another response than the message's
|
|
352
|
+
* (its id) says nothing of it. An answer whose attempt said nothing (no response.created) is unnamed.
|
|
353
|
+
* - Nothing heard of the request at all: undefined.
|
|
354
|
+
*/
|
|
355
|
+
function keptOptions<T extends AnswerCallbacks<never> | undefined>(
|
|
356
|
+
options: T,
|
|
357
|
+
): { options: T; said: (message: Record<string, unknown>) => Statement | undefined } {
|
|
302
358
|
const onEvent = options?.onProviderStreamEvent;
|
|
303
359
|
// Nobody hears the stream's events: there is nobody to tell.
|
|
304
|
-
if (!options || !onEvent) return options;
|
|
360
|
+
if (!options || !onEvent) return { options, said: () => undefined };
|
|
305
361
|
const onResponse = options.onResponse;
|
|
306
362
|
let headers: Record<string, string> | undefined;
|
|
307
363
|
let told = false;
|
|
364
|
+
/** What the current attempt said, and the response it said it of (WebSocket). */
|
|
365
|
+
let said: Statement | undefined;
|
|
366
|
+
let saidOf: string | undefined;
|
|
367
|
+
let heard = false;
|
|
308
368
|
const header = (wanted: string) =>
|
|
309
369
|
headers && Object.entries(headers).find(([name]) => name.toLowerCase() === wanted)?.[1];
|
|
310
|
-
|
|
370
|
+
const wrapped = {
|
|
311
371
|
...options,
|
|
312
372
|
onResponse: (response: { status: number; headers: Record<string, string> }, model: never) => {
|
|
313
373
|
// A retried request: the last response is the one whose body is read.
|
|
314
374
|
headers = response.headers ?? {};
|
|
375
|
+
said = {
|
|
376
|
+
kind: header(AUTH_KIND_HEADER),
|
|
377
|
+
provider: header(AUTH_PROVIDER_HEADER),
|
|
378
|
+
host: header(AUTH_HOST_HEADER),
|
|
379
|
+
};
|
|
315
380
|
return onResponse?.(response, model);
|
|
316
381
|
},
|
|
317
382
|
onProviderStreamEvent: (data: unknown, model: never) => {
|
|
318
|
-
if (
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
383
|
+
if (isRecord(data)) {
|
|
384
|
+
heard = true;
|
|
385
|
+
// Over HTTP the headers alone count: a body's own fields are an inner gateway's.
|
|
386
|
+
if (!headers && data.type === "response.created") {
|
|
387
|
+
said = { kind: data[AUTH_KIND_FIELD], provider: data[AUTH_PROVIDER_FIELD], host: data[AUTH_HOST_FIELD] };
|
|
388
|
+
const id = isRecord(data.response) ? data.response.id : undefined;
|
|
389
|
+
saidOf = typeof id === "string" ? id : undefined;
|
|
390
|
+
} else if (!headers && typeof data.type === "string" && FAILED_ATTEMPT.has(data.type)) {
|
|
391
|
+
// The attempt ended without an answer: the next one starts unnamed.
|
|
392
|
+
said = undefined;
|
|
393
|
+
saidOf = undefined;
|
|
394
|
+
}
|
|
395
|
+
// The event is told once per request, with its first statement.
|
|
396
|
+
if (!told && said && (headers || data.type === "response.created")) {
|
|
327
397
|
told = true;
|
|
328
|
-
statements().set(data,
|
|
329
|
-
kind: data[AUTH_KIND_FIELD],
|
|
330
|
-
provider: data[AUTH_PROVIDER_FIELD],
|
|
331
|
-
host: data[AUTH_HOST_FIELD],
|
|
332
|
-
});
|
|
398
|
+
statements().set(data, said);
|
|
333
399
|
}
|
|
334
400
|
}
|
|
335
401
|
return onEvent(data, model);
|
|
336
402
|
},
|
|
337
403
|
} as T;
|
|
404
|
+
const saidOfMessage = (message: Record<string, unknown>): Statement | undefined => {
|
|
405
|
+
if (headers) return said;
|
|
406
|
+
if (!heard) return undefined;
|
|
407
|
+
// The message is another response's than the one the held statement was said of: its attempt said nothing.
|
|
408
|
+
if (saidOf && typeof message.responseId === "string" && message.responseId !== saidOf) return UNNAMED;
|
|
409
|
+
return said ?? UNNAMED;
|
|
410
|
+
};
|
|
411
|
+
return { options: wrapped, said: saidOfMessage };
|
|
338
412
|
}
|
|
339
413
|
|
|
340
|
-
/**
|
|
414
|
+
/**
|
|
415
|
+
* A stream function whose every call keeps what its answer says to itself (`answeredOptions`), and with the message
|
|
416
|
+
* its stream ends with (`answerOf`).
|
|
417
|
+
*/
|
|
341
418
|
export function answeredStream<M, C, O extends AnswerCallbacks<never> | undefined, R>(
|
|
342
419
|
stream: (model: M, context: C, options: O) => R,
|
|
343
420
|
): (model: M, context: C, options: O) => R {
|
|
344
|
-
return (model, context, options) =>
|
|
421
|
+
return (model, context, options) => {
|
|
422
|
+
const kept = keptOptions(options);
|
|
423
|
+
const result = stream(model, context, kept.options);
|
|
424
|
+
keepWithMessage(result, kept.said);
|
|
425
|
+
return result;
|
|
426
|
+
};
|
|
345
427
|
}
|
|
346
428
|
|
|
347
429
|
/** pi-ai's implementation of an API, as `getApiProvider` gives it. */
|
|
@@ -407,8 +489,13 @@ export function answeredClaudeMessages(
|
|
|
407
489
|
const originals = { stream: implementation.stream, streamSimple: implementation.streamSimple };
|
|
408
490
|
const wrap =
|
|
409
491
|
(original: ApiImplementation[Method]): ApiImplementation[Method] =>
|
|
410
|
-
(model, context, options) =>
|
|
411
|
-
|
|
492
|
+
(model, context, options) => {
|
|
493
|
+
if (!scope.providers.has(model.provider)) return original(model, context, options);
|
|
494
|
+
const kept = keptOptions(options);
|
|
495
|
+
const result = original(model, context, kept.options);
|
|
496
|
+
keepWithMessage(result, kept.said);
|
|
497
|
+
return result;
|
|
498
|
+
};
|
|
412
499
|
const wrappers = { stream: wrap(originals.stream), streamSimple: wrap(originals.streamSimple) };
|
|
413
500
|
implementation.stream = wrappers.stream;
|
|
414
501
|
implementation.streamSimple = wrappers.streamSimple;
|
|
@@ -529,7 +616,7 @@ export class UpstreamsAnnouncer {
|
|
|
529
616
|
}
|
|
530
617
|
|
|
531
618
|
/** Whether the proxy names what answered: it lists its credentials (Provimux), or it named an answer before. */
|
|
532
|
-
|
|
619
|
+
namesAnswers(): boolean {
|
|
533
620
|
if (this.namedBefore) return true;
|
|
534
621
|
return !!this.listed && Object.values(this.listed.accounts).some((accounts) => accounts.length > 0);
|
|
535
622
|
}
|