pi-cliproxyapi 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -81,17 +81,44 @@ 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
- `~/.config/pi-cliproxyapi/config.json` — created by `/cliproxy-setup`, editable by hand:
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.
87
114
 
88
115
  ```jsonc
89
116
  {
90
117
  "proxy": {
91
118
  "endpoint": "https://proxy.example.com/v1",
92
- "apiKey": "!cat ~/.config/pi-cliproxyapi/key",
119
+ "apiKey": "!cat ~/.pi/agent/pi-cliproxyapi/key",
93
120
  "providerPrefix": "corp",
94
- "usageKey": "!cat ~/.config/pi-cliproxyapi/usage-key"
121
+ "usageKey": "!cat ~/.pi/agent/pi-cliproxyapi/usage-key"
95
122
  },
96
123
  "builtinProviders": {
97
124
  "anthropic": { "enabled": true, "models": ["claude-opus-4-7"] },
@@ -106,7 +133,7 @@ Then run `/cliproxy-setup` to configure your proxy endpoint.
106
133
  }
107
134
  ```
108
135
 
109
- Values support `!command` (shell exec), `$ENV_VAR`, `~/path` (auto-wrapped to `!cat`), or literal strings.
136
+ Values support `!command` (shell exec), `$ENV_VAR`, or literal strings. The `/cliproxy-setup` wizard also accepts bare `~/path` values and saves them as `!cat` commands; when editing the file by hand, write the `!cat ~/path` form explicitly.
110
137
 
111
138
  ## Discovery
112
139
 
@@ -172,6 +199,7 @@ Then route `/.well-known/pi` and `/api/usage` on your public domain to port 3458
172
199
  ### Connecting the plugin
173
200
 
174
201
  Run `/cliproxy-setup` in Pi and enter:
202
+
175
203
  - **endpoint** — your public proxy URL ending with `/v1`
176
204
  - **apiKey** — CliProxyAPI bearer key
177
205
  - **providerPrefix** — short slug for custom provider names (e.g. `corp`, `myproxy`)
