@firstpick/pi-package-webui 0.11.0 → 0.11.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/DEVELOPMENT.md CHANGED
@@ -4,6 +4,12 @@ Contributor-only implementation, API, architecture, testing, and maintenance inf
4
4
 
5
5
  [Back to README](README.md) · [Advanced user technical reference](TECHNICAL.md)
6
6
 
7
+ ## Pi 1.2 theme compatibility
8
+
9
+ Bundled native theme JSON now uses `https://pi.dev/schemas/theme.schema.json`. Pi 1.2 rejects WebUI-only fields inside a native theme's `export` object at startup. The theme bundle publishes those fields separately in `webui-backgrounds.json`, outside its `pi.themes` directory. `readBundledThemes()` reads that optional file next to the themes directory and merges only `WEBUI_THEME_EXPORT_FIELDS` into catalog exports. Native export colors cannot be overridden by this metadata. Older bundles with inline background fields still load through the existing bundled-only compatibility path.
10
+
11
+ `tests/theme-contract.test.mjs` reads the published `schemas/theme.schema.json` first and falls back to the pre-1.2 schema location only on `ENOENT`. `tests/http-endpoints-harness.test.mjs` checks separate background metadata and rejects unrelated fields.
12
+
7
13
  ## Host-provided dependencies
8
14
 
9
15
  Declare `@earendil-works/pi-ai`, `@earendil-works/pi-coding-agent`, `@earendil-works/pi-tui`, and `typebox` as `peerDependencies` with a `"*"` range. Pi supplies them to extensions. Regular runtime dependencies can install duplicate Pi modules and trigger an extension warning. Keep versioned development dependencies for checkout tests and standalone CLI development, and regenerate the npm and Bun lockfiles after changing the manifest.
