pi-cliproxyapi 0.3.5 → 0.4.1

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 CHANGED
@@ -71,7 +71,7 @@ Extra Models keys: `d` removes a custom group (with confirmation).
71
71
 
72
72
  You need a running [CliProxyAPI](https://github.com/router-for-me/CLIProxyAPI) instance — this is the corporate LLM proxy that aggregates multiple providers behind a single OpenAI-compatible endpoint.
73
73
 
74
- For full functionality (Usage tab, enriched model metadata from [models.dev](https://models.dev)), also deploy the companion sidecar: **[pi-cliproxyapi-wellknown](https://github.com/abix5/pi-cliproxyapi-wellknown)**. See [Deploying the sidecar](#deploying-the-sidecar-service) below.
74
+ For full functionality (Usage tab, enriched model metadata from [models.dev](https://models.dev)), also install the **[pi-bridge](https://github.com/abix5/pi-cliproxyapi-bridge)** plugin into that instance. See [Discovery](#discovery) below.
75
75
 
76
76
  ## Install
77
77
 
@@ -81,6 +81,33 @@ pi install npm:pi-cliproxyapi
81
81
 
82
82
  Then run `/cliproxy-setup` to configure your proxy endpoint.
83
83
 
84
+ ### Taskflow child agents
85
+
86
+ Taskflow starts children with an extension allowlist, so add this package's entrypoint
87
+ there as well; otherwise the child cannot register the proxy-backed model catalog.
88
+ For a normal npm installation:
89
+
90
+ ```jsonc
91
+ {
92
+ "taskflow": {
93
+ "piChild": {
94
+ "resourceProfile": "allowlist",
95
+ "extensions": [
96
+ "/Users/your-user/.pi/agent/npm/node_modules/pi-cliproxyapi/index.ts"
97
+ ]
98
+ }
99
+ }
100
+ }
101
+ ```
102
+
103
+ Use a real **absolute** path: taskflow does not expand `~`, so replace
104
+ `/Users/your-user` with your home directory. Preserve any existing allowlisted
105
+ extensions (such as taskflow's path guard and MCP adapter). For a local checkout, use
106
+ its absolute `index.ts` path instead. A child running in JSON/print mode reads the
107
+ discovery cache and registers providers without discovery, usage, command, status, or
108
+ timer work. Start Pi once interactively after configuring the proxy to populate that
109
+ cache.
110
+
84
111
  ## Config
85
112
 
86
113
  `~/.pi/agent/pi-cliproxyapi/config.json` — created by `/cliproxy-setup`, editable by hand. If only the legacy `~/.config/pi-cliproxyapi/config.json` exists, an installed plugin moves it here once; a local checkout copies it and retains the legacy file.
@@ -90,8 +117,7 @@ Then run `/cliproxy-setup` to configure your proxy endpoint.
90
117
  "proxy": {
91
118
  "endpoint": "https://proxy.example.com/v1",
92
119
  "apiKey": "!cat ~/.pi/agent/pi-cliproxyapi/key",
93
- "providerPrefix": "corp",
94
- "usageKey": "!cat ~/.pi/agent/pi-cliproxyapi/usage-key"
120
+ "providerPrefix": "corp"
95
121
  },
96
122
  "builtinProviders": {
97
123
  "anthropic": { "enabled": true, "models": ["claude-opus-4-7"] },
@@ -110,81 +136,56 @@ Values support `!command` (shell exec), `$ENV_VAR`, or literal strings. The `/cl
110
136
 
111
137
  ## Discovery
112
138
 
113
- The plugin tries `GET <endpoint-origin>/.well-known/pi` first (requires the sidecar). If unavailable, falls back to `GET <endpoint>/models` with local heuristics.
114
-
115
- ## Deploying the sidecar service
116
-
117
- The **[pi-cliproxyapi-wellknown](https://github.com/abix5/pi-cliproxyapi-wellknown)** sidecar runs alongside CliProxyAPI and provides:
118
-
119
- - `/.well-known/pi` — model discovery with metadata from [models.dev](https://models.dev) (context windows, costs, reasoning flags)
120
- - `/api/usage` — per-account quota windows used by the hub Usage tab
139
+ The extension reads the model catalogue and provider quota from the
140
+ **[pi-bridge](https://github.com/abix5/pi-cliproxyapi-bridge)** plugin running
141
+ inside CliProxyAPI, authenticating with the same `apiKey` it uses for model
142
+ calls. No second credential and no extra container are involved.
121
143
 
122
144
  ```
123
- ┌──────────────┐ ┌───────────────────────────┐
124
- │ Pi + plugin │────▶│ CliProxyAPI (:8317) │
125
- │ │ │ /v1/models, /v1/chat/... │
126
- │ │ └───────────────────────────┘
127
- │ │ ┌───────────────────────────┐
128
- │ │────▶│ wellknown sidecar (:3458)│
129
- │ │ │ /.well-known/pi │
130
- │ │ │ /api/usage │
131
- │ │ └───────────────────────────┘
132
- └──────────────┘
145
+ ┌──────────────┐ ┌────────────────────────────────────────┐
146
+ │ Pi + plugin │────▶│ CliProxyAPI │
147
+ │ │ │ /v1/models, /v1/chat/... │
148
+ │ │ │ /v0/resource/plugins/pi-bridge/… │
149
+ │ │ │ well-known → model catalogue │
150
+ │ │ │ usage → per-account quota │
151
+ └──────────────┘ └────────────────────────────────────────┘
133
152
  ```
134
153
 
135
- ### Quick start with Docker Compose
136
-
137
- Clone the sidecar repo next to your CliProxyAPI deployment:
138
-
139
- ```bash
140
- git clone https://github.com/abix5/pi-cliproxyapi-wellknown.git
141
- ```
154
+ Without the plugin the extension still works: it falls back to raw `/v1/models`
155
+ with local heuristics.
142
156
 
143
- Add to your `docker-compose.yml`:
144
-
145
- ```yaml
146
- services:
147
- cliproxyapi:
148
- # ... your existing CliProxyAPI service ...
149
-
150
- pi-cliproxyapi-wellknown:
151
- build:
152
- context: ./pi-cliproxyapi-wellknown
153
- restart: unless-stopped
154
- ports:
155
- - "127.0.0.1:3458:3458"
156
- environment:
157
- UPSTREAM_MODELS_URL: http://cliproxyapi:8317/v1/models
158
- UPSTREAM_TOKEN: ${UPSTREAM_TOKEN} # CliProxyAPI bearer key
159
- PI_PUBLIC_BASE_URL: ${PI_PUBLIC_BASE_URL} # e.g. https://proxy.example.com/v1
160
- MANAGEMENT_API_URL: http://cliproxyapi:8317/v0/management
161
- MANAGEMENT_API_KEY: ${MANAGEMENT_API_KEY}
162
- PI_PLUGIN_USAGE_KEY: ${PI_PLUGIN_USAGE_KEY} # shared with Pi plugin
163
- depends_on:
164
- cliproxyapi:
165
- condition: service_healthy
166
- networks:
167
- - your-network
168
- ```
157
+ | | With pi-bridge | Without |
158
+ | --- | --- | --- |
159
+ | Model discovery | Enriched from [models.dev](https://models.dev) — real context windows, costs, reasoning flags | Defaults: `contextWindow=128k`, `maxTokens=16k`, `cost=0` |
160
+ | Usage tab | Per-account quota bars | Unavailable |
161
+ | Classification | Server-side | Local heuristics by `owned_by` |
169
162
 
170
- Then route `/.well-known/pi` and `/api/usage` on your public domain to port 3458 via your reverse proxy (Nginx, Caddy, Cloudflare Tunnel, etc.).
163
+ See the plugin's README for installing it into CliProxyAPI.
171
164
 
172
- ### Connecting the plugin
165
+ ## Setup
173
166
 
174
167
  Run `/cliproxy-setup` in Pi and enter:
168
+
175
169
  - **endpoint** — your public proxy URL ending with `/v1`
176
170
  - **apiKey** — CliProxyAPI bearer key
177
- - **providerPrefix** — short slug for custom provider names (e.g. `corp`, `myproxy`)
178
- - **usageKey** — same value as `PI_PLUGIN_USAGE_KEY` above (enables the Usage tab)
171
+ - **providerPrefix** — short slug for custom provider names (e.g. `corp`)
179
172
 
180
- The sidecar is **optional for basic usage** — without it the plugin falls back to raw `/v1/models` with local heuristics. What changes:
173
+ ## Migrating from the wellknown sidecar
181
174
 
182
- | | With sidecar | Without sidecar |
183
- | --- | --- | --- |
184
- | Model discovery | Enriched from [models.dev](https://models.dev) (real context windows, costs, reasoning) | Defaults: `contextWindow=128k`, `maxTokens=16k`, `cost=0`, `reasoning=false` |
185
- | Usage tab | Works — per-account quota bars | **Does not work** (no `/api/usage` endpoint) |
186
- | Classification | Server-side, accurate | Local heuristics by `owned_by` |
187
- | `/cliproxy` hub | Works | Works (Usage tab shows an error) |
175
+ Earlier versions read `/.well-known/pi` and `/api/usage` from a separate
176
+ `pi-cliproxyapi-wellknown` container, which needed its own `usageKey`. Version
177
+ 0.4.0 reads both from the pi-bridge plugin instead.
178
+
179
+ 1. Install pi-bridge into CliProxyAPI (see its README).
180
+ 2. Update this extension to 0.4.0 or later.
181
+ 3. Confirm the Usage tab still populates — it now says `source=plugin`.
182
+ 4. Drop the sidecar's routes from your reverse proxy, then stop the container.
183
+ 5. Remove `proxy.usageKey` from the config above; it is no longer read by the
184
+ setup wizard and is only consulted as a fallback.
185
+
186
+ Steps 1–2 are safe in either order: until the plugin answers, the extension
187
+ keeps using the sidecar, and a version older than 0.4.0 keeps working against a
188
+ server that already runs the plugin.
188
189
 
189
190
  ## Layout
190
191
 
@@ -194,8 +195,8 @@ src/
194
195
  config.ts ~/.pi/agent/pi-cliproxyapi/config.json
195
196
  commands.ts 2 slash commands (hub + setup)
196
197
  apply.ts pi.registerProvider calls
197
- fetch-models.ts well-known + /v1/models fallback
198
- fetch-usage.ts /api/usage client with TTL cache
198
+ fetch-models.ts catalogue from pi-bridge, /v1/models fallback
199
+ fetch-usage.ts quota from pi-bridge, sidecar fallback, TTL cache
199
200
  compat.ts baseUrl derivation, model classification
200
201
  conflicts.ts read-only ~/.pi/{models,auth}.json scan
201
202
  ui-frame.ts single source of truth for overlay frames
@@ -0,0 +1,109 @@
1
+ # ISSUE: taskflow child agents have zero usable models (pi-cliproxyapi not loaded in `piChild`)
2
+
3
+ - **Status:** open (workaround applied at user-settings level; proper fix needed in this package)
4
+ - **Package:** `pi-cliproxyapi` (this repo, v0.3.5)
5
+ - **Interacts with:** `pi-taskflow` (`taskflow.piChild` spawn config), `@earendil-works/pi-coding-agent` runtime
6
+ - **Severity:** high — blocks ALL taskflow subagents/subflows from running on any model
7
+ - **Found:** 2026-07 while trying to run `designer` / `architect` subagents on `openai/gpt-5.6-sol`
8
+
9
+ ## Symptom
10
+
11
+ Every `taskflow action=run` (single agent or flow) fails immediately. The parent
12
+ session works fine; only the spawned child process is broken. Representative output:
13
+
14
+ ```
15
+ Taskflow 'task' failed (0/1 done, 1 failed).
16
+ Warning: No models match pattern "anthropic/claude-opus-4-8"
17
+ Warning: No models match pattern "proxy/glm-5.2"
18
+ Warning: No models match pattern "openai/gpt-5.6-sol"
19
+ ... (every entry of settings.enabledModels)
20
+ No API key found for openai. Use /login to log into a provider via OAuth or API key.
21
+ ```
22
+
23
+ i.e. in the child, **no model pattern resolves at all**, and the fallback to a
24
+ direct provider (`openai`) fails because there is no API key (`~/.pi/agent/auth.json`
25
+ is empty — auth is normally provided by this proxy extension, not by stored keys).
26
+
27
+ ## Root cause
28
+
29
+ The parent pi session gets its whole model catalog + auth from **this extension**
30
+ (`pi-cliproxyapi`): it registers the proxied model list and routes calls through the
31
+ local CLIProxyAPI. `settings.packages` loads it for the parent.
32
+
33
+ But `pi-taskflow` spawns children with an **allowlisted** extension set:
34
+
35
+ ```jsonc
36
+ // settings.json
37
+ "taskflow": {
38
+ "piChild": {
39
+ "resourceProfile": "allowlist",
40
+ "extensions": [
41
+ ".../taskflow-extensions/child-path-guard.ts",
42
+ ".../node_modules/pi-mcp-adapter/index.ts"
43
+ ]
44
+ }
45
+ }
46
+ ```
47
+
48
+ `pi-cliproxyapi` is **absent** from `piChild.extensions`, so the child never
49
+ registers the proxied model catalog and starts with an empty model registry →
50
+ every configured model (proxy/* and openai/*) is "not found", and the direct-provider
51
+ fallback has no key. Net effect: subagents cannot run on any model.
52
+
53
+ ## Workaround (applied at user settings level, reversible)
54
+
55
+ Prepend this extension to the taskflow child allowlist so the child also loads the
56
+ proxy and registers models. The child reads `settings.json` fresh on spawn, so no
57
+ parent restart is needed.
58
+
59
+ ```jsonc
60
+ "taskflow": {
61
+ "piChild": {
62
+ "extensions": [
63
+ ".../node_modules/pi-cliproxyapi/index.ts", // <-- added (first, so models
64
+ ".../taskflow-extensions/child-path-guard.ts", // register before agents resolve)
65
+ ".../node_modules/pi-mcp-adapter/index.ts"
66
+ ]
67
+ }
68
+ }
69
+ ```
70
+
71
+ After this, child agents resolve e.g. `openai/gpt-5.6-sol` and run. Backup kept at
72
+ `~/.pi/agent/settings.json.bak-notif`.
73
+
74
+ ### Secondary note (expected, not this bug)
75
+
76
+ `child-path-guard.ts` restricts child **writes** to the working directory. Run
77
+ taskflow with `cwd` set to the repo root and use **relative** output paths; absolute
78
+ paths like `/tmp/...` are rejected ("Taskflow запрещает дочернему агенту запись вне
79
+ рабочего каталога").
80
+
81
+ ## Proper fix (options for this package)
82
+
83
+ The extension should be usable inside a taskflow child out of the box, cheaply.
84
+
85
+ 1. **Docs-only (minimum):** document in README that `taskflow.piChild.extensions`
86
+ must include `pi-cliproxyapi` for subagents to have models. Low effort, leaves
87
+ every user to discover this the hard way.
88
+ 2. **Slim child entrypoint (recommended):** export a lightweight "child mode" that
89
+ only registers the model catalog + provider routing from the on-disk discovery
90
+ cache (`~/.pi/agent/discovery-cache.json`) and skips parent-only concerns
91
+ (interactive `/commands`, status/quota segments, live `fetchDiscovery`/`fetchUsage`).
92
+ Cheap enough to load on every child spawn; avoids network under the child's
93
+ `allowlist` resourceProfile (which may block discovery fetches → must rely on cache).
94
+ 3. **Auto-detect child context:** when the extension detects it is running in a
95
+ taskflow child (env/flag from pi-taskflow), self-limit to the slim registration
96
+ path from (2) automatically, so no `piChild.extensions` edit is required.
97
+
98
+ Preference: (3) if pi-taskflow exposes a detectable child signal, else (2) plus a
99
+ short README note. Coordinate the child-detection signal with `pi-taskflow`.
100
+
101
+ ## Acceptance criteria
102
+
103
+ - [ ] `taskflow action=run` with an agent pinned to a proxied model succeeds on a
104
+ clean setup (no manual `piChild.extensions` edit), OR README documents the
105
+ required allowlist entry.
106
+ - [ ] Child model registration does not perform blocking network fetches under
107
+ `resourceProfile: allowlist` (uses discovery cache).
108
+ - [ ] Child startup overhead from this extension is negligible per spawn.
109
+ - [ ] Revert the user-level workaround once shipped.
package/index.ts CHANGED
@@ -15,6 +15,8 @@
15
15
  */
16
16
 
17
17
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
18
+ import fs from "node:fs";
19
+ import path from "node:path";
18
20
 
19
21
  import { applyAll } from "./src/apply.ts";
20
22
  import { readDiscoveryCache } from "./src/cache.ts";
@@ -24,8 +26,13 @@ import { detectConflicts } from "./src/conflicts.ts";
24
26
  import { fetchDiscovery } from "./src/fetch-models.ts";
25
27
  import type { ProxyConfig } from "./src/config.ts";
26
28
  import type { UsageDocument } from "./src/fetch-usage.ts";
27
- import { fetchUsage } from "./src/fetch-usage.ts";
28
- import { log } from "./src/log.ts";
29
+ import {
30
+ fetchUsage,
31
+ lastUsageContract,
32
+ lastUsageSource,
33
+ PREFERRED_CONTRACT,
34
+ } from "./src/fetch-usage.ts";
35
+ import { log, setLogSink } from "./src/log.ts";
29
36
  import {
30
37
  isUsageFresh,
31
38
  readUsageCache,
@@ -42,6 +49,24 @@ const QUOTA_STATUS_KEY = "0quota";
42
49
  * shared file cache is stale (prevents burst fetches during rapid turns). */
43
50
  const TURN_FETCH_DEBOUNCE_MS = 5_000;
44
51
 
52
+ /** Guards the legacy-source warning so it appears once per session. */
53
+ let legacyUsageWarned = false;
54
+
55
+ /** Where an operator learns how to install or update the bridge plugin. */
56
+ const BRIDGE_DOCS_URL = "https://github.com/abix5/pi-cliproxyapi#pi-bridge";
57
+
58
+ /** Pi's taskflow children run in JSON/print mode and need providers only. */
59
+ export function isHeadlessRun(argv = process.argv): boolean {
60
+ const modeIndex = argv.indexOf("--mode");
61
+ const mode = modeIndex >= 0 ? argv[modeIndex + 1] : undefined;
62
+ return (
63
+ mode === "json" ||
64
+ mode === "print" ||
65
+ argv.includes("-p") ||
66
+ argv.includes("--print")
67
+ );
68
+ }
69
+
45
70
  /**
46
71
  * Fetch usage data through the shared file cache: if the on-disk cache is
47
72
  * fresh (within TTL), return it without any network call; otherwise acquire
@@ -75,6 +100,63 @@ async function loadUsageCached(
75
100
  }
76
101
  }
77
102
 
103
+ /**
104
+ * Refresh discovery over the network after the cached copy was applied.
105
+ *
106
+ * The extension handle captured at startup becomes invalid once pi replaces or
107
+ * reloads the session, so a slow refresh that finishes afterwards must not try
108
+ * to register providers with it. That case is expected, not an error.
109
+ */
110
+ async function revalidateDiscovery(
111
+ pi: ExtensionAPI,
112
+ cfg: ProxyConfig,
113
+ resolvedKey: string,
114
+ ): Promise<void> {
115
+ try {
116
+ const fresh = await fetchDiscovery(cfg, resolvedKey);
117
+ await applyAll(pi, cfg, fresh);
118
+ log.debug("discovery revalidated from network");
119
+ } catch (e) {
120
+ const message = (e as Error).message ?? "";
121
+ if (message.includes("stale after session replacement")) {
122
+ log.debug("discovery revalidate skipped: session was replaced");
123
+ return;
124
+ }
125
+ log.warn("background discovery revalidate failed:", message);
126
+ }
127
+ }
128
+
129
+ /** Warn once per session when quota still comes from a pre-contract source, so
130
+ * a deprecated path is visible rather than silently permanent. */
131
+ function warnIfLegacyUsageSource(ui: {
132
+ notify(message: string, level: "info" | "warning" | "error"): void;
133
+ }): void {
134
+ if (legacyUsageWarned) return;
135
+ const source = lastUsageSource();
136
+ const contract = lastUsageContract();
137
+ if (source === null) return;
138
+
139
+ if (source === "sidecar") {
140
+ legacyUsageWarned = true;
141
+ ui.notify(
142
+ "quota is served by the legacy pi-cliproxyapi-wellknown sidecar. " +
143
+ "Install the pi-bridge plugin in CLIProxyAPI to use your normal API key " +
144
+ `and drop proxy.usageKey: ${BRIDGE_DOCS_URL}`,
145
+ "warning",
146
+ );
147
+ return;
148
+ }
149
+ if (contract !== null && contract < PREFERRED_CONTRACT) {
150
+ legacyUsageWarned = true;
151
+ ui.notify(
152
+ `the pi-bridge plugin answered with contract v${contract}; this extension ` +
153
+ `prefers v${PREFERRED_CONTRACT}. Quota still works, but update the plugin ` +
154
+ `in CLIProxyAPI for cache and account details: ${BRIDGE_DOCS_URL}`,
155
+ "warning",
156
+ );
157
+ }
158
+ }
159
+
78
160
  /** Update the quota status segment for the current model. No-op if the model
79
161
  * has no quota windows (e.g. a custom provider) or if usage is unavailable. */
80
162
  async function refreshQuotaStatus(
@@ -93,10 +175,6 @@ async function refreshQuotaStatus(
93
175
  ui.setStatus(QUOTA_STATUS_KEY, undefined);
94
176
  return;
95
177
  }
96
- if (!resolvedUsageKey) {
97
- ui.setStatus(QUOTA_STATUS_KEY, undefined);
98
- return;
99
- }
100
178
  const doc = await loadUsageCached(cfg, resolvedUsageKey, opts);
101
179
  if (!doc) {
102
180
  ui.setStatus(QUOTA_STATUS_KEY, undefined);
@@ -106,8 +184,52 @@ async function refreshQuotaStatus(
106
184
  ui.setStatus(QUOTA_STATUS_KEY, rendered ?? undefined);
107
185
  }
108
186
 
187
+ /**
188
+ * True when THIS module is the globally-installed copy (its file lives under a
189
+ * `node_modules` tree), as opposed to a working-tree checkout.
190
+ */
191
+ function isInstalledCopy(): boolean {
192
+ try {
193
+ return import.meta.url.includes("/node_modules/");
194
+ } catch {
195
+ return false;
196
+ }
197
+ }
198
+
199
+ /**
200
+ * True when the current project is a dev checkout of this extension that loads
201
+ * its own working-tree source through `.pi/extensions/cliproxyapi.ts`.
202
+ */
203
+ function localDevLoaderPresent(cwd: string): boolean {
204
+ try {
205
+ return (
206
+ fs.existsSync(path.join(cwd, ".pi", "extensions", "cliproxyapi.ts")) &&
207
+ fs.existsSync(path.join(cwd, "src", "fetch-usage.ts"))
208
+ );
209
+ } catch {
210
+ return false;
211
+ }
212
+ }
213
+
109
214
  export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
110
- registerCommands(pi);
215
+ // Mode guard: inside this extension's own checkout the project-local loader
216
+ // already supplies the working-tree source. If the published package is also
217
+ // installed globally, both copies would load in one process and register the
218
+ // same providers twice, so the installed copy stands down and the dev source
219
+ // wins.
220
+ if (isInstalledCopy() && localDevLoaderPresent(process.cwd())) {
221
+ return;
222
+ }
223
+
224
+ const headless = isHeadlessRun();
225
+ if (!headless) registerCommands(pi);
226
+
227
+ // Route later messages through pi's notification channel. Startup runs before
228
+ // any session exists, so those messages have no UI to reach and are kept off
229
+ // the terminal instead (see log.ts).
230
+ pi.on("session_start", (_event, ctx) => {
231
+ setLogSink(ctx.hasUI ? ctx.ui : null);
232
+ });
111
233
 
112
234
  const cfg = loadConfig();
113
235
  const resolvedKey = resolveConfigValue(cfg.proxy.apiKey);
@@ -118,9 +240,11 @@ export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
118
240
  return;
119
241
  }
120
242
 
121
- // Conflict scan is read-only and cheap; do it once at startup.
122
- const conflicts = detectConflicts(cfg);
123
- for (const c of conflicts) log.warn(`conflict (${c.kind}): ${c.detail}`);
243
+ // Conflict scanning only feeds the interactive diagnostics UI.
244
+ if (!headless) {
245
+ const conflicts = detectConflicts(cfg);
246
+ for (const c of conflicts) log.warn(`conflict (${c.kind}): ${c.detail}`);
247
+ }
124
248
 
125
249
  try {
126
250
  const cached = readDiscoveryCache();
@@ -132,18 +256,17 @@ export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
132
256
  `discovery from cache (age ${Math.round(cached.ageMs / 1000)}s): ${cached.discovery.builtinProviders.length} builtin, ${cached.discovery.customPool.length} custom`,
133
257
  );
134
258
  await applyAll(pi, cfg, cached.discovery);
135
- void (async () => {
136
- try {
137
- const fresh = await fetchDiscovery(cfg, resolvedKey);
138
- await applyAll(pi, cfg, fresh);
139
- log.debug("discovery revalidated from network");
140
- } catch (e) {
141
- log.warn(
142
- "background discovery revalidate failed:",
143
- (e as Error).message,
144
- );
145
- }
146
- })();
259
+ if (!headless) {
260
+ // Revalidate in the background, but bind the work to the session
261
+ // that started it: pi invalidates the extension handle when the
262
+ // session is replaced or reloaded, and using a captured handle
263
+ // afterwards throws.
264
+ void revalidateDiscovery(pi, cfg, resolvedKey);
265
+ }
266
+ } else if (headless) {
267
+ log.warn(
268
+ "discovery cache missing in headless run — no providers registered",
269
+ );
147
270
  } else {
148
271
  const discovery = await fetchDiscovery(cfg, resolvedKey);
149
272
  await applyAll(pi, cfg, discovery);
@@ -153,7 +276,7 @@ export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
153
276
  // Commands stay registered; user can open /cliproxy and press r to refresh.
154
277
  }
155
278
 
156
- if (cfg.refreshIntervalMinutes > 0) {
279
+ if (!headless && cfg.refreshIntervalMinutes > 0) {
157
280
  const ms = cfg.refreshIntervalMinutes * 60_000;
158
281
  setInterval(() => {
159
282
  void (async () => {
@@ -178,14 +301,19 @@ export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
178
301
  // model's provider only (anthropic→claude, openai→codex, custom→hidden).
179
302
  // The shared file cache ensures multiple Pi instances don't fetch more than
180
303
  // once every 2 minutes.
181
- const resolvedUsageKey = resolveConfigValue(cfg.proxy.usageKey);
182
- if (resolvedUsageKey) {
304
+ const resolvedUsageKey = headless
305
+ ? ""
306
+ : resolveConfigValue(cfg.proxy.usageKey);
307
+ // Quota is available through the pi-bridge plugin (ordinary API key) or the
308
+ // legacy sidecar (separate usage key), so either credential enables it.
309
+ if (resolvedUsageKey || cfg.proxy.apiKey) {
183
310
  let lastTurnFetchMs = 0;
184
311
 
185
312
  // session_start: render immediately from cache (no fetch needed if fresh).
186
313
  pi.on("session_start", async (_event, ctx) => {
187
314
  if (!ctx.hasUI) return;
188
315
  await refreshQuotaStatus(cfg, resolvedUsageKey, ctx.ui, ctx.model);
316
+ warnIfLegacyUsageSource(ctx.ui);
189
317
  });
190
318
 
191
319
  // model_select: re-render for the new provider. Read from cache so the
package/package.json CHANGED
@@ -1,39 +1,40 @@
1
1
  {
2
- "name": "pi-cliproxyapi",
3
- "version": "0.3.5",
4
- "type": "module",
5
- "description": "Pi extension for corporate management of model providers via a single CliProxyAPI endpoint",
6
- "license": "MIT",
7
- "repository": {
8
- "type": "git",
9
- "url": "git+https://github.com/abix5/pi-cliproxyapi.git"
10
- },
11
- "files": [
12
- "index.ts",
13
- "src",
14
- "docs",
15
- "README.md"
16
- ],
17
- "pi": {
18
- "extensions": [
19
- "./"
20
- ]
21
- },
22
- "keywords": [
23
- "pi-package",
24
- "pi-extension",
25
- "cliproxyapi"
26
- ],
27
- "scripts": {
28
- "typecheck": "tsc --noEmit",
29
- "check:migration": "node --disable-warning=ExperimentalWarning --experimental-strip-types scripts/check-config-migration.ts"
30
- },
31
- "peerDependencies": {
32
- "@earendil-works/pi-ai": "*",
33
- "@earendil-works/pi-coding-agent": "*",
34
- "@earendil-works/pi-tui": "*"
35
- },
36
- "devDependencies": {
37
- "typescript": "^5.6.0"
38
- }
2
+ "name": "pi-cliproxyapi",
3
+ "version": "0.4.1",
4
+ "type": "module",
5
+ "description": "Pi extension for corporate management of model providers via a single CliProxyAPI endpoint",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/abix5/pi-cliproxyapi.git"
10
+ },
11
+ "files": [
12
+ "index.ts",
13
+ "src",
14
+ "docs",
15
+ "README.md"
16
+ ],
17
+ "pi": {
18
+ "extensions": [
19
+ "./"
20
+ ]
21
+ },
22
+ "keywords": [
23
+ "pi-package",
24
+ "pi-extension",
25
+ "cliproxyapi"
26
+ ],
27
+ "scripts": {
28
+ "typecheck": "tsc --noEmit",
29
+ "check:migration": "node --disable-warning=ExperimentalWarning --experimental-strip-types scripts/check-config-migration.ts",
30
+ "check:child": "node --disable-warning=ExperimentalWarning --experimental-strip-types tests/headless-child.ts"
31
+ },
32
+ "peerDependencies": {
33
+ "@earendil-works/pi-ai": "*",
34
+ "@earendil-works/pi-coding-agent": "*",
35
+ "@earendil-works/pi-tui": "*"
36
+ },
37
+ "devDependencies": {
38
+ "typescript": "^5.6.0"
39
+ }
39
40
  }
package/src/config.ts CHANGED
@@ -22,7 +22,7 @@
22
22
  // "discoveryExcludes": ["*:*"],
23
23
  // "overrides": {},
24
24
  // "refreshIntervalMinutes": 0,
25
- // "usageCacheTtlMs": 30000
25
+ // "usageCacheTtlMs": 15000
26
26
  // }
27
27
 
28
28
  import { execSync } from "node:child_process";
@@ -143,7 +143,7 @@ const DEFAULT_CONFIG: ProxyConfig = {
143
143
  discoveryExcludes: ["*:*"],
144
144
  overrides: {},
145
145
  refreshIntervalMinutes: 0,
146
- usageCacheTtlMs: 30_000,
146
+ usageCacheTtlMs: 15_000,
147
147
  };
148
148
 
149
149
  export function loadConfig(): ProxyConfig {
@@ -17,11 +17,25 @@ import {
17
17
  normalizeSuggestedProvider,
18
18
  reasoningFromId,
19
19
  } from "./compat.ts";
20
+ import { readFileSync } from "node:fs";
21
+
20
22
  import { writeDiscoveryCache } from "./cache.ts";
21
23
  import type { ProxyConfig } from "./config.ts";
24
+ import { resolveConfigValue } from "./config.ts";
25
+ import { CONTRACT_HEADER, PREFERRED_CONTRACT } from "./fetch-usage.ts";
22
26
  import { log } from "./log.ts";
23
27
 
24
- export const PLUGIN_USER_AGENT = "pi-cliproxyapi/0.3.5";
28
+ /** Extension version, read from the manifest so there is one source of truth. */
29
+ export const PLUGIN_VERSION: string = (() => {
30
+ try {
31
+ const manifest = new URL("../package.json", import.meta.url);
32
+ return JSON.parse(readFileSync(manifest, "utf8")).version ?? "unknown";
33
+ } catch {
34
+ return "unknown";
35
+ }
36
+ })();
37
+
38
+ export const PLUGIN_USER_AGENT = `pi-cliproxyapi/${PLUGIN_VERSION}`;
25
39
  const REQUEST_TIMEOUT_MS = 5_000;
26
40
 
27
41
  export interface DiscoveryModelEntry {
@@ -87,40 +101,96 @@ async function fetchWithTimeout(
87
101
  }
88
102
  }
89
103
 
90
- function discoveryUrl(endpoint: string): string {
91
- return new URL("/.well-known/pi", new URL(endpoint).origin).toString();
104
+ /** Origin of the proxy endpoint, or null when it is not a usable URL. */
105
+ function endpointOrigin(endpoint: string): string | null {
106
+ try {
107
+ return new URL(endpoint).origin;
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+
113
+ function discoveryUrl(endpoint: string): string | null {
114
+ const origin = endpointOrigin(endpoint);
115
+ return origin ? new URL("/.well-known/pi", origin).toString() : null;
92
116
  }
93
117
 
118
+ /** Model catalogue served by the pi-bridge plugin inside CLIProxyAPI. */
119
+ const PLUGIN_DISCOVERY_PATH = "/v0/resource/plugins/pi-bridge/well-known";
120
+ /** Path used while the plugin was in testing; kept for older deployments. */
121
+ const PLUGIN_DISCOVERY_PATH_LEGACY =
122
+ "/v0/resource/plugins/pi-bridge/dev/well-known";
123
+
94
124
  // --------------------------------------------------------------------------- well-known path
95
125
 
126
+ /**
127
+ * Fetch the model catalogue.
128
+ *
129
+ * The pi-bridge plugin is preferred: it authenticates with the API key already
130
+ * configured for model calls and answers the newest contract. A deployment
131
+ * still running the standalone sidecar has no such route, so the legacy
132
+ * unauthenticated path remains as a fallback.
133
+ */
96
134
  async function tryWellKnown(cfg: ProxyConfig): Promise<Discovery | null> {
97
- const url = discoveryUrl(cfg.proxy.endpoint);
135
+ const origin = endpointOrigin(cfg.proxy.endpoint);
136
+ if (!origin) {
137
+ log.warn(`proxy.endpoint is not a valid URL: ${cfg.proxy.endpoint}`);
138
+ return null;
139
+ }
140
+
141
+ const apiKey = cfg.proxy.apiKey ? resolveConfigValue(cfg.proxy.apiKey) : "";
142
+ if (apiKey) {
143
+ const headers = {
144
+ Authorization: `Bearer ${apiKey}`,
145
+ [CONTRACT_HEADER]: String(PREFERRED_CONTRACT),
146
+ };
147
+ for (const path of [PLUGIN_DISCOVERY_PATH, PLUGIN_DISCOVERY_PATH_LEGACY]) {
148
+ const viaPlugin = await tryDiscoverySource(
149
+ cfg,
150
+ new URL(path, origin).toString(),
151
+ headers,
152
+ "pi-bridge",
153
+ );
154
+ if (viaPlugin) return viaPlugin;
155
+ }
156
+ }
157
+
158
+ const legacy = discoveryUrl(cfg.proxy.endpoint);
159
+ return legacy ? tryDiscoverySource(cfg, legacy, {}, "well-known") : null;
160
+ }
161
+
162
+ async function tryDiscoverySource(
163
+ cfg: ProxyConfig,
164
+ url: string,
165
+ extraHeaders: Record<string, string>,
166
+ label: string,
167
+ ): Promise<Discovery | null> {
98
168
  let resp: Response;
99
169
  try {
100
170
  resp = await fetchWithTimeout(url, {
101
- headers: { "User-Agent": PLUGIN_USER_AGENT, Accept: "application/json" },
171
+ headers: {
172
+ ...extraHeaders,
173
+ "User-Agent": PLUGIN_USER_AGENT,
174
+ Accept: "application/json",
175
+ },
102
176
  });
103
177
  } catch (err) {
104
- log.warn(
105
- "well-known fetch failed:",
106
- (err as Error).message,
107
- "— falling back to /v1/models",
108
- );
178
+ log.debug(`${label} fetch failed:`, (err as Error).message);
109
179
  return null;
110
180
  }
111
181
  if (!resp.ok) {
112
- log.warn(`well-known returned ${resp.status} — falling back to /v1/models`);
182
+ log.debug(`${label} returned ${resp.status}`);
113
183
  return null;
114
184
  }
115
185
  let body: any;
116
186
  try {
117
187
  body = await resp.json();
118
188
  } catch {
119
- log.warn("well-known returned non-JSON — falling back to /v1/models");
189
+ log.debug(`${label} returned non-JSON`);
120
190
  return null;
121
191
  }
122
192
  if (!body || body.schemaVersion !== 1) {
123
- log.warn("well-known schemaVersion != 1 — falling back to /v1/models");
193
+ log.debug(`${label} schemaVersion != 1`);
124
194
  return null;
125
195
  }
126
196
 
@@ -166,10 +236,14 @@ async function tryWellKnown(cfg: ProxyConfig): Promise<Discovery | null> {
166
236
 
167
237
  return {
168
238
  source: "well-known",
239
+ // The sidecar only ever filled lproxy.upstreamVersion, and with null at
240
+ // that; the bridge reports the real proxy version under upstream.
169
241
  upstreamVersion:
170
242
  typeof body?.upstream?.upstreamVersion === "string"
171
243
  ? body.upstream.upstreamVersion
172
- : null,
244
+ : typeof body?.lproxy?.upstreamVersion === "string"
245
+ ? body.lproxy.upstreamVersion
246
+ : null,
173
247
  builtinProviders: builtin,
174
248
  customPool,
175
249
  serverDiscoveryExcludes: Array.isArray(body.discoveryExcludes)
@@ -190,10 +264,11 @@ async function fetchRawModels(
190
264
  cfg: ProxyConfig,
191
265
  resolvedKey: string,
192
266
  ): Promise<RawUpstreamModel[]> {
193
- const url = new URL(
194
- "/v1/models",
195
- new URL(cfg.proxy.endpoint).origin,
196
- ).toString();
267
+ const origin = endpointOrigin(cfg.proxy.endpoint);
268
+ if (!origin) {
269
+ throw new Error(`proxy.endpoint is not a valid URL: ${cfg.proxy.endpoint}`);
270
+ }
271
+ const url = new URL("/v1/models", origin).toString();
197
272
  const resp = await fetchWithTimeout(url, {
198
273
  headers: {
199
274
  Authorization: `Bearer ${resolvedKey}`,
@@ -1,14 +1,39 @@
1
- // /api/usage client.
1
+ // Usage client.
2
2
  //
3
- // GET <host>/api/usage with X-Plugin-Key. Returns the parsed document, with a
4
- // small in-memory TTL cache. Caller passes `force: true` to bypass the cache.
3
+ // Quota comes from one of two sources:
4
+ //
5
+ // - the pi-bridge plugin inside CLIProxyAPI, authenticated with the ordinary
6
+ // API key already used for model calls, or
7
+ // - the legacy standalone sidecar at /api/usage, authenticated with a
8
+ // separate usage key.
9
+ //
10
+ // The plugin is preferred and probed first; the sidecar remains supported so a
11
+ // server can be migrated without changing the client in lockstep. Results are
12
+ // cached in memory; callers pass `force: true` to bypass it.
5
13
 
6
14
  import type { ProxyConfig } from "./config.ts";
15
+ import { resolveConfigValue } from "./config.ts";
7
16
  import { PLUGIN_USER_AGENT } from "./fetch-models.ts";
8
17
  import { log } from "./log.ts";
9
18
 
10
19
  const REQUEST_TIMEOUT_MS = 15_000;
11
20
 
21
+ /** Response contract this client is written against. */
22
+ export const PREFERRED_CONTRACT = 2;
23
+
24
+ /** Header the bridge reads to select a contract, and echoes back. */
25
+ export const CONTRACT_HEADER = "X-Pi-Contract";
26
+
27
+ /** Routes served by the pi-bridge plugin inside CLIProxyAPI. */
28
+ const PLUGIN_BASE = "/v0/resource/plugins/pi-bridge";
29
+ const PLUGIN_USAGE_PATH = `${PLUGIN_BASE}/usage`;
30
+ /** Path used while the plugin was in testing; kept for older deployments. */
31
+ const PLUGIN_USAGE_PATH_LEGACY = `${PLUGIN_BASE}/dev/usage`;
32
+ const SIDECAR_USAGE_PATH = "/api/usage";
33
+
34
+ /** Where a usage document came from. */
35
+ export type UsageSource = "plugin" | "sidecar";
36
+
12
37
  export interface UsageGroup {
13
38
  id: string;
14
39
  label: string;
@@ -38,11 +63,17 @@ export interface UsageDocument {
38
63
  generatedAt: string;
39
64
  accounts: UsageAccount[];
40
65
  unsupportedProviders: string[];
66
+ /** Contract v2 only: server-side cache provenance. */
67
+ cache?: { updatedAt: string; stale: boolean; ttlMs: number };
68
+ /** Contract v2 only: which key the server authenticated. */
69
+ client?: { keyHint: string };
41
70
  }
42
71
 
43
72
  interface CacheEntry {
44
73
  fetchedAt: number;
45
74
  doc: UsageDocument;
75
+ source: UsageSource;
76
+ contract: number;
46
77
  }
47
78
 
48
79
  let cache: CacheEntry | null = null;
@@ -51,6 +82,47 @@ export function clearUsageCache(): void {
51
82
  cache = null;
52
83
  }
53
84
 
85
+ /** Which source served the cached document, if any. */
86
+ export function lastUsageSource(): UsageSource | null {
87
+ return cache?.source ?? null;
88
+ }
89
+
90
+ /** Which contract the cached document was served under, if any. */
91
+ export function lastUsageContract(): number | null {
92
+ return cache?.contract ?? null;
93
+ }
94
+
95
+ async function getJSON(
96
+ url: string,
97
+ headers: Record<string, string>,
98
+ ): Promise<Response> {
99
+ const ctrl = new AbortController();
100
+ const timer = setTimeout(
101
+ () => ctrl.abort(new Error("timeout")),
102
+ REQUEST_TIMEOUT_MS,
103
+ );
104
+ try {
105
+ return await fetch(url, {
106
+ headers: {
107
+ ...headers,
108
+ Accept: "application/json",
109
+ "User-Agent": PLUGIN_USER_AGENT,
110
+ },
111
+ signal: ctrl.signal,
112
+ });
113
+ } finally {
114
+ clearTimeout(timer);
115
+ }
116
+ }
117
+
118
+ function parseUsage(body: unknown, origin: string): UsageDocument {
119
+ const doc = body as UsageDocument;
120
+ if (!doc || doc.schemaVersion !== 1 || !Array.isArray(doc.accounts)) {
121
+ throw new Error(`${origin} returned unexpected payload shape`);
122
+ }
123
+ return doc;
124
+ }
125
+
54
126
  export async function fetchUsage(
55
127
  cfg: ProxyConfig,
56
128
  resolvedUsageKey: string,
@@ -63,41 +135,94 @@ export async function fetchUsage(
63
135
  ) {
64
136
  return cache.doc;
65
137
  }
138
+
139
+ let origin: string;
140
+ try {
141
+ origin = new URL(cfg.proxy.endpoint).origin;
142
+ } catch {
143
+ throw new Error(`proxy.endpoint is not a valid URL: ${cfg.proxy.endpoint}`);
144
+ }
145
+ // The key may be a `!command` reference, so it must be resolved before use.
146
+ const apiKey = cfg.proxy.apiKey ? resolveConfigValue(cfg.proxy.apiKey) : "";
147
+
148
+ // Preferred path: the plugin, using the key already configured for models.
149
+ if (apiKey) {
150
+ try {
151
+ const { doc, contract } = await fetchFromPlugin(origin, apiKey);
152
+ cache = { fetchedAt: Date.now(), doc, source: "plugin", contract };
153
+ log.debug(
154
+ `usage fetched from plugin (contract v${contract}), accounts:`,
155
+ doc.accounts.length,
156
+ );
157
+ return doc;
158
+ } catch (err) {
159
+ // Fall back only when a usage key exists; otherwise surface the error
160
+ // rather than silently reporting "no quota configured".
161
+ if (!resolvedUsageKey) throw err;
162
+ log.debug("plugin usage unavailable, falling back to sidecar:", err);
163
+ }
164
+ }
165
+
66
166
  if (!resolvedUsageKey) {
67
167
  throw new Error(
68
- "usage key not configured; set proxy.usageKey in config and rerun",
168
+ "no usage source available: set proxy.apiKey for the pi-bridge plugin, or proxy.usageKey for the legacy sidecar",
69
169
  );
70
170
  }
71
- const url = new URL(
72
- "/api/usage",
73
- new URL(cfg.proxy.endpoint).origin,
74
- ).toString();
75
- const ctrl = new AbortController();
76
- const timer = setTimeout(
77
- () => ctrl.abort(new Error("timeout")),
78
- REQUEST_TIMEOUT_MS,
171
+
172
+ const doc = await fetchFromSidecar(origin, resolvedUsageKey);
173
+ // The sidecar predates contracts and only ever served the v1 shape.
174
+ cache = { fetchedAt: Date.now(), doc, source: "sidecar", contract: 1 };
175
+ log.debug("usage fetched from sidecar, accounts:", doc.accounts.length);
176
+ return doc;
177
+ }
178
+
179
+ /**
180
+ * Ask the bridge for the newest contract this client understands.
181
+ *
182
+ * A bridge that predates contracts ignores the header and answers with the v1
183
+ * document; it is detected by the absent echo, and its response is used as-is.
184
+ * That keeps a new client working against an old bridge without a second
185
+ * round-trip or a version probe.
186
+ */
187
+ async function fetchFromPlugin(
188
+ origin: string,
189
+ apiKey: string,
190
+ ): Promise<{ doc: UsageDocument; contract: number }> {
191
+ const headers = {
192
+ Authorization: `Bearer ${apiKey}`,
193
+ [CONTRACT_HEADER]: String(PREFERRED_CONTRACT),
194
+ };
195
+
196
+ let resp = await getJSON(
197
+ new URL(PLUGIN_USAGE_PATH, origin).toString(),
198
+ headers,
79
199
  );
80
- let resp: Response;
81
- try {
82
- resp = await fetch(url, {
83
- headers: {
84
- "X-Plugin-Key": resolvedUsageKey,
85
- Accept: "application/json",
86
- "User-Agent": PLUGIN_USER_AGENT,
87
- },
88
- signal: ctrl.signal,
89
- });
90
- } finally {
91
- clearTimeout(timer);
200
+ if (resp.status === 404) {
201
+ // Older bridge: only the testing path exists.
202
+ resp = await getJSON(
203
+ new URL(PLUGIN_USAGE_PATH_LEGACY, origin).toString(),
204
+ headers,
205
+ );
92
206
  }
93
207
  if (!resp.ok) {
94
- throw new Error(`/api/usage returned ${resp.status}`);
208
+ throw new Error(`pi-bridge usage returned ${resp.status}`);
95
209
  }
96
- const body = (await resp.json()) as UsageDocument;
97
- if (!body || body.schemaVersion !== 1 || !Array.isArray(body.accounts)) {
98
- throw new Error("/api/usage returned unexpected payload shape");
210
+
211
+ const doc = parseUsage(await resp.json(), "pi-bridge usage");
212
+ const echoed = Number.parseInt(resp.headers.get(CONTRACT_HEADER) ?? "", 10);
213
+ const contract = Number.isNaN(echoed) ? 1 : echoed;
214
+ return { doc, contract };
215
+ }
216
+
217
+ async function fetchFromSidecar(
218
+ origin: string,
219
+ usageKey: string,
220
+ ): Promise<UsageDocument> {
221
+ const resp = await getJSON(new URL(SIDECAR_USAGE_PATH, origin).toString(), {
222
+ "X-Plugin-Key": usageKey,
223
+ });
224
+ if (!resp.ok) {
225
+ throw new Error(`/api/usage returned ${resp.status}`);
99
226
  }
100
- cache = { fetchedAt: Date.now(), doc: body };
101
- log.debug("usage fetched, accounts:", body.accounts.length);
102
- return body;
227
+ return parseUsage(await resp.json(), "/api/usage");
103
228
  }
package/src/log.ts CHANGED
@@ -1,32 +1,85 @@
1
- // Tiny logger that prefixes all messages with the extension tag.
2
- // Uses console.* directly — pi pipes stdout/stderr into its log sink.
1
+ // Extension logging.
3
2
  //
4
- // While an interactive overlay is open, console output corrupts the TUI (it
5
- // prints over the box and forces a redraw below it — stacking headers). The
6
- // overlay code wraps its lifetime in setLogQuiet(true) to mute us; user-facing
7
- // results are surfaced inside the overlay instead.
3
+ // pi has no log sink for extensions: console.* writes straight to the terminal,
4
+ // so anything printed during a session lands on top of the live TUI and
5
+ // corrupts it. Messages the user needs to see go through ctx.ui.notify, which
6
+ // pi renders as a proper [Warning]/[Error] line; the rest are dropped unless
7
+ // debugging is explicitly enabled.
8
8
 
9
9
  const TAG = "[pi-cliproxyapi]";
10
10
 
11
+ type Level = "info" | "warning" | "error";
12
+
13
+ interface NotifySink {
14
+ notify(message: string, type?: Level): void;
15
+ }
16
+
11
17
  let quiet = false;
18
+ let sink: NotifySink | null = null;
12
19
 
13
- /** Mute/unmute all console output (used around interactive overlays). */
20
+ /** Mute/unmute output (used around interactive overlays). */
14
21
  export function setLogQuiet(v: boolean): void {
15
22
  quiet = v;
16
23
  }
17
24
 
25
+ /**
26
+ * Route user-facing messages through pi's notification channel.
27
+ *
28
+ * Called once a UI context exists. Without a sink — print mode, JSON mode, or
29
+ * before the first event — printing is safe because there is no TUI to damage.
30
+ */
31
+ export function setLogSink(next: NotifySink | null): void {
32
+ sink = next;
33
+ }
34
+
35
+ /** Explicit opt-in for verbose terminal output when diagnosing a live session. */
36
+ function verbose(): boolean {
37
+ return !!process.env.PI_CLIPROXYAPI_DEBUG;
38
+ }
39
+
40
+ function format(args: unknown[]): string {
41
+ return args
42
+ .map((a) => {
43
+ if (typeof a === "string") return a;
44
+ if (a instanceof Error) return a.message;
45
+ try {
46
+ return JSON.stringify(a);
47
+ } catch {
48
+ return String(a);
49
+ }
50
+ })
51
+ .join(" ");
52
+ }
53
+
54
+ function emit(level: Level, args: unknown[]): void {
55
+ if (quiet) return;
56
+ const message = format(args);
57
+
58
+ if (sink) {
59
+ sink.notify(`${TAG} ${message}`, level);
60
+ return;
61
+ }
62
+ // No UI attached: safe to write to the terminal.
63
+ (level === "info" ? console.log : console.error)(TAG, message);
64
+ }
65
+
18
66
  export const log = {
67
+ /**
68
+ * Routine progress. These are the lines that used to litter the TUI, so
69
+ * they are only shown when explicitly debugging.
70
+ */
19
71
  info(...args: unknown[]): void {
20
- if (!quiet) console.log(TAG, ...args);
72
+ if (!verbose()) return;
73
+ emit("info", args);
21
74
  },
22
75
  warn(...args: unknown[]): void {
23
- if (!quiet) console.warn(TAG, ...args);
76
+ emit("warning", args);
24
77
  },
25
78
  error(...args: unknown[]): void {
26
- if (!quiet) console.error(TAG, ...args);
79
+ emit("error", args);
27
80
  },
28
81
  debug(...args: unknown[]): void {
29
- if (!quiet && process.env.PI_CLIPROXYAPI_DEBUG)
30
- console.log(TAG, "[debug]", ...args);
82
+ if (!verbose()) return;
83
+ emit("info", args);
31
84
  },
32
85
  };
package/src/ui-setup.ts CHANGED
@@ -1,4 +1,4 @@
1
- // First-run setup wizard: collects endpoint + apiKey + providerPrefix + (optional) usageKey
1
+ // First-run setup wizard: collects endpoint + apiKey + providerPrefix
2
2
  // and writes them to ~/.pi/agent/pi-cliproxyapi/config.json.
3
3
  //
4
4
  // All three fields support the same "!cmd" / "$ENV" / literal semantics as
@@ -64,11 +64,6 @@ const STEPS: WizardStep[] = [
64
64
  validate: (raw) =>
65
65
  /^[a-z0-9][a-z0-9-]*$/i.test(raw) ? null : "letters/digits/dashes only",
66
66
  },
67
- {
68
- label: "usageKey",
69
- hint: "Optional X-Plugin-Key for /api/usage. Leave blank to skip the Usage tab",
70
- required: false,
71
- },
72
67
  ];
73
68
 
74
69
  /**
@@ -96,7 +91,6 @@ export async function runSetup(
96
91
  endpoint: existing.proxy.endpoint ?? "",
97
92
  apiKey: existing.proxy.apiKey ?? "",
98
93
  providerPrefix: existing.proxy.providerPrefix ?? "",
99
- usageKey: existing.proxy.usageKey ?? "",
100
94
  };
101
95
 
102
96
  let cancelled = false;
@@ -141,8 +135,6 @@ export async function runSetup(
141
135
  apiKey: values.apiKey ?? "",
142
136
  providerPrefix: values.providerPrefix ?? "",
143
137
  };
144
- if (values.usageKey) next.proxy.usageKey = values.usageKey;
145
- else delete next.proxy.usageKey;
146
138
 
147
139
  saveConfig(next);
148
140
  ctx.ui.notify(`saved to ${CONFIG_PATH}`, "info");
@@ -28,8 +28,15 @@ import { log } from "./log.ts";
28
28
  export const USAGE_CACHE_PATH = join(CONFIG_DIR, "usage-cache.json");
29
29
  export const USAGE_LOCK_PATH = join(CONFIG_DIR, "usage-cache.lock");
30
30
 
31
- /** Minimum interval between network fetches, shared across all Pi instances. */
32
- export const USAGE_CACHE_TTL_MS = 120_000; // 2 minutes
31
+ /**
32
+ * Minimum interval between network fetches, shared across all Pi instances.
33
+ *
34
+ * This throttles calls to the bridge only, which are cheap: the bridge holds
35
+ * its own cache and is the only thing that talks to the providers, whose rate
36
+ * limits are the real constraint. So it can be short enough for the status line
37
+ * to react to a finished turn.
38
+ */
39
+ export const USAGE_CACHE_TTL_MS = 15_000;
33
40
  /** A lock file older than this is considered stale (process crashed). */
34
41
  const LOCK_STALE_MS = 30_000;
35
42