@router-for-me/pi-cliproxyapi-provider 1.4.26 → 1.5.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
@@ -1,15 +1,15 @@
1
1
  # pi-cliproxyapi-provider
2
2
 
3
- Pi provider extension that discovers models from [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) and registers them for use in pi. It supports catalog-driven OpenAI Fast mode and also ships a small TUI helper that shows elapsed runtime and a TPS summary after each agent turn.
3
+ Pi provider extension that discovers models from [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) and registers them for use in pi. It supports catalog-driven Fast and Ultra Fast modes and also ships a small TUI helper that shows elapsed runtime and a TPS summary after each agent turn.
4
4
 
5
5
  ## What it does
6
6
 
7
7
  1. Registers a provider that always appears in `/login` (account sign-in path).
8
8
  2. Interactive setup collects `baseUrl` + `apiKey` via `/login CLIProxyAPI` or `/login cliproxyapi`.
9
9
  3. Fetches `{root}/v1/models?client_version=pi`.
10
- 4. Maps the CLIProxyAPI catalog into pi models, including Fast service-tier capability.
10
+ 4. Maps the CLIProxyAPI catalog into pi models, including support for faster service tiers.
11
11
  5. Registers inference against `{root}/backend-api/`.
12
- 6. Provides `/fast` to toggle OpenAI priority processing for supported models.
12
+ 6. Provides `/fast` and `/ultrafast` to select faster service tiers for supported models.
13
13
  7. Caches the model catalog in `~/.pi/agent/cliproxyapi-models.json`, refreshes it in the background on startup, and provides `/cliproxyapi-refresh` to force a refresh.
14
14
  8. In interactive TUI sessions, shows footer elapsed time during runs and a TPS / token usage toast when the agent settles.
15
15
  9. After compaction, closes the reused Codex WebSocket for that session so CLIProxyAPI's server-side context resets with the compacted client messages.
@@ -98,7 +98,7 @@ Optional fields:
98
98
  | `apiKey` | _(required unless set via /login or env)_ | Bearer token / CPA API key |
99
99
  | `providerId` | `cliproxyapi` | Provider id shown in `/model` |
100
100
  | `providerName` | `CLIProxyAPI` | Display name in `/login` and UI |
101
- | `fast` | `false` | Persisted Fast mode preference; only applies to catalog-supported models |
101
+ | `fast` | `false` | Persisted speed preference: `false` (off), `true` (Fast), or `"ultrafast"` (Ultra Fast) |
102
102
  | `pause` | `false` | Persisted request-pause preference; provider requests wait until it is cleared |
103
103
 
104
104
  ### Environment overrides
@@ -118,7 +118,7 @@ Resolution order for connection settings:
118
118
  3. `/login` credentials in `auth.json`
119
119
  4. Default baseUrl `http://127.0.0.1:8317`
120
120
 
121
- The Fast preference resolves separately as `CLIPROXYAPI_FAST` → `cliproxyapi.json` → `false`.
121
+ At startup, `CLIPROXYAPI_FAST` overrides the persisted speed preference: a true value selects Fast, and a false value turns both modes off. The variable does not accept `ultrafast`. If unset, the provider uses `fast` from `cliproxyapi.json`, or defaults to off.
122
122
 
123
123
  ### baseUrl normalization
124
124
 
@@ -133,21 +133,20 @@ Preferred form is **host:port only**:
133
133
 
134
134
  pi then sends inference traffic to `{inference}/codex/responses`.
135
135
 
136
- ## Fast mode
136
+ ## Fast and Ultra Fast modes
137
137
 
138
- OpenAI Fast mode requests the priority service tier. It can reduce latency for supported models, but consumes more OpenAI/Codex credits or incurs priority-processing pricing.
138
+ Both modes are **off by default**. They request faster processing for supported models and may use more credits or incur higher costs.
139
139
 
140
- Fast is **off by default**. Toggle the global preference with:
140
+ | Command | Model status label | Request field |
141
+ | ------- | ------------------ | ------------- |
142
+ | `/fast` | `fast` | `service_tier: "priority"` |
143
+ | `/ultrafast` | `Ultra Fast` | `service_tier: "ultrafast"` |
141
144
 
142
- ```text
143
- /fast
144
- ```
145
-
146
- Each invocation switches Fast between on and off and writes the result to `~/.pi/agent/cliproxyapi.json`. On the next startup, a persisted `true` value immediately enables Fast for catalog-supported models. Fast remains ineffective for unsupported models, so their requests are left unchanged. If `CLIPROXYAPI_FAST` is set, that environment variable still takes precedence on startup.
145
+ The modes are mutually exclusive. Run the active command again to turn it off, or run the other command to switch directly. Each change saves the global preference in `~/.pi/agent/cliproxyapi.json` and refreshes the provider's model pricing. The saved preference is restored at the next startup unless `CLIPROXYAPI_FAST` overrides it.
147
146
 