@@ -586,6 +592,30 @@ The browser negotiates `compact-v1` per EventSource connection (`outputMode=auto
586
592
 
587
593
  The included compact-mode metric measures deterministic post-parse serialized JSON byte-work only (`R + 2×S`) and semantic parity; it does not claim wall-clock improvement, lower DOM CPU, reduced network latency, or higher model token/s.
588
594
 
595
+ ### Codex subscription usage authentication
596
+
597
+ `lib/codex-usage-auth.mjs` resolves the legacy `openai-codex` credential first. If that login is absent or its provider no longer supports OAuth, it checks `openai` only when the runtime advertises subscription OAuth. A usable legacy login keeps precedence. Reads and lock-safe refreshes use the selected provider's storage key; the adapter never copies or migrates credentials and never resolves the unified OpenAI provider's API-key fallback for subscription usage. Login guidance follows the runtime's available subscription provider.
598
+
599
+ The new Sign in with ChatGPT flow stores `clientId` and scopes including `chatgpt.tokens.use.direct`. Those credentials target the public OpenAI API, not the existing `https://chatgpt.com/backend-api/wham/usage` fetcher. The adapter returns `unsupportedReason: "chatgpt-direct-token"` without refreshing or returning an access token. It repeats that check inside and after the credential lock to handle concurrent login changes. The legacy reader returns a sanitized `501` explanation before any backend request when given this direct-flow credential. The public usage route first tries Codex CLI and can succeed independently of Pi's login. Do not forward direct-flow tokens to ChatGPT backend endpoints; see [OpenAI's models and inference guidance](https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference).
600
+
601
+ `lib/codex-cli-usage.mjs` launches `codex app-server --listen stdio://` without a shell, normalizing standard Windows npm shims to Node plus the installed Codex entry point. Its JSONL session sends `initialize`, the `initialized` notification, `account/read` with `refreshToken: false`, and `account/rateLimits/read` with null params. Only a `chatgpt` account can reach the rate-limit read. It never starts threads or turns, starts login flows, consumes reset credits, or supplies credentials to unsolicited server requests. CLI-managed authentication may perform its own normal refresh.
602
+
603
+ The client bounds each stdout record to 1 MiB and total stdout and stderr to 4 MiB each. Stderr is drained but never retained or published. A 15-second overall deadline bounds the request sequence. Cleanup closes stdin, waits 300 ms, terminates the owned process tree if necessary, and waits another second before destroying pipes. Windows tree termination uses the existing bounded taskkill helper. A scoped parent-exit handler also terminates an in-flight child and is removed after cleanup. Only allowlisted, bounded quota windows, plan labels, bucket labels, and numeric credit balances survive the projection; raw account data and provider error bodies are discarded.
604
+
605
+ `lib/codex-usage-source.mjs` coalesces concurrent reads and caches successful normalized snapshots for 30 seconds. `?refresh=1` bypasses a completed cache but joins an in-flight check. CLI success returns `source: "codex-cli"` and does not resolve Pi authentication. CLI failure tries the existing legacy reader, whose `source: "chatgpt.com"` snapshot gains a static `sourceNotice`. When both fail, only sanitized CLI guidance and a generic fallback explanation reach the browser. The browser includes source and notice in its structural signature so equal-shaped results still redraw when the account source changes. It displays the CLI-account warning without trying to compare identities or infer equivalence with Pi's direct ChatGPT allowance.
606
+
607
+ Focused coverage includes provider compatibility, refresh and lock races, protocol framing, login-mode gating, secret stripping, read-only method sequences, malformed and oversized output, timeout, cancellation, process-tree cleanup, cache expiry and coalescing, source changes, and the actual HTTP route. `tests/fixtures/fake-codex-app-server.mjs` supplies deterministic peers without real authentication or inference. Run these from the package:
608
+
609
+ ```bash
610
+ node tests/codex-cli-usage.test.mjs
611
+ node tests/codex-usage-source.test.mjs
612
+ node tests/codex-usage-http.test.mjs
613
+ node tests/codex-usage-auth.test.mjs
614
+ node tests/mobile-static.test.mjs
615
+ ```
616
+
617
+ Protocol reference: [Codex App Server](https://developers.openai.com/codex/app-server). A live usage-only smoke check with Codex CLI 0.162.1 returned a subscription snapshot; no thread or model turn was created.
618
+
589
619
  ### Codex subscription Fast mode
590
620
 
591
621
  The optional `@firstpick/pi-extension-codex-fast-mode` companion adds `/fast-mode` and a **Normal / Fast / Ultrafast** selector under **Codex Usage**. Normal is the default and state is scoped to the active Pi session branch. The browser asks the extension to change mode and renders the extension-published `codex-fast-mode` status; it does not inspect ChatGPT credentials or rewrite provider requests itself.
package/README.md CHANGED
@@ -19,7 +19,7 @@ Pi Web UI keeps the normal Pi agent experience while giving you more room to man
19
19
  | --- | --- |
20
20
  | **Sessions and workspaces** | Run several isolated Pi sessions, resume prior work in a new terminal without replacing the current one, switch projects, preserve per-tab drafts, add another tab directly from the tab strip, and create branch worktrees. |
21
21
  | **Live agent work** | Follow streaming Markdown with syntax highlighting for code blocks, grouped consecutive thinking, tool output, queues, todo progress, managed agent runs, and direct agent-to-agent conversations without leaving the browser. |
22
- | **Models and controls** | Change models and thinking effort, manage scoped models, configure tools and skills, and use the command palette. |
22
+ | **Models and controls** | Change models and thinking effort, check Codex CLI subscription usage, manage scoped models, configure tools and skills, and use the command palette. |
23
23
  | **Files and prompts** | Upload or paste files and images, edit text attachments, use slash-command suggestions, browse project files, and reference project paths with `@`. |
24
24
  | **Git workflows** | Inspect changes, switch branches, review diffs, stage work, generate commit messages with an optional one-shot fallback model, push, and prepare pull requests through guided steps. |
25
25
  | **Project utilities** | Launch detected app runners, manage working directories, search files and transcripts, and customize themes. |
@@ -244,9 +244,13 @@ Ask a quick side question without derailing the main agent flow, then transfer u
244
244
 
245
245
  ![Pi Web UI Codex usage widget showing subscription usage windows and reset timers](https://raw.githubusercontent.com/Firstp1ck/pi-coding-agent-forge/main/pi-package-webui/images/Webui_CodexUsage_v0.4.8.png)
246
246
 
247
- **Optional feature needed:** None for usage reporting, which is included in Pi Web UI core for supported Codex authentication. The Normal/Fast/Ultrafast selector requires `@firstpick/pi-extension-codex-fast-mode`.
247
+ **Optional feature needed:** No Pi companion package for usage reporting. Install [Codex CLI](https://developers.openai.com/codex/cli) and sign in with ChatGPT to use the preferred usage source. The Normal/Fast/Ultrafast selector requires `@firstpick/pi-extension-codex-fast-mode`.
248
248
 
249
- Monitor subscription usage windows and reset times. With the companion enabled, choose a speed under Codex Usage and click Apply. Ultrafast is offered only for subscription-backed GPT-6 Astra and asks for cost confirmation.
249
+ Run `codex login`, check the login with `codex login status`, then choose **Refresh usage** under **Codex Usage**. Web UI shows the CLI account's subscription usage windows and reset times without starting a model turn. The panel labels the source because Codex CLI's login is separate from Pi's; do not assume its limits match Pi's newer ChatGPT-plan allowance.
250
+
251
+ If Codex CLI cannot provide usage, Web UI tries a compatible legacy Pi Codex login. Pi's newer **OpenAI → Sign in with ChatGPT** token cannot supply that fallback. See [authentication compatibility](TECHNICAL.md#codex-subscription-usage) for configuration and troubleshooting, or check [ChatGPT usage](https://chatgpt.com/settings/usage) directly.
252
+
253
+ With the companion enabled, choose a speed under Codex Usage and click Apply. Ultrafast is offered only for subscription-backed GPT-6 Astra and asks for cost confirmation.
250
254
 
251
255
  **Ultrafast costs more:** it requires Pro $500 or eligible Enterprise/Edu access and uses 8× Standard included usage or 6× purchased-credit/pay-as-you-go usage. Workspace terms may differ. The selector shows your preference, not confirmation of upstream acceptance.
252
256
 
package/TECHNICAL.md CHANGED
@@ -184,6 +184,20 @@ Behavior and limits:
184
184
  - Coloring is intentionally approximate rather than a full language parser. Unusual constructs such as nested string interpolation, shell heredocs, PowerShell here-strings, or embedded scripts inside markup may be colored imprecisely; the code text itself is never altered.
185
185
  - Fenced `mermaid` and `mmd` blocks keep rendering as diagrams instead of highlighted source.
186
186
 
187
+ ## Codex subscription usage
188
+
189
+ The **Codex Usage** panel prefers your installed Codex CLI as its usage source. Run `codex login` and sign in with ChatGPT, verify with `codex login status`, then choose **Refresh usage** in Web UI. It reports the CLI account's subscription windows and reset times without starting a model turn, opening a Codex conversation, or redeeming usage resets. API-key and other provider logins cannot supply these subscription numbers.
190
+
191
+ Codex CLI's login is separate from Pi's. The panel labels **Codex CLI account** and warns that these limits may differ from Pi's newer ChatGPT-plan allowance. Sign into the intended account in Codex CLI. Web UI does not compare or display account IDs or email addresses, and choosing this source does not change Pi's login or model.
192
+
193
+ Codex CLI must be available to the account and environment running Web UI. It uses the CLI's existing configuration and `CODEX_HOME` if you have set it. Set `PI_WEBUI_CODEX_BIN` to an executable path if `codex` is not on that environment's PATH. Windows native executables and the standard npm installation are supported without a command shell; custom Windows script launchers need an executable or JavaScript entry point instead. Restart the Web UI after changing its launch environment. The adapter was verified with Codex CLI 0.162.1; older or incompatible versions fall back rather than starting model work.
194
+
195
+ The CLI check has a 15-second deadline plus bounded process cleanup. Concurrent requests share one check, successful results are cached for 30 seconds, and **Refresh usage** requests a fresh check. Failures are not cached. A missing CLI, missing ChatGPT login, timeout, or unusable response triggers the legacy fallback. Its source label makes the change visible.
196
+
197
+ The fallback uses a supported legacy Pi Codex subscription OAuth login. Keep Pi and Web UI on the same `PI_CODING_AGENT_DIR` when using a custom configuration location. Pi's newer **OpenAI → Sign in with ChatGPT** token cannot supply this legacy usage reader and is never refreshed or forwarded for that purpose. If neither source works, check [ChatGPT usage](https://chatgpt.com/settings/usage) directly.
198
+
199
+ Codex CLI manages its own authentication and normal token refresh. Web UI does not read its credential files, request a login flow, scrape terminal output, or publish raw CLI diagnostics. Tokens, email addresses, account IDs, and other raw account details never reach the browser. The legacy reader keeps Pi OAuth credentials server-side too.
200
+
187
201
  ## Codex subscription Fast mode
188
202
 
189
203
  The optional `@firstpick/pi-extension-codex-fast-mode` companion adds a **Normal / Fast / Ultrafast** selector under **Codex Usage**. Normal is the default. The preference belongs to the active Pi session branch, and changes are blocked while that tab is busy. The displayed mode is a preference, not proof that OpenAI accepted the tier.
@@ -388,6 +402,8 @@ The side-panel **Git** section groups repositories represented by open terminal
388
402
 
389
403
  Use **Controls → Interface → Theme** to choose a theme.
390
404
 
405
+ Update WebUI and `@firstpick/pi-themes-bundle` together when moving to Pi 1.2. The updated bundle keeps native palettes valid under Pi's stricter theme checks, while WebUI retains the Catppuccin Mocha and Matrix background images.
406
+
391
407
  ### Custom themes
392
408
 
393
409
  **Customize…** opens a visual editor for Pi's exact 51 required theme tokens, optional colors, variables, and advanced JSON. Valid changes preview immediately. Invalid or incomplete edits remain editable but cannot replace the last valid preview or be saved.
package/bin/pi-webui.mjs CHANGED
@@ -14,6 +14,7 @@ import { brotliCompress, brotliCompressSync, constants as zlibConstants, gzip, g
14
14
  import { SessionManager, SettingsManager, DefaultPackageManager } from "@earendil-works/pi-coding-agent";
15
15
  import {
16
16
  ThemeContractError,
17
+ WEBUI_THEME_EXPORT_FIELDS,
17
18
  canonicalizeTheme,
18
19
  normalizeThemeFileName,
19
20
  serializeTheme,
@@ -28,7 +29,9 @@ import {
28
29
  validateAppendSystemSelection,
29
30
  validateSavedAppendSystemSelection,
30
31
  } from "../lib/append-system-selection.mjs";
31
- import { resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
32
+ import { CODEX_USAGE_DIRECT_TOKEN_MESSAGE, codexUsageLoginGuidance, resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
33
+ import { readCodexCliUsage } from "../lib/codex-cli-usage.mjs";
34
+ import { createCodexUsageReader } from "../lib/codex-usage-source.mjs";
32
35
  import { codexSpeedModeFromIntent, codexSpeedModeFromStatus } from "../public/codex-speed-mode.mjs";
33
36
  import { AgentRunIndex, canonicalAgentRunId, normalizeAgentInstance } from "../lib/agent-run-protocol.mjs";
34
37
  import { AgentRunRegistry } from "../lib/agent-run-registry.mjs";
@@ -5318,7 +5321,7 @@ function normalizeCodexUsagePayload(rawPayload) {
5318
5321
  };
5319
5322
 
5320
5323
  const directRateLimits = firstDefined(payload.rateLimits, payload.rate_limits);
5321
- if (directRateLimits && typeof directRateLimits === "object" && (directRateLimits.primary || directRateLimits.primary_window || directRateLimits.primaryWindow)) {
5324
+ if (directRateLimits && typeof directRateLimits === "object" && (directRateLimits.primary || directRateLimits.secondary || directRateLimits.primary_window || directRateLimits.secondary_window || directRateLimits.primaryWindow || directRateLimits.secondaryWindow)) {
5322
5325
  addSnapshot(makeCodexUsageSnapshot({
5323
5326
  limitId: firstDefined(directRateLimits.limitId, directRateLimits.limit_id, "codex"),
5324
5327
  limitName: firstDefined(directRateLimits.limitName, directRateLimits.limit_name),
@@ -5382,26 +5385,33 @@ function normalizeCodexUsagePayload(rawPayload) {
5382
5385
 
5383
5386
  async function getOpenAICodexUsageCredentials({ forceRefresh = false } = {}) {
5384
5387
  const { modelRuntime } = await authContext();
5388
+ const loginGuidance = codexUsageLoginGuidance(modelRuntime);
5385
5389
  let resolved;
5386
5390
  try {
5387
5391
  resolved = await resolveCodexUsageAuth(modelRuntime, OPENAI_CODEX_PROVIDER_ID, { forceRefresh });
5388
5392
  } catch {
5389
5393
  // Client-facing auth failures must not include provider stack traces,
5390
5394
  // refresh tokens, or raw upstream error details.
5391
- throw makeHttpError(401, "OpenAI Codex OAuth token refresh failed. Run /login and choose ChatGPT Plus/Pro (Codex Subscription) to re-authenticate.");
5395
+ throw makeHttpError(401, `OpenAI Codex OAuth token refresh failed. ${loginGuidance}`);
5392
5396
  }
5393
5397
 
5398
+ if (resolved.unsupportedReason === "chatgpt-direct-token") {
5399
+ throw makeHttpError(501, CODEX_USAGE_DIRECT_TOKEN_MESSAGE);
5400
+ }
5394
5401
  const accessToken = resolved.accessToken;
5395
5402
  if (!accessToken) {
5396
- const status = modelRuntime.getProviderAuthStatus(OPENAI_CODEX_PROVIDER_ID);
5397
- if (status.configured) throw makeHttpError(401, "OpenAI Codex OAuth token is expired or unavailable. Run /login to refresh credentials.");
5398
- throw makeHttpError(401, "OpenAI Codex OAuth is not configured. Run /login and choose ChatGPT Plus/Pro (Codex Subscription).");
5403
+ if (resolved.providerId === "openai" && resolved.credential?.type === "api_key") {
5404
+ throw makeHttpError(401, `Codex subscription usage requires ChatGPT OAuth, not an OpenAI API key. ${loginGuidance}`);
5405
+ }
5406
+ const status = modelRuntime.getProviderAuthStatus(resolved.providerId);
5407
+ if (status.configured) throw makeHttpError(401, `OpenAI Codex OAuth token is expired or unavailable. ${loginGuidance}`);
5408
+ throw makeHttpError(401, `OpenAI Codex OAuth is not configured. ${loginGuidance}`);
5399
5409
  }
5400
5410
 
5401
5411
  const latest = resolved.credential || {};
5402
5412
  const accountId = latest.accountId || codexAccountIdFromAccessToken(accessToken);
5403
5413
  if (!accountId) {
5404
- throw makeHttpError(401, "OpenAI Codex account id is unavailable. Run /login and choose ChatGPT Plus/Pro (Codex Subscription) again.");
5414
+ throw makeHttpError(401, `OpenAI Codex account id is unavailable. ${loginGuidance}`);
5405
5415
  }
5406
5416
 
5407
5417
  return {
@@ -5447,7 +5457,7 @@ async function fetchOpenAICodexUsagePayload(credentials) {
5447
5457
  }
5448
5458
  }
5449
5459
 
5450
- async function getOpenAICodexUsageStatus({ forceRefresh = false } = {}) {
5460
+ async function getLegacyOpenAICodexUsageStatus({ forceRefresh = false } = {}) {
5451
5461
  let credentials = await getOpenAICodexUsageCredentials({ forceRefresh });
5452
5462
  let rawPayload;
5453
5463
  try {
@@ -5475,6 +5485,21 @@ async function getOpenAICodexUsageStatus({ forceRefresh = false } = {}) {
5475
5485
  };
5476
5486
  }
5477
5487
 
5488
+ const getOpenAICodexUsageStatus = createCodexUsageReader({
5489
+ readCli: async () => {
5490
+ const payload = await readCodexCliUsage();
5491
+ return {
5492
+ available: true,
5493
+ providerId: OPENAI_CODEX_PROVIDER_ID,
5494
+ source: "codex-cli",
5495
+ fetchedAt: new Date().toISOString(),
5496
+ auth: { source: "codex-cli" },
5497
+ ...normalizeCodexUsagePayload(payload),
5498
+ };
5499
+ },
5500
+ readLegacy: getLegacyOpenAICodexUsageStatus,
5501
+ });
5502
+
5478
5503
  const CLAUDE_USAGE_MONTHS = new Map([
5479
5504
  ["jan", 1], ["january", 1], ["feb", 2], ["february", 2],
5480
5505
  ["mar", 3], ["march", 3], ["apr", 4], ["april", 4], ["may", 5],
@@ -9128,12 +9153,24 @@ async function readBundledThemes() {
9128
9153
  const dir = await resolveBundledThemesDir();
9129
9154
  if (!dir) return { source: "@firstpick/pi-themes-bundle", themes: [] };
9130
9155
  const themes = [];
9156
+ let backgrounds = {};
9157
+ try {
9158
+ const metadata = JSON.parse(await readFile(path.join(dir, "..", "webui-backgrounds.json"), "utf8"));
9159
+ if (metadata && typeof metadata === "object" && !Array.isArray(metadata)) backgrounds = metadata;
9160
+ } catch (error) {
9161
+ if (error?.code !== "ENOENT") console.error(`Skipping invalid bundled theme backgrounds: ${sanitizeError(error)}`);
9162
+ }
9131
9163
  for (const fileName of (await readdir(dir)).filter((file) => file.endsWith(".json")).sort((a, b) => a.localeCompare(b))) {
9132
9164
  try {
9133
9165
  const target = path.join(dir, fileName);
9134
9166
  const info = await lstat(target);
9135
9167
  if (info.isSymbolicLink() || !info.isFile()) continue;
9136
- themes.push(catalogTheme(JSON.parse(await readFile(target, "utf8")), fileName, "bundled"));
9168
+ const entry = catalogTheme(JSON.parse(await readFile(target, "utf8")), fileName, "bundled");
9169
+ const background = Object.hasOwn(backgrounds, entry.name) ? backgrounds[entry.name] : null;
9170
+ for (const key of WEBUI_THEME_EXPORT_FIELDS) {
9171
+ if (background && typeof background[key] === "string") entry.export[key] = background[key];
9172
+ }
9173
+ themes.push(entry);
9137
9174
  } catch (error) {
9138
9175
  console.error(`Skipping invalid bundled theme ${fileName}: ${sanitizeError(error)}`);
9139
9176
  }
@@ -0,0 +1,232 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { StringDecoder } from "node:string_decoder";
5
+ import { resolveCommandDirectory } from "./npm-command.mjs";
6
+ import { terminateProcessTree } from "./process-tree.mjs";
7
+
8
+ export const CODEX_CLI_USAGE_TIMEOUT_MS = 15_000;
9
+ const MAX_LINE_BYTES = 1024 * 1024;
10
+ const MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
11
+ const MAX_BUCKETS = 16;
12
+
13
+ export class CodexCliUsageError extends Error {
14
+ constructor(code, message, statusCode = 503) {
15
+ super(message);
16
+ this.name = "CodexCliUsageError";
17
+ this.code = code;
18
+ this.statusCode = statusCode;
19
+ }
20
+ }
21
+
22
+ function failure(code, message, statusCode) {
23
+ return new CodexCliUsageError(code, message, statusCode);
24
+ }
25
+
26
+ /** Resolve native executables and npm shims without a shell or command interpolation. */
27
+ export function resolveCodexCliInvocation(runtime = {}) {
28
+ const env = runtime.env ?? process.env;
29
+ const platform = runtime.platform ?? process.platform;
30
+ const exists = runtime.existsSync ?? existsSync;
31
+ const execPath = runtime.execPath ?? process.execPath;
32
+ const api = platform === "win32" ? path.win32 : path.posix;
33
+ const command = String(env.PI_WEBUI_CODEX_BIN || "codex").trim();
34
+ const args = ["app-server", "--listen", "stdio://"];
35
+ if (/\.(?:js|mjs|cjs)$/i.test(command)) return { command: execPath, args: [command, ...args] };
36
+ if (platform !== "win32" || /\.(?:exe|com)$/i.test(command)) return { command, args };
37
+ const directory = resolveCommandDirectory(command, { ...runtime, env, platform, existsSync: exists });
38
+ if (directory && /^codex(?:\.(?:cmd|ps1))?$/i.test(api.basename(command))) {
39
+ const native = api.join(directory, "codex.exe");
40
+ if (!api.extname(command) && exists(native)) return { command: native, args };
41
+ const script = api.join(directory, "node_modules", "@openai", "codex", "bin", "codex.js");
42
+ if (exists(script)) return { command: execPath, args: [script, ...args] };
43
+ }
44
+ if (/\.(?:cmd|bat|ps1)$/i.test(command) || directory) {
45
+ throw failure("CODEX_CLI_SHIM", "Codex CLI's Windows launcher cannot be used directly. Set PI_WEBUI_CODEX_BIN to codex.exe or the npm codex.js entry point.");
46
+ }
47
+ return { command, args };
48
+ }
49
+
50
+ function text(value, maximum = 80) {
51
+ return typeof value === "string" && value.length > 0 && value.length <= maximum && !/[\u0000-\u001f\u007f]/.test(value) ? value : null;
52
+ }
53
+
54
+ function windowSnapshot(value) {
55
+ if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.usedPercent !== "number" || !Number.isFinite(value.usedPercent) || value.usedPercent < 0 || value.usedPercent > 100) return null;
56
+ return {
57
+ usedPercent: value.usedPercent,
58
+ windowDurationMins: Number.isInteger(value.windowDurationMins) && value.windowDurationMins > 0 && value.windowDurationMins <= 10_000_000 ? value.windowDurationMins : null,
59
+ resetsAt: Number.isInteger(value.resetsAt) && value.resetsAt >= 0 && value.resetsAt <= 253402300799 ? value.resetsAt : null,
60
+ };
61
+ }
62
+
63
+ function limitSnapshot(value) {
64
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
65
+ const credits = value.credits;
66
+ return {
67
+ limitId: text(value.limitId),
68
+ limitName: text(value.limitName),
69
+ planType: text(value.planType),
70
+ rateLimitReachedType: text(value.rateLimitReachedType),
71
+ primary: windowSnapshot(value.primary),
72
+ secondary: windowSnapshot(value.secondary),
73
+ credits: credits && typeof credits === "object" ? {
74
+ hasCredits: typeof credits.hasCredits === "boolean" ? credits.hasCredits : undefined,
75
+ unlimited: typeof credits.unlimited === "boolean" ? credits.unlimited : undefined,
76
+ balance: typeof credits.balance === "string" && /^-?\d{1,32}(?:\.\d{1,16})?$/.test(credits.balance) ? credits.balance : null,
77
+ } : null,
78
+ };
79
+ }
80
+
81
+ /** Project only displayable quota fields. Account IDs, email and raw payloads stay private. */
82
+ export function projectCodexCliUsage(result, planType) {
83
+ if (!result || typeof result !== "object" || Array.isArray(result)) throw failure("CODEX_CLI_PROTOCOL", "Codex CLI returned an invalid usage response.", 502);
84
+ const rateLimits = limitSnapshot(result.rateLimits);
85
+ const byId = result.rateLimitsByLimitId;
86
+ const entries = byId && typeof byId === "object" && !Array.isArray(byId)
87
+ ? Object.entries(byId).slice(0, MAX_BUCKETS).flatMap(([id, value]) => {
88
+ const snapshot = limitSnapshot(value);
89
+ return text(id) && snapshot ? [[id, snapshot]] : [];
90
+ }) : [];
91
+ if (![rateLimits, ...entries.map(([, snapshot]) => snapshot)].some((snapshot) => snapshot?.primary || snapshot?.secondary)) {
92
+ throw failure("CODEX_CLI_NO_USAGE", "Codex CLI returned no supported subscription usage windows.", 502);
93
+ }
94
+ return { planType: text(planType), rateLimits, rateLimitsByLimitId: Object.fromEntries(entries) };
95
+ }
96
+
97
+ function waitForClose(closed, timeoutMs) {
98
+ return new Promise((resolve) => {
99
+ const timer = setTimeout(() => resolve(false), timeoutMs);
100
+ closed.then(() => { clearTimeout(timer); resolve(true); });
101
+ });
102
+ }
103
+
104
+ /** A usage-only app-server connection. Never starts threads, turns, login flows or resets. */
105
+ export async function readCodexCliUsage(options = {}) {
106
+ const env = options.env ?? process.env;
107
+ const timeoutMs = options.timeoutMs ?? CODEX_CLI_USAGE_TIMEOUT_MS;
108
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 60_000) throw new TypeError("Codex CLI usage timeout must be between 1 and 60000ms");
109
+ if (options.signal?.aborted) throw failure("CODEX_CLI_ABORTED", "Codex CLI usage check was cancelled.");
110
+ const invocation = options.invocation ?? resolveCodexCliInvocation({ env });
111
+ let child;
112
+ try {
113
+ child = (options.spawn ?? spawn)(invocation.command, invocation.args, {
114
+ cwd: options.cwd,
115
+ env,
116
+ windowsHide: true,
117
+ detached: process.platform !== "win32",
118
+ stdio: ["pipe", "pipe", "pipe"],
119
+ shell: false,
120
+ });
121
+ } catch {
122
+ throw failure("CODEX_CLI_START", "Codex CLI could not start. Check its installation and PI_WEBUI_CODEX_BIN.");
123
+ }
124
+ const pending = new Map();
125
+ let serial = 0;
126
+ let terminalError;
127
+ let finishClose;
128
+ const closed = new Promise((resolve) => { finishClose = resolve; });
129
+ const decoder = new StringDecoder("utf8");
130
+ let buffer = "";
131
+ let stdoutBytes = 0;
132
+ let stderrBytes = 0;
133
+ const fail = (error) => {
134
+ if (terminalError) return;
135
+ terminalError = error;
136
+ for (const operation of pending.values()) operation.reject(error);
137
+ pending.clear();
138
+ };
139
+ const write = (frame) => {
140
+ if (terminalError) throw terminalError;
141
+ child.stdin.write(`${JSON.stringify(frame)}\n`, (error) => {
142
+ if (error) fail(failure("CODEX_CLI_PIPE", "Codex CLI closed its usage connection."));
143
+ });
144
+ };
145
+ const request = (method, params) => new Promise((resolve, reject) => {
146
+ if (terminalError) { reject(terminalError); return; }
147
+ const id = ++serial;
148
+ pending.set(id, { resolve, reject });
149
+ try { write({ id, method, params }); } catch (error) { pending.delete(id); reject(error); }
150
+ });
151
+ const receive = (line) => {
152
+ if (!line.trim()) return;
153
+ let frame;
154
+ try { frame = JSON.parse(line); } catch { fail(failure("CODEX_CLI_PROTOCOL", "Codex CLI returned invalid usage protocol data.", 502)); return; }
155
+ if (!frame || typeof frame !== "object" || Array.isArray(frame)) { fail(failure("CODEX_CLI_PROTOCOL", "Codex CLI returned invalid usage protocol data.", 502)); return; }
156
+ if (typeof frame.method === "string") {
157
+ // Reject unsolicited server requests rather than launching an auth flow,
158
+ // approving work, or handing over credentials. Ignore notifications.
159
+ if (frame.id !== undefined) {
160
+ try { write({ id: frame.id, error: { code: -32601, message: "Usage-only client does not handle server requests." } }); } catch { /* request already failed */ }
161
+ }
162
+ return;
163
+ }
164
+ const operation = pending.get(frame.id);
165
+ if (!operation) return;
166
+ pending.delete(frame.id);
167
+ if (frame.error) operation.reject(failure("CODEX_CLI_REQUEST", "Codex CLI could not read subscription usage. Check codex login status and try again.", 502));
168
+ else if (!Object.hasOwn(frame, "result")) operation.reject(failure("CODEX_CLI_PROTOCOL", "Codex CLI returned an incomplete usage response.", 502));
169
+ else operation.resolve(frame.result);
170
+ };
171
+ child.stdout.on("data", (chunk) => {
172
+ if (terminalError) return;
173
+ stdoutBytes += chunk.length;
174
+ if (stdoutBytes > MAX_OUTPUT_BYTES) { fail(failure("CODEX_CLI_OUTPUT_LIMIT", "Codex CLI usage output exceeded the safe size limit.", 502)); return; }
175
+ buffer += decoder.write(chunk);
176
+ let newline;
177
+ while ((newline = buffer.indexOf("\n")) >= 0) {
178
+ const line = buffer.slice(0, newline);
179
+ buffer = buffer.slice(newline + 1);
180
+ if (Buffer.byteLength(line) > MAX_LINE_BYTES) { fail(failure("CODEX_CLI_OUTPUT_LIMIT", "Codex CLI usage output exceeded the safe size limit.", 502)); return; }
181
+ receive(line);
182
+ if (terminalError) return;
183
+ }
184
+ if (Buffer.byteLength(buffer) > MAX_LINE_BYTES) fail(failure("CODEX_CLI_OUTPUT_LIMIT", "Codex CLI usage output exceeded the safe size limit.", 502));
185
+ });
186
+ child.stderr.on("data", (chunk) => {
187
+ // Drain, but never retain or publish CLI diagnostics. They can contain secrets.
188
+ stderrBytes += chunk.length;
189
+ if (stderrBytes > MAX_OUTPUT_BYTES) fail(failure("CODEX_CLI_OUTPUT_LIMIT", "Codex CLI usage diagnostics exceeded the safe size limit.", 502));
190
+ });
191
+ child.stdin.on("error", () => fail(failure("CODEX_CLI_PIPE", "Codex CLI closed its usage connection.")));
192
+ child.stdout.on("error", () => fail(failure("CODEX_CLI_PIPE", "Codex CLI closed its usage connection.")));
193
+ child.stderr.on("error", () => fail(failure("CODEX_CLI_PIPE", "Codex CLI closed its usage connection.")));
194
+ child.on("error", (error) => fail(error?.code === "ENOENT"
195
+ ? failure("CODEX_CLI_NOT_FOUND", "Codex CLI was not found. Install it or set PI_WEBUI_CODEX_BIN, then run codex login.")
196
+ : failure("CODEX_CLI_START", "Codex CLI could not start. Check its installation and PI_WEBUI_CODEX_BIN.")));
197
+ child.on("close", () => { finishClose(); fail(failure("CODEX_CLI_EXIT", "Codex CLI exited before completing the usage check.")); });
198
+ const timer = setTimeout(() => fail(failure("CODEX_CLI_TIMEOUT", "Codex CLI subscription usage check timed out.", 504)), timeoutMs);
199
+ const abort = () => fail(failure("CODEX_CLI_ABORTED", "Codex CLI usage check was cancelled."));
200
+ options.signal?.addEventListener("abort", abort, { once: true });
201
+ if (options.signal?.aborted) abort();
202
+ const terminate = options.terminate ?? terminateProcessTree;
203
+ const onParentExit = () => terminate(child, "SIGKILL");
204
+ process.once("exit", onParentExit);
205
+ try {
206
+ await request("initialize", { clientInfo: { name: "pi_webui_usage", title: "Pi Web UI usage", version: "1.0.0" } });
207
+ write({ method: "initialized" });
208
+ const account = await request("account/read", { refreshToken: false });
209
+ if (!account?.account) throw failure("CODEX_CLI_LOGIN_REQUIRED", "Codex CLI is not logged in. Run codex login and sign in with ChatGPT.", 401);
210
+ if (account.account.type !== "chatgpt") throw failure("CODEX_CLI_AUTH_TYPE", "Codex CLI subscription usage requires a ChatGPT login, not API-key or other provider authentication. Run codex login.", 401);
211
+ const usage = await request("account/rateLimits/read", null);
212
+ return projectCodexCliUsage(usage, account.account.planType);
213
+ } finally {
214
+ clearTimeout(timer);
215
+ options.signal?.removeEventListener("abort", abort);
216
+ fail(failure("CODEX_CLI_CLOSED", "Codex CLI usage connection closed."));
217
+ try {
218
+ child.stdin.end();
219
+ if (!await waitForClose(closed, 300)) {
220
+ terminate(child, "SIGKILL");
221
+ if (!await waitForClose(closed, 1_000)) {
222
+ child.stdin.destroy();
223
+ child.stdout.destroy();
224
+ child.stderr.destroy();
225
+ child.unref();
226
+ }
227
+ }
228
+ } finally {
229
+ process.removeListener("exit", onParentExit);
230
+ }
231
+ }
232
+ }
@@ -1,4 +1,13 @@
1
1
  export const CODEX_TOKEN_REFRESH_SKEW_MS = 5 * 60 * 1000;
2
+ export const CODEX_USAGE_DIRECT_TOKEN_MESSAGE = "Your ChatGPT login is configured, but Codex usage reporting is unavailable for Pi's Sign in with ChatGPT authentication. Check https://chatgpt.com/settings/usage. Logging in again will not enable this panel.";
3
+
4
+ function isDirectChatGPTCredential(credential) {
5
+ return credential?.type === "oauth" && Array.isArray(credential.scopes) && credential.scopes.includes("chatgpt.tokens.use.direct");
6
+ }
7
+
8
+ function unsupportedDirectAuth(providerId, credential) {
9
+ return { providerId, credential, accessToken: undefined, refreshed: false, unsupportedReason: "chatgpt-direct-token" };
10
+ }
2
11
 
3
12
  function privateCredentialStore(modelRuntime) {
4
13
  // Compatibility adapter: ModelRuntime intentionally does not expose a
@@ -11,12 +20,34 @@ function privateCredentialStore(modelRuntime) {
11
20
  return credentials;
12
21
  }
13
22
 
23
+ export function codexUsageLoginGuidance(modelRuntime) {
24
+ return modelRuntime.getProvider("openai")?.auth?.oauth?.isSubscription === true
25
+ ? "Run /login, choose OpenAI, then Sign in with ChatGPT."
26
+ : "Run /login and choose ChatGPT Plus/Pro (Codex Subscription).";
27
+ }
28
+
14
29
  export async function resolveCodexUsageAuth(modelRuntime, providerId, options = {}) {
15
30
  const now = options.now ?? Date.now();
16
31
  const forceRefresh = options.forceRefresh === true;
17
32
  const credentials = privateCredentialStore(modelRuntime);
18
- const provider = modelRuntime.getProvider(providerId);
33
+ let provider = modelRuntime.getProvider(providerId);
19
34
  let stored = await credentials.read(providerId);
35
+ // Newer Pi versions store ChatGPT OAuth under the unified OpenAI provider.
36
+ // Only select that alias when the runtime supports subscription OAuth.
37
+ if (providerId === "openai-codex" && (stored?.type !== "oauth" || !provider?.auth?.oauth)) {
38
+ const openai = modelRuntime.getProvider("openai");
39
+ if (openai?.auth?.oauth?.isSubscription === true) {
40
+ const current = await credentials.read("openai");
41
+ if (current?.type === "oauth" || !provider?.auth?.oauth) {
42
+ providerId = "openai";
43
+ provider = openai;
44
+ stored = current;
45
+ }
46
+ }
47
+ }
48
+ // Sign in with ChatGPT tokens target api.openai.com, not the legacy Codex
49
+ // usage endpoint. Do not refresh or forward them just to report this limit.
50
+ if (isDirectChatGPTCredential(stored)) return unsupportedDirectAuth(providerId, stored);
20
51
  let refreshed = false;
21
52
 
22
53
  if (stored?.type === "oauth") {
@@ -28,7 +59,7 @@ export async function resolveCodexUsageAuth(modelRuntime, providerId, options =
28
59
 
29
60
  if (shouldRefresh) {
30
61
  await credentials.modify(providerId, async (current) => {
31
- if (current?.type !== "oauth") return undefined;
62
+ if (current?.type !== "oauth" || isDirectChatGPTCredential(current)) return undefined;
32
63
  // Another process may have refreshed while this caller waited for the
33
64
  // auth-file lock. Reuse that newer token rather than refreshing twice.
34
65
  if (forceRefresh && current.access !== rejectedAccess) return undefined;
@@ -42,18 +73,23 @@ export async function resolveCodexUsageAuth(modelRuntime, providerId, options =
42
73
  stored = await credentials.read(providerId);
43
74
  }
44
75
 
76
+ if (isDirectChatGPTCredential(stored)) return unsupportedDirectAuth(providerId, stored);
45
77
  if (forceRefresh && stored?.type === "oauth" && stored.access === rejectedAccess) {
46
78
  throw new Error("Codex OAuth refresh returned the rejected credential.");
47
79
  }
48
80
  return {
81
+ providerId,
49
82
  accessToken: stored?.type === "oauth" ? stored.access : undefined,
50
83
  credential: stored,
51
84
  refreshed: refreshed || (forceRefresh && stored?.type === "oauth" && stored.access !== rejectedAccess),
52
85
  };
53
86
  }
54
87
 
55
- const resolved = await modelRuntime.getAuth(providerId);
88
+ // OpenAI API keys are not ChatGPT subscription credentials. Never resolve
89
+ // the unified provider's API key or environment fallback for usage requests.
90
+ const resolved = providerId === "openai" ? undefined : await modelRuntime.getAuth(providerId);
56
91
  return {
92
+ providerId,
57
93
  accessToken: resolved?.auth?.apiKey,
58
94
  credential: stored,
59
95
  refreshed: false,
@@ -0,0 +1,36 @@
1
+ import { CodexCliUsageError } from "./codex-cli-usage.mjs";
2
+
3
+ export const CODEX_USAGE_CACHE_MS = 30_000;
4
+
5
+ /** Coalesce browser polls and cache only successful snapshots, never credentials or failures. */
6
+ export function createCodexUsageReader({ readCli, readLegacy, cacheMs = CODEX_USAGE_CACHE_MS, now = Date.now }) {
7
+ let cached;
8
+ let cachedAt = 0;
9
+ let inFlight;
10
+ return async function read(options = {}) {
11
+ if (inFlight) return inFlight;
12
+ if (!options.forceRefresh && cached && now() - cachedAt < cacheMs) return cached;
13
+ inFlight = (async () => {
14
+ let cliError;
15
+ try {
16
+ const result = await readCli();
17
+ cached = result;
18
+ cachedAt = now();
19
+ return result;
20
+ } catch (error) {
21
+ cliError = error instanceof CodexCliUsageError ? error : new CodexCliUsageError("CODEX_CLI_FAILED", "Codex CLI usage is unavailable.");
22
+ }
23
+ try {
24
+ const result = await readLegacy(options);
25
+ cached = { ...result, sourceNotice: "Codex CLI usage is unavailable. Showing usage from Pi's legacy Codex login." };
26
+ cachedAt = now();
27
+ return cached;
28
+ } catch {
29
+ // Do not expose raw CLI diagnostics, Pi auth errors, account details,
30
+ // stack traces or upstream response bodies when both readers fail.
31
+ throw new CodexCliUsageError(cliError.code, `${cliError.message} Pi's legacy Codex usage fallback also could not provide usage. Check https://chatgpt.com/settings/usage.`, cliError.statusCode);
32
+ }
33
+ })();
34
+ try { return await inFlight; } finally { inFlight = undefined; }
35
+ };
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstpick/pi-package-webui",
3
- "version": "0.11.0",
3
+ "version": "0.11.1",
4
4
  "description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/Firstp1ck/pi-coding-agent-forge/tree/main/pi-package-webui#readme",
@@ -30,7 +30,7 @@
30
30
  "pi-webui": "./bin/pi-webui-launcher.mjs"
31
31
  },
32
32
  "scripts": {
33
- "check": "node --check public/app.js && node --check public/codex-speed-mode.mjs && node --check lib/app-runner-terminal.mjs && node --check public/middle-button-drag-scroll.mjs && node --check public/stream-output-controller.mjs && node --check public/theme-contract.mjs && node --check public/transcript-renderer.mjs && node --check public/syntax-highlight.mjs && node --check public/mobile-shell-state.mjs && node --check public/issue-wizard-state.mjs && node --check public/issue-bot-client.mjs && node --check public/workflow-status-stack.mjs && node --check public/fast-output-live.mjs && node --check public/subagent-launch-slot-state.mjs && node --check public/subagent-gate-visibility.mjs && node --check public/voice-conversation.mjs && node --check public/aur-review-payload.mjs && node --check public/guided-git-command-state.mjs && node --check public/guided-git-review-state.mjs && node --check bin/pi-webui.mjs && node --check bin/pi-webui-launcher.mjs && node --check bin/pi-webui-native-update-runner.mjs && node --check bin/pi-webui-update-context.mjs && node --check lib/update/coordination.mjs && node --check lib/update/native-jobs.mjs && node --check lib/update/discovery.mjs && node --check lib/update/native-targets.mjs && node --check lib/update/path-pi.mjs && node --check lib/update/migration.mjs && node --check lib/update/supervisor.mjs && node --check bin/pi-webui-rpc-supervisor.mjs && node --check lib/rpc-supervisor-protocol.mjs && node --check lib/rpc-supervisor-state.mjs && node --check lib/rpc-supervisor-client.mjs && node --check webui-rpc-helper.mjs && node --check lib/subagent-launch-slots.mjs && node --check lib/git-live-watcher.mjs && node --check lib/workspace-files-live-watcher.mjs && node --check lib/git-message-artifacts.mjs && node --check lib/trust-boundaries.mjs && node --check lib/native-command-adapter.mjs && node --check lib/session-actions.mjs && node --check lib/auth-actions.mjs && node --check lib/temp-artifacts.mjs && node tests/run-all.mjs",
33
+ "check": "node --check public/app.js && node --check public/codex-speed-mode.mjs && node --check lib/app-runner-terminal.mjs && node --check public/middle-button-drag-scroll.mjs && node --check public/stream-output-controller.mjs && node --check public/theme-contract.mjs && node --check public/transcript-renderer.mjs && node --check public/syntax-highlight.mjs && node --check public/mobile-shell-state.mjs && node --check public/issue-wizard-state.mjs && node --check public/issue-bot-client.mjs && node --check public/workflow-status-stack.mjs && node --check public/fast-output-live.mjs && node --check public/subagent-launch-slot-state.mjs && node --check public/subagent-gate-visibility.mjs && node --check public/voice-conversation.mjs && node --check public/aur-review-payload.mjs && node --check public/guided-git-command-state.mjs && node --check public/guided-git-review-state.mjs && node --check bin/pi-webui.mjs && node --check bin/pi-webui-launcher.mjs && node --check bin/pi-webui-native-update-runner.mjs && node --check bin/pi-webui-update-context.mjs && node --check lib/update/coordination.mjs && node --check lib/update/native-jobs.mjs && node --check lib/update/discovery.mjs && node --check lib/update/native-targets.mjs && node --check lib/update/path-pi.mjs && node --check lib/update/migration.mjs && node --check lib/update/supervisor.mjs && node --check bin/pi-webui-rpc-supervisor.mjs && node --check lib/rpc-supervisor-protocol.mjs && node --check lib/rpc-supervisor-state.mjs && node --check lib/rpc-supervisor-client.mjs && node --check webui-rpc-helper.mjs && node --check lib/subagent-launch-slots.mjs && node --check lib/git-live-watcher.mjs && node --check lib/workspace-files-live-watcher.mjs && node --check lib/git-message-artifacts.mjs && node --check lib/trust-boundaries.mjs && node --check lib/native-command-adapter.mjs && node --check lib/session-actions.mjs && node --check lib/auth-actions.mjs && node --check lib/codex-cli-usage.mjs && node --check lib/codex-usage-source.mjs && node --check lib/temp-artifacts.mjs && node tests/run-all.mjs",
34
34
  "test": "node tests/run-all.mjs",
35
35
  "test:browser": "playwright test"
36
36
  },
@@ -75,7 +75,7 @@
75
75
  "devDependencies": {
76
76
  "@axe-core/playwright": "4.12.1",
77
77
  "@earendil-works/pi-ai": "^0.83.0",
78
- "@earendil-works/pi-coding-agent": "^0.99.2",
78
+ "@earendil-works/pi-coding-agent": "^1.0.0",
79
79
  "@earendil-works/pi-tui": "^0.83.0",
80
80
  "@playwright/test": "1.62.1",
81
81
  "typebox": "^1.3.6"