@@ -191,7 +219,7 @@ The sidecar is **optional for basic usage** — without it the plugin falls back
191
219
  ```
192
220
  index.ts ExtensionFactory entry point
193
221
  src/
194
- config.ts ~/.config/pi-cliproxyapi/config.json
222
+ config.ts ~/.pi/agent/pi-cliproxyapi/config.json
195
223
  commands.ts 2 slash commands (hub + setup)
196
224
  apply.ts pi.registerProvider calls
197
225
  fetch-models.ts well-known + /v1/models fallback
@@ -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
@@ -3,7 +3,7 @@
3
3
  * CliProxyAPI endpoint with one corporate key.
4
4
  *
5
5
  * On factory boot we:
6
- * 1. load ~/.config/pi-cliproxyapi/config.json (defaults if missing)
6
+ * 1. load ~/.pi/agent/pi-cliproxyapi/config.json (migrates legacy config; defaults if missing)
7
7
  * 2. fetch discovery (well-known → fall back to /v1/models)
8
8
  * 3. call pi.registerProvider for each enabled built-in + custom provider
9
9
  * 4. register slash commands /cliproxy and /cliproxy-setup
@@ -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,38 +1,40 @@
1
1
  {
2
- "name": "pi-cliproxyapi",
3
- "version": "0.3.4",
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
- },
30
- "peerDependencies": {
31
- "@earendil-works/pi-ai": "*",
32
- "@earendil-works/pi-coding-agent": "*",
33
- "@earendil-works/pi-tui": "*"
34
- },
35
- "devDependencies": {
36
- "typescript": "^5.6.0"
37
- }
2
+ "name": "pi-cliproxyapi",
3
+ "version": "0.4.0",
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
+ }
38
40
  }
package/src/config.ts CHANGED
@@ -1,13 +1,13 @@
1
- // ~/.config/pi-cliproxyapi/config.json — load, validate, persist.
1
+ // ~/.pi/agent/pi-cliproxyapi/config.json — migrate, load, validate, persist.
2
2
  //
3
3
  // Schema:
4
4
  //
5
5
  // {
6
6
  // "proxy": {
7
7
  // "endpoint": "https://your-proxy.example.com/v1",
8
- // "apiKey": "!cat ~/.config/pi-cliproxyapi/key",
8
+ // "apiKey": "!cat ~/.pi/agent/pi-cliproxyapi/key",
9
9
  // "providerPrefix": "myproxy",
10
- // "usageKey": "!cat ~/.config/pi-cliproxyapi/usage-key"
10
+ // "usageKey": "!cat ~/.pi/agent/pi-cliproxyapi/usage-key"
11
11
  // },
12
12
  // "builtinProviders": {
13
13
  // "openai": { "enabled": true, "apiOverride": null, "models": ["gpt-5.2"] },
@@ -26,16 +26,71 @@
26
26
  // }
27
27
 
28
28
  import { execSync } from "node:child_process";
29
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
29
+ import { randomUUID } from "node:crypto";
30
+ import {
31
+ constants,
32
+ copyFileSync,
33
+ existsSync,
34
+ linkSync,
35
+ mkdirSync,
36
+ readFileSync,
37
+ rmSync,
38
+ unlinkSync,
39
+ writeFileSync,
40
+ } from "node:fs";
30
41
  import { homedir } from "node:os";
31
42
  import { dirname, join } from "node:path";
43
+ import { fileURLToPath } from "node:url";
32
44
 
33
45
  import type { Api } from "@earendil-works/pi-ai";
34
46
 
35
47
  import { log } from "./log.ts";
36
48
 
37
- export const CONFIG_DIR = join(homedir(), ".config", "pi-cliproxyapi");
49
+ export const CONFIG_DIR = join(homedir(), ".pi", "agent", "pi-cliproxyapi");
38
50
  export const CONFIG_PATH = join(CONFIG_DIR, "config.json");
51
+ const LEGACY_CONFIG_PATH = join(
52
+ homedir(),
53
+ ".config",
54
+ "pi-cliproxyapi",
55
+ "config.json",
56
+ );
57
+
58
+ export function isLocalCheckout(): boolean {
59
+ return existsSync(
60
+ join(dirname(fileURLToPath(import.meta.url)), "..", ".git"),
61
+ );
62
+ }
63
+
64
+ export function migrateLegacyConfig(
65
+ legacyPath = LEGACY_CONFIG_PATH,
66
+ configPath = CONFIG_PATH,
67
+ localCheckout = isLocalCheckout(),
68
+ ): void {
69
+ if (existsSync(configPath) || !existsSync(legacyPath)) return;
70
+ let temporaryPath: string | undefined;
71
+ try {
72
+ mkdirSync(dirname(configPath), { recursive: true });
73
+ temporaryPath = `${configPath}.${process.pid}.${randomUUID()}.tmp`;
74
+ copyFileSync(legacyPath, temporaryPath, constants.COPYFILE_EXCL);
75
+ linkSync(temporaryPath, configPath);
76
+ rmSync(temporaryPath);
77
+ temporaryPath = undefined;
78
+ if (!localCheckout) unlinkSync(legacyPath);
79
+ log.info(
80
+ localCheckout ? "legacy config copied to" : "legacy config moved to",
81
+ configPath,
82
+ );
83
+ } catch (err) {
84
+ if (temporaryPath) {
85
+ try {
86
+ rmSync(temporaryPath, { force: true });
87
+ } catch (cleanupErr) {
88
+ log.warn("failed to clean temporary config:", cleanupErr);
89
+ }
90
+ }
91
+ log.warn("failed to migrate legacy config:", err);
92
+ }
93
+ }
39
94
 
40
95
  export interface BuiltinProviderConfig {
41
96
  enabled: boolean;
@@ -92,6 +147,7 @@ const DEFAULT_CONFIG: ProxyConfig = {
92
147
  };
93
148
 
94
149
  export function loadConfig(): ProxyConfig {
150
+ migrateLegacyConfig();
95
151
  if (!existsSync(CONFIG_PATH)) {
96
152
  log.info("config not found, using defaults at", CONFIG_PATH);
97
153
  return structuredClone(DEFAULT_CONFIG);
@@ -115,9 +171,7 @@ function normalizeConfig(raw: unknown): ProxyConfig {
115
171
  if (!raw || typeof raw !== "object") return structuredClone(DEFAULT_CONFIG);
116
172
  const r = raw as Record<string, unknown>;
117
173
  const merged = structuredClone(DEFAULT_CONFIG);
118
- const proxyBlock =
119
- (r.proxy as Record<string, unknown> | undefined) ??
120
- {};
174
+ const proxyBlock = (r.proxy as Record<string, unknown> | undefined) ?? {};
121
175
  merged.proxy.endpoint =
122
176
  typeof proxyBlock.endpoint === "string"
123
177
  ? proxyBlock.endpoint
@@ -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.3";
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
  };
@@ -23,7 +23,7 @@ import type { UsageAccount, UsageDocument, UsageGroup } from "./fetch-usage.ts";
23
23
  const GAUGE_ICON = "\u{F0627}";
24
24
 
25
25
  /** Braille fill chars, 8 levels (empty → full). */
26
- const BRAILLE = ["⡀", "⠂", "▌", "⣄", "⣤", "⣶", "⣷", "⣾"];
26
+ const BRAILLE = ["⡀", "⠂", "⣀", "⣄", "⣤", "⣶", "⣷", "⣾"];
27
27
 
28
28
  /**
29
29
  * Map a Pi provider name to the provider key used by the usage API.
package/src/ui-setup.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // First-run setup wizard: collects endpoint + apiKey + providerPrefix + (optional) usageKey
2
- // and writes them to ~/.config/pi-cliproxyapi/config.json.
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
5
5
  // the rest of the config (see resolveConfigValue). For convenience the wizard