148
- When Fast is effective, pi's model status appends a yellow lowercase `fast`, for example `gpt-5.6-sol • xhigh • fast`. When Fast is off or the selected model is unsupported, the original model status remains unchanged. Supported models do not produce a separate status notification. Running `/fast` with an unsupported model still updates the global preference; enabling it warns that the current model cannot use Fast.
147
+ Both modes apply only to models whose CLIProxyAPI catalog entry has a non-empty `service_tiers` array. The provider ignores `additional_speed_tiers`. When a mode is effective, pi appends its yellow label to the bottom-right model status without a separate notification. On unsupported models, the commands still update the global preference and warn when enabling a mode, but the request and model status remain unchanged.
149
148
 
150
- Fast capability is catalog-driven: the plugin considers a CLIProxyAPI model Fast-capable when its `service_tiers` field is a non-empty array. The `additional_speed_tiers` field is ignored. For supported models, Fast injects `service_tier: "priority"`; unsupported models are left unchanged. Fast is independent from pi's reasoning/thinking level. When `models.dev` provides `experimental.modes.fast.cost`, the registered model cost switches to those Fast rates as well; the provider is refreshed when `/fast` is toggled. If no Fast price is published, the standard price is retained. The plugin does not guess Fast prices from `-pro`/`-fast` model IDs.
149
+ Both modes are independent of pi's reasoning level and use `experimental.modes.fast.cost` from `models.dev` when available. Otherwise, the registered model uses the standard price; the plugin does not guess prices from `-pro` or `-fast` model IDs.
151
150
 
152
151
  ## Pausing provider requests
153
152
 
@@ -250,5 +249,5 @@ Disable just this helper via `pi config` if you only want the CLIProxyAPI provid
250
249
  - HTTP 200 (including empty catalog) → credentials are persisted
251
250
  - non-200 / network / invalid baseUrl → nothing is persisted; re-enter baseUrl + API key
252
251
  - If CPA returns HTTP 200 with zero usable models: login still succeeds; re-run `/login CLIProxyAPI` later after models become available.
253
- - If the selected model does not provide a non-empty `service_tiers` array: the request is left unchanged; `/fast` still updates the global preference and warns when enabling it.
252
+ - If the selected model does not provide a non-empty `service_tiers` array: the request is left unchanged; `/fast` and `/ultrafast` still update the global preference and warn when enabling a mode.
254
253
  - After `/compact`, threshold compaction, or overflow recovery, the provider closes the reused Codex WebSocket for the current session. CLIProxyAPI binds server-side context to the connection, so a reused socket would keep reporting a near-full `cacheRead` and retrigger proactive compaction even though the client context is now small. SSE is unaffected because it bills from the request body.
@@ -21,6 +21,7 @@ import { dirname, join, resolve } from "node:path";
21
21
  import { fileURLToPath, pathToFileURL } from "node:url";
22
22
  import type { Api, AssistantMessageEventStream, Context, Model, SimpleStreamOptions } from "@earendil-works/pi-ai";
23
23
  import { getPackageDir } from "@earendil-works/pi-coding-agent";
24
+ import type { FastServiceTier } from "./fast.ts";
24
25
 
25
26
  export const CLIPROXYAPI_CODEX_API = "cliproxyapi-codex-responses" as const;
26
27
 
@@ -42,7 +43,7 @@ export type CliproxyCodexStreams = {
42
43
  };
43
44
 
44
45
  export interface CliproxyCodexStreamOptions {
45
- shouldUseFast?: (model: Model<Api>) => boolean;
46
+ resolveServiceTier?: (model: Model<Api>) => FastServiceTier | undefined;
46
47
  }
47
48
 
48
49
  type PayloadHook = NonNullable<SimpleStreamOptions["onPayload"]>;
@@ -248,38 +249,39 @@ function moveGptInstructionsToInput(
248
249
  };
249
250
  }
250
251
 
251
- export function withPriorityServiceTier(payload: unknown): unknown {
252
+ export function withServiceTier(payload: unknown, tier: FastServiceTier): unknown {
252
253
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
253
254
  return payload;
254
255
  }
255
256
  return {
256
257
  ...(payload as Record<string, unknown>),
257
- service_tier: "priority",
258
+ service_tier: tier,
258
259
  };
259
260
  }
260
261
 
261
- /** Apply Fast before pi's shared payload hooks so later extensions retain final control. */
262
- export async function applyFastPayloadHook(
262
+ /** Apply the tier before pi's shared payload hooks so later extensions retain final control. */
263
+ export async function applyServiceTierPayloadHook(
263
264
  payload: unknown,
264
265
  model: Model<Api>,
266
+ tier: FastServiceTier,
265
267
  onPayload?: PayloadHook,
266
268
  ): Promise<unknown> {
267
- const fastPayload = withPriorityServiceTier(payload);
268
- const nextPayload = await onPayload?.(fastPayload, model);
269
- return nextPayload === undefined ? fastPayload : nextPayload;
269
+ const tierPayload = withServiceTier(payload, tier);
270
+ const nextPayload = await onPayload?.(tierPayload, model);
271
+ return nextPayload === undefined ? tierPayload : nextPayload;
270
272
  }
271
273
 
272
- export function wrapStreamSimpleForFast(
273
- streamSimple: CliproxyCodexStreamSimple,
274
- shouldUseFast?: (model: Model<Api>) => boolean,
274
+ export function wrapStreamForServiceTier(
275
+ stream: CliproxyCodexStreamSimple,
276
+ resolveServiceTier?: (model: Model<Api>, options?: SimpleStreamOptions) => FastServiceTier | undefined,
275
277
  ): CliproxyCodexStreamSimple {
276
278
  return (model, context, streamOptions) => {
277
- if (!shouldUseFast?.(model)) {
278
- return streamSimple(model, context, streamOptions);
279
- }
280
- return streamSimple(model, context, {
279
+ const tier = resolveServiceTier?.(model, streamOptions);
280
+ if (!tier) return stream(model, context, streamOptions);
281
+ return stream(model, context, {
281
282
  ...streamOptions,
282
- onPayload: (payload, payloadModel) => applyFastPayloadHook(payload, payloadModel, streamOptions?.onPayload),
283
+ onPayload: (payload, payloadModel) =>
284
+ applyServiceTierPayloadHook(payload, payloadModel, tier, streamOptions?.onPayload),
283
285
  });
284
286
  };
285
287
  }
@@ -1493,8 +1495,8 @@ export async function loadCliproxyCodexStreams(
1493
1495
  return mod.stream(adaptModel(model), adaptContext(context), adaptOptions(context, streamOptions));
1494
1496
  };
1495
1497
 
1496
- const streamSimple = wrapStreamSimpleForFast(adaptedStreamSimple, options.shouldUseFast);
1497
- const stream = wrapStreamSimpleForFast(adaptedStream, options.shouldUseFast);
1498
+ const streamSimple = wrapStreamForServiceTier(adaptedStreamSimple, options.resolveServiceTier);
1499
+ const stream = wrapStreamForServiceTier(adaptedStream, options.resolveServiceTier);
1498
1500
 
1499
1501
  return {
1500
1502
  api: CLIPROXYAPI_CODEX_API,
@@ -1,6 +1,6 @@
1
1
  import { type ExtensionAPI, type ExtensionContext, FooterComponent } from "@earendil-works/pi-coding-agent";
2
2
  import type { ProactiveCompactionSettings } from "./auto-compact.ts";
3
- import type { FastModeController } from "./fast.ts";
3
+ import type { FastModeController, FastServiceTier } from "./fast.ts";
4
4
  import { type PauseController, pauseController } from "./pause.ts";
5
5
 
6
6
  const FAST_FOOTER_PATCH = Symbol.for("@router-for-me/pi-cliproxyapi-provider/fast-footer-patch");
@@ -43,19 +43,17 @@ export function formatFastModelStatus(
43
43
  modelName: string,
44
44
  supportsReasoning: boolean,
45
45
  thinkingLevel: string,
46
- fastEnabled: boolean,
47
- fastLabel = "fast",
48
- paused = false,
49
- pausedLabel = "paused",
46
+ fastLabel?: string,
47
+ pausedLabel?: string,
50
48
  ): string {
51
49
  let status = modelName;
52
50
  if (supportsReasoning) {
53
51
  status += thinkingLevel === "off" ? " • thinking off" : ` • ${thinkingLevel}`;
54
52
  }
55
- if (fastEnabled) {
53
+ if (fastLabel) {
56
54
  status += ` • ${fastLabel}`;
57
55
  }
58
- if (paused) {
56
+ if (pausedLabel) {
59
57
  status += ` • ${pausedLabel}`;
60
58
  }
61
59
  return status;
@@ -96,13 +94,13 @@ function installFooterPatch(controller: FastFooterController): void {
96
94
  const originalId = model.id;
97
95
  const originalReasoning = model.reasoning;
98
96
  const originalContextWindow = model.contextWindow;
99
- const fastEnabled = activeController.isEffectiveFor(model);
100
- if (fastEnabled || activeController.isPaused()) {
97
+ const tier = activeController.getServiceTierFor(model);
98
+ if (tier || activeController.isPaused()) {
101
99
  model.id = activeController.formatModelStatus(
102
100
  originalId,
103
101
  originalReasoning,
104
102
  session?.state.thinkingLevel ?? "off",
105
- fastEnabled,
103
+ tier,
106
104
  );
107
105
  model.reasoning = false;
108
106
  }
@@ -138,7 +136,7 @@ function removeFooterPatch(controller: FastFooterController): void {
138
136
  delete prototype[FAST_FOOTER_PATCH];
139
137
  }
140
138
 
141
- /** Adds Fast to pi's built-in model status without replacing the footer. */
139
+ /** Adds the active speed label to pi's built-in model status without replacing the footer. */
142
140
  export class FastFooterController {
143
141
  private activeContext: ExtensionContext | undefined;
144
142
  private patchInstalled = false;
@@ -166,27 +164,25 @@ export class FastFooterController {
166
164
  });
167
165
  }
168
166
 
169
- formatModelStatus(modelName: string, supportsReasoning: boolean, thinkingLevel: string, fastEnabled = true): string {
167
+ formatModelStatus(
168
+ modelName: string,
169
+ supportsReasoning: boolean,
170
+ thinkingLevel: string,
171
+ tier?: FastServiceTier,
172
+ ): string {
170
173
  const theme = this.activeContext?.ui.theme;
171
- const fastLabel = theme?.fg("warning", "fast") ?? "fast";
172
- const pausedLabel = formatOrangeLabel(theme, "paused");
173
- return formatFastModelStatus(
174
- modelName,
175
- supportsReasoning,
176
- thinkingLevel,
177
- fastEnabled,
178
- fastLabel,
179
- this.pauseMode.isEnabled(),
180
- pausedLabel,
181
- );
174
+ const label = tier === "ultrafast" ? "Ultra Fast" : "fast";
175
+ const fastLabel = tier ? (theme?.fg("warning", label) ?? label) : undefined;
176
+ const pausedLabel = this.isPaused() ? formatOrangeLabel(theme, "paused") : undefined;
177
+ return formatFastModelStatus(modelName, supportsReasoning, thinkingLevel, fastLabel, pausedLabel);
182
178
  }
183
179
 
184
180
  isProviderModel(model: MutableModel): boolean {
185
181
  return model.provider === this.providerId;
186
182
  }
187
183
 
188
- isEffectiveFor(model: MutableModel): boolean {
189
- return this.isProviderModel(model) && this.fastMode.isEffectiveFor(model.id);
184
+ getServiceTierFor(model: MutableModel): FastServiceTier | undefined {
185
+ return this.isProviderModel(model) ? this.fastMode.getServiceTierFor(model.id) : undefined;
190
186
  }
191
187
 
192
188
  isPaused(): boolean {
@@ -1,11 +1,18 @@
1
- /** Global Fast preference plus the capability set advertised by CPA. */
1
+ export type FastPreference = boolean | "ultrafast";
2
+ export type FastServiceTier = "priority" | "ultrafast";
3
+
4
+ /** Global speed preference plus the capability set advertised by CPA. */
2
5
  export class FastModeController {
3
6
  private supportedModelIds = new Set<string>();
4
7
 
5
- constructor(private enabled: boolean) {}
8
+ constructor(private preference: FastPreference) {}
9
+
10
+ getPreference(): FastPreference {
11
+ return this.preference;
12
+ }
6
13
 
7
- setEnabled(enabled: boolean): void {
8
- this.enabled = enabled;
14
+ setPreference(preference: FastPreference): void {
15
+ this.preference = preference;
9
16
  }
10
17
 
11
18
  setSupportedModelIds(modelIds: Iterable<string>): void {
@@ -15,14 +22,15 @@ export class FastModeController {
15
22
  }
16
23
 
17
24
  isEnabled(): boolean {
18
- return this.enabled;
25
+ return this.preference !== false;
19
26
  }
20
27
 
21
28
  isModelSupported(modelId: string): boolean {
22
29
  return this.supportedModelIds.has(modelId.trim());
23
30
  }
24
31
 
25
- isEffectiveFor(modelId: string): boolean {
26
- return this.enabled && this.isModelSupported(modelId);
32
+ getServiceTierFor(modelId: string): FastServiceTier | undefined {
33
+ if (!this.isEnabled() || !this.isModelSupported(modelId)) return undefined;
34
+ return this.preference === "ultrafast" ? "ultrafast" : "priority";
27
35
  }
28
36
  }
@@ -10,7 +10,7 @@
10
10
  * 4. Final login step validates credentials via /v1/models?client_version=pi
11
11
  * (HTTP 200 = success even if the catalog is empty; otherwise re-prompt).
12
12
  * 5. On success, models/credentials are saved and registered immediately.
13
- * 6. `/fast` globally controls catalog-driven priority service tier injection.
13
+ * 6. `/fast` and `/ultrafast` globally control catalog-driven service tier injection.
14
14
  *
15
15
  * Uses a patched openai-codex-responses implementation that does not require
16
16
  * extracting chatgpt_account_id from the API key (plain CPA keys work).
@@ -29,12 +29,12 @@ import type {
29
29
  import { type ExtensionAPI, type ExtensionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
30
30
  import { ProactiveCompactionController } from "./auto-compact.ts";
31
31
  import {
32
- applyFastPayloadHook,
33
32
  CLIPROXYAPI_CODEX_API,
34
33
  type CliproxyCodexStreamSimple,
35
34
  loadCliproxyCodexStreams,
35
+ wrapStreamForServiceTier,
36
36
  } from "./codex-stream.ts";
37
- import { FastModeController } from "./fast.ts";
37
+ import { FastModeController, type FastPreference } from "./fast.ts";
38
38
  import { FastFooterController } from "./fast-footer.ts";
39
39
  import {
40
40
  CONFIG_FILE_NAME,
@@ -310,7 +310,6 @@ async function configureAndRegister(options: {
310
310
  streamSimple: CliproxyCodexStreamSimple;
311
311
  fastMode: FastModeController;
312
312
  refreshCoordinator: ModelRefreshCoordinator;
313
- onFastModeChange?: (enabled: boolean, ctx: ExtensionContext) => Promise<void>;
314
313
  onRefreshOutcome?: (loaded: MappedModels) => void;
315
314
  }): Promise<RefreshResult> {
316
315
  const {
@@ -324,7 +323,6 @@ async function configureAndRegister(options: {
324
323
  streamSimple,
325
324
  fastMode,
326
325
  refreshCoordinator,
327
- onFastModeChange,
328
326
  onRefreshOutcome,
329
327
  } = options;
330
328
 
@@ -362,7 +360,6 @@ async function configureAndRegister(options: {
362
360
  streamSimple,
363
361
  fastMode,
364
362
  refreshCoordinator,
365
- onFastModeChange,
366
363
  onRefreshOutcome,
367
364
  });
368
365
  fastMode.setSupportedModelIds(loaded.fastModelIds);
@@ -386,7 +383,6 @@ function createOAuthHandlers(options: {
386
383
  streamSimple: CliproxyCodexStreamSimple;
387
384
  fastMode: FastModeController;
388
385
  refreshCoordinator: ModelRefreshCoordinator;
389
- onFastModeChange?: (enabled: boolean, ctx: ExtensionContext) => Promise<void>;
390
386
  onRefreshOutcome?: (loaded: MappedModels) => void;
391
387
  }) {
392
388
  const {
@@ -398,7 +394,6 @@ function createOAuthHandlers(options: {
398
394
  streamSimple,
399
395
  fastMode,
400
396
  refreshCoordinator,
401
- onFastModeChange,
402
397
  onRefreshOutcome,
403
398
  } = options;
404
399
 
@@ -429,7 +424,6 @@ function createOAuthHandlers(options: {
429
424
  streamSimple,
430
425
  fastMode,
431
426
  refreshCoordinator,
432
- onFastModeChange,
433
427
  onRefreshOutcome,
434
428
  });
435
429
 
@@ -494,7 +488,6 @@ function registerProvider(
494
488
  streamSimple: CliproxyCodexStreamSimple;
495
489
  fastMode: FastModeController;
496
490
  refreshCoordinator?: ModelRefreshCoordinator;
497
- onFastModeChange?: (enabled: boolean, ctx: ExtensionContext) => Promise<void>;
498
491
  onRefreshOutcome?: (loaded: MappedModels) => void;
499
492
  },
500
493
  ): void {
@@ -508,7 +501,6 @@ function registerProvider(
508
501
  agentDir,
509
502
  streamSimple,
510
503
  fastMode,
511
- onFastModeChange,
512
504
  onRefreshOutcome,
513
505
  } = options;
514
506
  const refreshCoordinator = options.refreshCoordinator ?? new ModelRefreshCoordinator();
@@ -523,7 +515,6 @@ function registerProvider(
523
515
  streamSimple,
524
516
  fastMode,
525
517
  refreshCoordinator,
526
- onFastModeChange,
527
518
  onRefreshOutcome,
528
519
  });
529
520
 
@@ -593,22 +584,22 @@ export function registerPauseGuard(options: { pi: ExtensionAPI; agentDir: string
593
584
  });
594
585
  }
595
586
 
596
- export function registerFastCommand(options: {
587
+ export function registerFastCommands(options: {
597
588
  pi: ExtensionAPI;
598
589
  agentDir: string;
599
590
  providerId: string;
600
591
  fastMode: FastModeController;
601
592
  onStatusChange?: (ctx: ExtensionContext) => void;
602
- onModeChange?: (enabled: boolean, ctx: ExtensionContext) => Promise<void>;
593
+ onModeChange?: (ctx: ExtensionContext) => Promise<void>;
603
594
  }): void {
604
595
  const { pi, agentDir, providerId, fastMode, onStatusChange, onModeChange } = options;
605
596
  let modeChangeInProgress = false;
606
597
 
607
- pi.registerCommand("fast", {
608
- description: "Toggle CLIProxyAPI Fast mode globally.",
609
- handler: async (args, ctx) => {
598
+ const createCommand = (name: string, label: string, selected: Exclude<FastPreference, false>) => ({
599
+ description: `Toggle CLIProxyAPI ${label} mode globally.`,
600
+ handler: async (args: string, ctx: ExtensionContext) => {
610
601
  if (args.trim()) {
611
- ctx.ui.notify("Usage: /fast", "error");
602
+ ctx.ui.notify(`Usage: /${name}`, "error");
612
603
  return;
613
604
  }
614
605
  if (modeChangeInProgress) {
@@ -618,32 +609,33 @@ export function registerFastCommand(options: {
618
609
 
619
610
  modeChangeInProgress = true;
620
611
  try {
621
- const previousEnabled = fastMode.isEnabled();
622
- const enabled = !previousEnabled;
612
+ const previousPreference = fastMode.getPreference();
613
+ const preference = previousPreference === selected ? false : selected;
614
+ let previousSavedPreference: FastPreference | undefined;
623
615
  try {
624
- saveConfigFile(agentDir, { fast: enabled });
616
+ previousSavedPreference = saveConfigFile(agentDir, { fast: preference }).fast;
625
617
  } catch (error) {
626
618
  const message = error instanceof Error ? error.message : String(error);
627
- ctx.ui.notify(`Failed to save Fast mode: ${message}`, "error");
619
+ ctx.ui.notify(`Failed to save ${label} mode: ${message}`, "error");
628
620
  return;
629
621
  }
630
- fastMode.setEnabled(enabled);
622
+ fastMode.setPreference(preference);
631
623
  try {
632
- await onModeChange?.(enabled, ctx);
624
+ await onModeChange?.(ctx);
633
625
  } catch (error) {
634
626
  // Restore all three views of the mode after a partial refresh:
635
627
  // in-memory request behavior, persisted preference, and model metadata.
636
- fastMode.setEnabled(previousEnabled);
628
+ fastMode.setPreference(previousPreference);
637
629
  const rollbackErrors: string[] = [];
638
630
  try {
639
- saveConfigFile(agentDir, { fast: previousEnabled });
631
+ saveConfigFile(agentDir, { fast: previousSavedPreference });
640
632
  } catch (rollbackError) {
641
633
  rollbackErrors.push(
642
634
  `config rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`,
643
635
  );
644
636
  }
645
637
  try {
646
- await onModeChange?.(previousEnabled, ctx);
638
+ await onModeChange?.(ctx);
647
639
  } catch (rollbackError) {
648
640
  rollbackErrors.push(
649
641
  `pricing rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`,
@@ -659,10 +651,13 @@ export function registerFastCommand(options: {
659
651
 
660
652
  const currentModel = ctx.model;
661
653
  if (!currentModel || currentModel.provider !== providerId || !fastMode.isModelSupported(currentModel.id)) {
662
- if (enabled) {
663
- ctx.ui.notify("Fast mode is enabled globally, but the current model does not support it.", "warning");
654
+ if (preference !== false) {
655
+ ctx.ui.notify(
656
+ `${label} mode is enabled globally, but the current model does not support it.`,
657
+ "warning",
658
+ );
664
659
  } else {
665
- ctx.ui.notify("Fast mode is disabled globally.", "info");
660
+ ctx.ui.notify(`${label} mode is disabled globally.`, "info");
666
661
  }
667
662
  }
668
663
  } finally {
@@ -670,6 +665,8 @@ export function registerFastCommand(options: {
670
665
  }
671
666
  },
672
667
  });
668
+ pi.registerCommand("fast", createCommand("fast", "Fast", true));
669
+ pi.registerCommand("ultrafast", createCommand("ultrafast", "Ultra Fast", "ultrafast"));
673
670
  }
674
671
 
675
672
  export function registerRefreshCommand(options: {
@@ -786,14 +783,14 @@ export default async function (pi: ExtensionAPI): Promise<void> {
786
783
  const proactiveCompaction = new ProactiveCompactionController(agentDir, identity.providerId);
787
784
  proactiveCompaction.register(pi);
788
785
 
789
- let fastEnabled = false;
786
+ let fastPreference: FastPreference = false;
790
787
  try {
791
- fastEnabled = resolveFastDefault(agentDir);
788
+ fastPreference = resolveFastDefault(agentDir);
792
789
  } catch (error) {
793
790
  const message = error instanceof Error ? error.message : String(error);
794
791
  logWarn(`invalid Fast configuration (${message}); using fast=false`);
795
792
  }
796
- const fastMode = new FastModeController(fastEnabled);
793
+ const fastMode = new FastModeController(fastPreference);
797
794
  const modelRefreshCoordinator = new ModelRefreshCoordinator();
798
795
 
799
796
  let streamLoadError: string | undefined;
@@ -805,7 +802,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
805
802
  };
806
803
  try {
807
804
  const streams = await loadCliproxyCodexStreams([identity.providerId, "cliproxyapi"], {
808
- shouldUseFast: (model) => model.provider === identity.providerId && fastMode.isEffectiveFor(model.id),
805
+ resolveServiceTier: (model) =>
806
+ model.provider === identity.providerId ? fastMode.getServiceTierFor(model.id) : undefined,
809
807
  });
810
808
  proactiveCompaction.setCloseWebSocketSessions(streams.closeOpenAICodexWebSocketSessions);
811
809
  streamSimple = proactiveCompaction.wrapStreamSimple(streams.streamSimple);
@@ -834,46 +832,35 @@ export default async function (pi: ExtensionAPI): Promise<void> {
834
832
 
835
833
  coordinator.stack.push(entry);
836
834
 
837
- const dispatchStream: CliproxyCodexStreamSimple = (model, context, options) => {
838
- const active = findActiveCompatEntry(coordinator.stack, model.provider);
839
- if (!active) {
840
- throw new Error(
841
- `No active provider stream handler registered for provider: ${model.provider} (api: ${CLIPROXYAPI_CODEX_API})`,
842
- );
843
- }
844
- const shouldFast = (options as any)?.serviceTier === "priority" || (options as any)?.fast === true;
845
- if (shouldFast) {
846
- return active.rawStream(model, context, {
847
- ...options,
848
- onPayload: (payload, payloadModel) => applyFastPayloadHook(payload, payloadModel, options?.onPayload),
849
- });
850
- }
851
- return active.rawStream(model, context, options);
852
- };
853
-
854
- const dispatchStreamSimple: CliproxyCodexStreamSimple = (model, context, options) => {
855
- const active = findActiveCompatEntry(coordinator.stack, model.provider);
856
- if (!active) {
857
- throw new Error(
858
- `No active provider streamSimple handler registered for provider: ${model.provider} (api: ${CLIPROXYAPI_CODEX_API})`,
859
- );
860
- }
861
- const shouldFast = (options as any)?.serviceTier === "priority" || (options as any)?.fast === true;
862
- if (shouldFast) {
863
- return active.rawStreamSimple(model, context, {
864
- ...options,
865
- onPayload: (payload, payloadModel) => applyFastPayloadHook(payload, payloadModel, options?.onPayload),
866
- });
867
- }
868
- return active.rawStreamSimple(model, context, options);
869
- };
835
+ // Compat calls use only per-request options, never the foreground speed preference.
836
+ const createCompatDispatch = (method: "stream" | "streamSimple") =>
837
+ wrapStreamForServiceTier(
838
+ (model, context, options) => {
839
+ const active = findActiveCompatEntry(coordinator.stack, model.provider);
840
+ if (!active) {
841
+ throw new Error(
842
+ `No active provider ${method} handler registered for provider: ${model.provider} (api: ${CLIPROXYAPI_CODEX_API})`,
843
+ );
844
+ }
845
+ return active[method === "stream" ? "rawStream" : "rawStreamSimple"](model, context, options);
846
+ },
847
+ (_model, options) => {
848
+ const explicit = options as { serviceTier?: string; fast?: boolean } | undefined;
849
+ const tier = explicit?.serviceTier;
850
+ if (tier === "ultrafast" || tier === "priority") return tier;
851
+ return explicit?.fast === true ? "priority" : undefined;
852
+ },
853
+ );
870
854
 
871
855
  unregisterApiProviders(COMPAT_SOURCE_ID);
872
856
  registerApiProvider(
873
857
  {
874
858
  api: CLIPROXYAPI_CODEX_API,
875
- stream: dispatchStream as StreamFunction<typeof CLIPROXYAPI_CODEX_API>,
876
- streamSimple: dispatchStreamSimple as StreamFunction<typeof CLIPROXYAPI_CODEX_API, SimpleStreamOptions>,
859
+ stream: createCompatDispatch("stream") as StreamFunction<typeof CLIPROXYAPI_CODEX_API>,
860
+ streamSimple: createCompatDispatch("streamSimple") as StreamFunction<
861
+ typeof CLIPROXYAPI_CODEX_API,
862
+ SimpleStreamOptions
863
+ >,
877
864
  },
878
865
  COMPAT_SOURCE_ID,
879
866
  );
@@ -901,16 +888,15 @@ export default async function (pi: ExtensionAPI): Promise<void> {
901
888
  proactiveCompaction.getCompactionSettings(),
902
889
  );
903
890
  let refreshModelsForFast: ((ctx: ExtensionContext) => Promise<void>) | undefined;
904
- const onFastModeChange = async (_enabled: boolean, ctx: ExtensionContext): Promise<void> => {
905
- await refreshModelsForFast?.(ctx);
906
- };
907
- registerFastCommand({
891
+ registerFastCommands({
908
892
  pi,
909
893
  agentDir,
910
894
  providerId: identity.providerId,
911
895
  fastMode,
912
896
  onStatusChange: (ctx) => fastFooter.refresh(ctx),
913
- onModeChange: onFastModeChange,
897
+ onModeChange: async (ctx) => {
898
+ await refreshModelsForFast?.(ctx);
899
+ },
914
900
  });
915
901
  fastFooter.register(pi);
916
902
 
@@ -950,7 +936,6 @@ export default async function (pi: ExtensionAPI): Promise<void> {
950
936
  streamSimple,
951
937
  fastMode,
952
938
  refreshCoordinator: modelRefreshCoordinator,
953
- onFastModeChange: onFastModeChange,
954
939
  onRefreshOutcome: handleRefreshOutcome,
955
940
  });
956
941
  registerTransientNetworkErrorRetry(pi, identity.providerId);
@@ -1039,7 +1024,6 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1039
1024
  streamSimple,
1040
1025
  fastMode,
1041
1026
  refreshCoordinator: modelRefreshCoordinator,
1042
- onFastModeChange,
1043
1027
  onRefreshOutcome: handleRefreshOutcome,
1044
1028
  });
1045
1029
 
package/extensions/lib.ts CHANGED
@@ -6,6 +6,7 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
6
  import { tmpdir } from "node:os";
7
7
  import { dirname, join } from "node:path";
8
8
  import { readStoredCredential } from "@earendil-works/pi-coding-agent";
9
+ import type { FastPreference } from "./fast.ts";
9
10
 
10
11
  // Local shape matching pi ThinkingLevelMap; avoid hard runtime peer imports here.
11
12
  export type ThinkingLevelMap = Partial<
@@ -41,7 +42,7 @@ export interface CliproxyConfigFile {
41
42
  apiKey?: string;
42
43
  providerId?: string;
43
44
  providerName?: string;
44
- fast?: boolean;
45
+ fast?: FastPreference;
45
46
  pause?: boolean;
46
47
  }
47
48
 
@@ -312,7 +313,8 @@ export function isModelReferencedAsDefault(
312
313
  return false;
313
314
  }
314
315
 
315
- export function saveConfigFile(agentDir: string, config: CliproxyConfigFile): void {
316
+ /** Merge the config update and return the previous values for callers that need to roll back. */
317
+ export function saveConfigFile(agentDir: string, config: CliproxyConfigFile): CliproxyConfigFile {
316
318
  const configPath = join(agentDir, CONFIG_FILE_NAME);
317
319
  mkdirSync(dirname(configPath), { recursive: true });
318
320
 
@@ -322,6 +324,7 @@ export function saveConfigFile(agentDir: string, config: CliproxyConfigFile): vo
322
324
  ...config,
323
325
  };
324
326
  writeFileSync(configPath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
327
+ return existing;
325
328
  }
326
329
 
327
330
  export function loadModelsCache(agentDir: string, baseUrlInput: string): ModelsCacheFile | null {
@@ -397,8 +400,8 @@ export function parseBooleanSetting(value: string): boolean | undefined {
397
400
  }
398
401
  }
399
402
 
400
- /** Resolve the Fast preference from env, then cliproxyapi.json, then false. */
401
- export function resolveFastDefault(agentDir: string): boolean {
403
+ /** Resolve the speed preference from the boolean env override, then config, then false. */
404
+ export function resolveFastDefault(agentDir: string): FastPreference {
402
405
  const envValue = firstNonEmpty(process.env.CLIPROXYAPI_FAST);
403
406
  if (envValue !== undefined) {
404
407
  const parsed = parseBooleanSetting(envValue);
@@ -412,8 +415,8 @@ export function resolveFastDefault(agentDir: string): boolean {
412
415
  if (file.fast === undefined) {
413
416
  return false;
414
417
  }
415
- if (typeof file.fast !== "boolean") {
416
- throw new Error(`${CONFIG_FILE_NAME} field "fast" must be a boolean`);
418
+ if (typeof file.fast !== "boolean" && file.fast !== "ultrafast") {
419
+ throw new Error(`${CONFIG_FILE_NAME} field "fast" must be a boolean or "ultrafast"`);
417
420
  }
418
421
  return file.fast;
419
422
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@router-for-me/pi-cliproxyapi-provider",
3
- "version": "1.4.26",
3
+ "version": "1.5.0",
4
4
  "description": "Pi provider extension that auto-registers CLIProxyAPI models, plus TUI elapsed/TPS status",
5
5
  "type": "module",
6
6
  "keywords": [