@router-for-me/pi-cliproxyapi-provider 1.4.7 → 1.4.9

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
@@ -11,6 +11,7 @@ Pi provider extension that discovers models from [CLIProxyAPI](https://github.co
11
11
  5. Registers inference against `{root}/backend-api/`.
12
12
  6. Provides `/fast` to toggle OpenAI priority processing for supported models.
13
13
  7. In interactive TUI sessions, shows footer elapsed time during runs and a TPS / token usage toast when the agent settles.
14
+ 8. Proactively ends over-threshold CLIProxyAPI tool turns so pi can compact and retry before a long tool chain fills the context window.
14
15
 
15
16
  ## Install
16
17
 
@@ -145,6 +146,34 @@ When Fast is effective, pi's model status appends a yellow lowercase `fast`, for
145
146
 
146
147
  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.
147
148
 
149
+ ## Proactive compaction during tool runs
150
+
151
+ Pi normally checks its automatic compaction threshold after an agent run settles or before the next user prompt. A single agent run can contain many consecutive tool turns, so it may otherwise grow well beyond the configured threshold before pi gets another check opportunity.
152
+
153
+ For CLIProxyAPI models, this package also checks each completed tool turn. It reloads pi's existing merged compaction settings from `~/.pi/agent/settings.json` and the trusted project `.pi/settings.json`. When all of the following are true:
154
+
155
+ - `compaction.enabled` is `true`
156
+ - the completed assistant response requested tools
157
+ - reported context usage exceeds `contextWindow - compaction.reserveTokens`
158
+
159
+ …the package schedules a recognized `context_length_exceeded` error instead of sending the next provider request. Pi's built-in overflow recovery then compacts the session and retries automatically. The current tool batch finishes before this check, so the package does not discard valid tool calls or repeat completed tool operations.
160
+
161
+ No separate CLIProxyAPI setting is required. For example:
162
+
163
+ ```json
164
+ {
165
+ "compaction": {
166
+ "enabled": true,
167
+ "reserveTokens": 65536,
168
+ "keepRecentTokens": 20000
169
+ }
170
+ }
171
+ ```
172
+
173
+ This only adds an earlier check point for the provider registered by this package. Summary generation, retained context, session persistence, and retry execution remain handled by pi.
174
+
175
+ In the TUI footer, CLIProxyAPI context usage also uses this effective threshold as its denominator. With a `372000` model window and `reserveTokens: 65536`, the footer displays `/306k`; the percentage is recalculated against `306464`, so `100%` corresponds to the proactive compaction threshold rather than the model's absolute limit. Disabling automatic compaction restores the full model window display.
176
+
148
177
  ## Model mapping
149
178
 
150
179
  From CPA catalog entry → pi model:
@@ -180,6 +209,7 @@ Disable just this helper via `pi config` if you only want the CLIProxyAPI provid
180
209
 
181
210
  ## Failure behavior
182
211
 
212
+ - CLIProxyAPI `closed network connection` responses are normalized as transient network errors so pi's agent-level retry policy reconnects and restarts the interrupted assistant turn. Completed conversation and tool results remain available; token streaming does not resume from the exact interruption point.
183
213
  - Before setup / without credentials: provider still appears in `/login`; no models are listed yet.
184
214
  - After successful `/login`: models are registered; credentials are stored in `auth.json` and mirrored to `cliproxyapi.json`.
185
215
  - The built-in `/logout` command removes only the matching `auth.json` credential; environment variables and `cliproxyapi.json` are unchanged.
@@ -0,0 +1,147 @@
1
+ import { type Api, type AssistantMessage, createAssistantMessageEventStream, type Model } from "@earendil-works/pi-ai";
2
+ import { type ExtensionAPI, SettingsManager } from "@earendil-works/pi-coding-agent";
3
+ import type { CliproxyCodexStreamSimple } from "./codex-stream.ts";
4
+
5
+ export const PROACTIVE_COMPACTION_ERROR_PREFIX = "context_length_exceeded: proactive compaction threshold reached";
6
+
7
+ export interface ProactiveCompactionSettings {
8
+ enabled: boolean;
9
+ reserveTokens: number;
10
+ }
11
+
12
+ export function shouldScheduleProactiveCompaction(
13
+ message: AssistantMessage,
14
+ contextTokens: number,
15
+ contextWindow: number,
16
+ settings: ProactiveCompactionSettings,
17
+ ): boolean {
18
+ if (!settings.enabled || message.stopReason !== "toolUse") {
19
+ return false;
20
+ }
21
+ if (!message.content.some((block) => block.type === "toolCall")) {
22
+ return false;
23
+ }
24
+ if (!Number.isFinite(contextTokens) || contextTokens <= 0) {
25
+ return false;
26
+ }
27
+ if (!Number.isFinite(contextWindow) || contextWindow <= 0) {
28
+ return false;
29
+ }
30
+ if (!Number.isFinite(settings.reserveTokens) || settings.reserveTokens < 0) {
31
+ return false;
32
+ }
33
+
34
+ return contextTokens > contextWindow - settings.reserveTokens;
35
+ }
36
+
37
+ export function createProactiveCompactionStream(model: Model<Api>, contextTokens: number, threshold: number) {
38
+ const stream = createAssistantMessageEventStream();
39
+ const output: AssistantMessage = {
40
+ role: "assistant",
41
+ content: [],
42
+ api: model.api,
43
+ provider: model.provider,
44
+ model: model.id,
45
+ usage: {
46
+ input: 0,
47
+ output: 0,
48
+ cacheRead: 0,
49
+ cacheWrite: 0,
50
+ totalTokens: 0,
51
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
52
+ },
53
+ stopReason: "error",
54
+ errorMessage: `${PROACTIVE_COMPACTION_ERROR_PREFIX} (${contextTokens} > ${threshold})`,
55
+ timestamp: Date.now(),
56
+ };
57
+
58
+ queueMicrotask(() => {
59
+ stream.push({ type: "start", partial: output });
60
+ stream.push({ type: "error", reason: "error", error: output });
61
+ stream.end();
62
+ });
63
+
64
+ return stream;
65
+ }
66
+
67
+ export class ProactiveCompactionController {
68
+ private settingsManager: SettingsManager | undefined;
69
+ private pending: { modelKey: string; contextTokens: number; threshold: number } | undefined;
70
+
71
+ constructor(
72
+ private readonly agentDir: string,
73
+ private readonly providerId: string,
74
+ ) {}
75
+
76
+ register(pi: ExtensionAPI): void {
77
+ pi.on("session_start", (_event, ctx) => {
78
+ this.settingsManager = SettingsManager.create(ctx.cwd, this.agentDir, {
79
+ projectTrusted: ctx.isProjectTrusted(),
80
+ });
81
+ this.pending = undefined;
82
+ });
83
+
84
+ pi.on("session_shutdown", () => {
85
+ this.settingsManager = undefined;
86
+ this.pending = undefined;
87
+ });
88
+
89
+ pi.on("session_compact", () => {
90
+ this.pending = undefined;
91
+ });
92
+
93
+ pi.on("agent_settled", () => {
94
+ this.pending = undefined;
95
+ });
96
+
97
+ pi.on("turn_end", async (event, ctx) => {
98
+ const message = event.message;
99
+ if (message.role !== "assistant" || message.provider !== this.providerId) {
100
+ return;
101
+ }
102
+ if (!ctx.model || ctx.model.provider !== this.providerId || ctx.model.id !== message.model) {
103
+ return;
104
+ }
105
+
106
+ const settingsManager = this.settingsManager;
107
+ if (!settingsManager) {
108
+ return;
109
+ }
110
+ await settingsManager.reload();
111
+ const settings = settingsManager.getCompactionSettings();
112
+ const contextTokens = ctx.getContextUsage()?.tokens;
113
+ if (contextTokens === null || contextTokens === undefined) {
114
+ return;
115
+ }
116
+ if (!shouldScheduleProactiveCompaction(message, contextTokens, ctx.model.contextWindow, settings)) {
117
+ return;
118
+ }
119
+
120
+ this.pending = {
121
+ modelKey: this.modelKey(ctx.model),
122
+ contextTokens,
123
+ threshold: ctx.model.contextWindow - settings.reserveTokens,
124
+ };
125
+ });
126
+ }
127
+
128
+ getCompactionSettings(): ProactiveCompactionSettings | undefined {
129
+ return this.settingsManager?.getCompactionSettings();
130
+ }
131
+
132
+ wrapStreamSimple(streamSimple: CliproxyCodexStreamSimple): CliproxyCodexStreamSimple {
133
+ return (model, context, options) => {
134
+ const pending = this.pending;
135
+ if (!pending || pending.modelKey !== this.modelKey(model)) {
136
+ return streamSimple(model, context, options);
137
+ }
138
+
139
+ this.pending = undefined;
140
+ return createProactiveCompactionStream(model, pending.contextTokens, pending.threshold);
141
+ };
142
+ }
143
+
144
+ private modelKey(model: Pick<Model<Api>, "provider" | "id">): string {
145
+ return `${model.provider}/${model.id}`;
146
+ }
147
+ }
@@ -99,11 +99,16 @@ function rewriteRelativeImports(source: string, originalDir: string): string {
99
99
  }
100
100
 
101
101
  function patchWebSocketOnlyTransport(source: string): string {
102
- const disabledForSession =
103
- /const websocketDisabledForSession\s*=\s*transport !== "sse" && isWebSocketSseFallbackActive\(options\?\.sessionId\);/;
102
+ const sessionIdExpression = String.raw`(?:options\?\.sessionId|cacheSessionId)`;
103
+ const disabledForSession = new RegExp(
104
+ String.raw`const websocketDisabledForSession\s*=\s*transport !== "sse" && isWebSocketSseFallbackActive\(${sessionIdExpression}\);`,
105
+ );
104
106
  const retryVariables = /let retriedWebSocketConnectionLimit\s*=\s*false;/;
105
- const websocketFailureHandling =
106
- /const connectionLimitBeforeStart = !websocketStarted && isWebSocketConnectionLimitReachedError\(error\);[\s\S]*?recordWebSocketSseFallback\(options\?\.sessionId\);\s*break;/;
107
+ const connectionLimitRetry =
108
+ /if \(!aborted && connectionLimitBeforeStart && !retriedWebSocketConnectionLimit\) \{\s*retriedWebSocketConnectionLimit = true;\s*continue;\s*\}/;
109
+ const websocketFailureHandling = new RegExp(
110
+ String.raw`if \(aborted \|\| \(isCodexNonTransportError\(error\) && !connectionLimitBeforeStart\)\) \{[\s\S]*?recordWebSocketFailure\((${sessionIdExpression}), error\);[\s\S]*?recordWebSocketSseFallback\(\1\);\s*break;`,
111
+ );
107
112
  const fallbackSessionRecord = "websocketSseFallbackSessions.add(sessionId);";
108
113
  const fallbackActiveRecord = "stats.websocketFallbackActive = true;";
109
114
 
@@ -112,7 +117,7 @@ function patchWebSocketOnlyTransport(source: string): string {
112
117
  throw new Error("openai-codex-responses source no longer supports the WebSocket-only transport patch");
113
118
  }
114
119
  }
115
- for (const pattern of [disabledForSession, retryVariables, websocketFailureHandling]) {
120
+ for (const pattern of [disabledForSession, retryVariables, connectionLimitRetry, websocketFailureHandling]) {
116
121
  if (!pattern.test(source)) {
117
122
  throw new Error("openai-codex-responses source no longer supports the WebSocket-only transport patch");
118
123
  }
@@ -127,10 +132,13 @@ function patchWebSocketOnlyTransport(source: string): string {
127
132
  ? Math.min(Math.max(0, Math.floor(options.maxRetries)), 5)
128
133
  : 3;`,
129
134
  )
135
+ .replace(connectionLimitRetry, "")
130
136
  .replace(
131
137
  websocketFailureHandling,
132
- `const connectionLimitBeforeStart = !websocketStarted && isWebSocketConnectionLimitReachedError(error);
133
- if (aborted || (isCodexNonTransportError(error) && !connectionLimitBeforeStart)) {
138
+ (
139
+ _match,
140
+ activeSessionId: string,
141
+ ) => `if (aborted || (isCodexNonTransportError(error) && !connectionLimitBeforeStart)) {
134
142
  throw error;
135
143
  }
136
144
  if (!websocketStarted && websocketRetries < maxWebSocketRetries) {
@@ -144,7 +152,7 @@ function patchWebSocketOnlyTransport(source: string): string {
144
152
  phase: websocketStarted ? "after_message_stream_start" : "before_message_stream_start",
145
153
  requestBytes: new TextEncoder().encode(bodyJson).byteLength,
146
154
  }));
147
- recordWebSocketFailure(options?.sessionId, error);
155
+ recordWebSocketFailure(${activeSessionId}, error);
148
156
  throw error;`,
149
157
  )
150
158
  .replace(fallbackSessionRecord, "")
@@ -1,4 +1,5 @@
1
1
  import { type ExtensionAPI, type ExtensionContext, FooterComponent } from "@earendil-works/pi-coding-agent";
2
+ import type { ProactiveCompactionSettings } from "./auto-compact.ts";
2
3
  import type { FastModeController } from "./fast.ts";
3
4
 
4
5
  const FAST_FOOTER_PATCH = Symbol.for("@router-for-me/pi-cliproxyapi-provider/fast-footer-patch");
@@ -8,6 +9,7 @@ interface MutableModel {
8
9
  id: string;
9
10
  provider: string;
10
11
  reasoning: boolean;
12
+ contextWindow: number;
11
13
  }
12
14
 
13
15
  interface FooterSessionLike {
@@ -19,6 +21,7 @@ interface FooterSessionLike {
19
21
 
20
22
  interface FooterComponentLike {
21
23
  session?: FooterSessionLike;
24
+ autoCompactEnabled?: boolean;
22
25
  }
23
26
 
24
27
  interface FooterPatchState {
@@ -57,12 +60,13 @@ function installFooterPatch(controller: FastFooterController): void {
57
60
  controllers: new Set(),
58
61
  originalRender,
59
62
  patchedRender(this: FooterComponent, width: number): string[] {
60
- const session = (this as unknown as FooterComponentLike).session;
63
+ const footer = this as unknown as FooterComponentLike;
64
+ const session = footer.session;
61
65
  const model = session?.state.model;
62
66
  let activeController: FastFooterController | undefined;
63
67
  if (model) {
64
68
  for (const candidate of patchState?.controllers ?? []) {
65
- if (candidate.isEffectiveFor(model)) {
69
+ if (candidate.isProviderModel(model)) {
66
70
  activeController = candidate;
67
71
  break;
68
72
  }
@@ -74,17 +78,25 @@ function installFooterPatch(controller: FastFooterController): void {
74
78
 
75
79
  const originalId = model.id;
76
80
  const originalReasoning = model.reasoning;
77
- model.id = activeController.formatModelStatus(
78
- originalId,
79
- originalReasoning,
80
- session?.state.thinkingLevel ?? "off",
81
+ const originalContextWindow = model.contextWindow;
82
+ if (activeController.isEffectiveFor(model)) {
83
+ model.id = activeController.formatModelStatus(
84
+ originalId,
85
+ originalReasoning,
86
+ session?.state.thinkingLevel ?? "off",
87
+ );
88
+ model.reasoning = false;
89
+ }
90
+ model.contextWindow = activeController.getDisplayContextWindow(
91
+ originalContextWindow,
92
+ footer.autoCompactEnabled ?? false,
81
93
  );
82
- model.reasoning = false;
83
94
  try {
84
95
  return originalRender.call(this, width);
85
96
  } finally {
86
97
  model.id = originalId;
87
98
  model.reasoning = originalReasoning;
99
+ model.contextWindow = originalContextWindow;
88
100
  }
89
101
  },
90
102
  };
@@ -115,6 +127,7 @@ export class FastFooterController {
115
127
  constructor(
116
128
  private readonly providerId: string,
117
129
  private readonly fastMode: FastModeController,
130
+ private readonly resolveCompactionSettings: () => ProactiveCompactionSettings | undefined = () => undefined,
118
131
  ) {}
119
132
 
120
133
  register(pi: ExtensionAPI): void {
@@ -138,8 +151,21 @@ export class FastFooterController {
138
151
  return formatFastModelStatus(modelName, supportsReasoning, thinkingLevel, true, fastLabel);
139
152
  }
140
153
 
154
+ isProviderModel(model: MutableModel): boolean {
155
+ return model.provider === this.providerId;
156
+ }
157
+
141
158
  isEffectiveFor(model: MutableModel): boolean {
142
- return model.provider === this.providerId && this.fastMode.isEffectiveFor(model.id);
159
+ return this.isProviderModel(model) && this.fastMode.isEffectiveFor(model.id);
160
+ }
161
+
162
+ getDisplayContextWindow(contextWindow: number, autoCompactEnabled: boolean): number {
163
+ const settings = this.resolveCompactionSettings();
164
+ if (!autoCompactEnabled || !settings || !Number.isFinite(settings.reserveTokens) || settings.reserveTokens < 0) {
165
+ return contextWindow;
166
+ }
167
+ const availableContextWindow = contextWindow - settings.reserveTokens;
168
+ return availableContextWindow > 0 ? availableContextWindow : contextWindow;
143
169
  }
144
170
 
145
171
  refresh(ctx: ExtensionContext): void {
@@ -20,6 +20,7 @@
20
20
 
21
21
  import type { Api, Model, OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
22
22
  import { type ExtensionAPI, type ExtensionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
23
+ import { ProactiveCompactionController } from "./auto-compact.ts";
23
24
  import { CLIPROXYAPI_CODEX_API, type CliproxyCodexStreamSimple, loadCliproxyCodexStreams } from "./codex-stream.ts";
24
25
  import { FastModeController } from "./fast.ts";
25
26
  import { FastFooterController } from "./fast-footer.ts";
@@ -41,6 +42,7 @@ import {
41
42
  resolveIdentity,
42
43
  saveConfigFile,
43
44
  } from "./lib.ts";
45
+ import { registerTransientNetworkErrorRetry } from "./retry.ts";
44
46
 
45
47
  class ConfigPersistenceError extends Error {
46
48
  constructor(cause: unknown) {
@@ -347,6 +349,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
347
349
  const agentDir = getAgentDir();
348
350
  const identity = resolveIdentity(agentDir);
349
351
  const defaultBaseUrl = resolveDefaultBaseUrl(agentDir, identity.providerId);
352
+ const proactiveCompaction = new ProactiveCompactionController(agentDir, identity.providerId);
353
+ proactiveCompaction.register(pi);
350
354
 
351
355
  let fastEnabled = false;
352
356
  try {
@@ -362,14 +366,16 @@ export default async function (pi: ExtensionAPI): Promise<void> {
362
366
  const streams = await loadCliproxyCodexStreams([identity.providerId, "cliproxyapi"], {
363
367
  shouldUseFast: (model) => model.provider === identity.providerId && fastMode.isEffectiveFor(model.id),
364
368
  });
365
- streamSimple = streams.streamSimple;
369
+ streamSimple = proactiveCompaction.wrapStreamSimple(streams.streamSimple);
366
370
  } catch (error) {
367
371
  const message = error instanceof Error ? error.message : String(error);
368
372
  logWarn(`failed to load patched codex protocol: ${message}`);
369
373
  return;
370
374
  }
371
375
 
372
- const fastFooter = new FastFooterController(identity.providerId, fastMode);
376
+ const fastFooter = new FastFooterController(identity.providerId, fastMode, () =>
377
+ proactiveCompaction.getCompactionSettings(),
378
+ );
373
379
  registerFastCommand({
374
380
  pi,
375
381
  agentDir,
@@ -389,6 +395,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
389
395
  streamSimple,
390
396
  fastMode,
391
397
  });
398
+ registerTransientNetworkErrorRetry(pi, identity.providerId);
392
399
 
393
400
  const connection = resolveConnection(agentDir, identity.providerId);
394
401
  if (!connection) {
@@ -0,0 +1,34 @@
1
+ import { type AssistantMessage, isRetryableAssistantError } from "@earendil-works/pi-ai";
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+
4
+ const CLOSED_NETWORK_CONNECTION_PATTERN = /\bclosed network connection\b/i;
5
+ const NETWORK_ERROR_PREFIX = "network error:";
6
+
7
+ export function normalizeTransientNetworkError(message: AssistantMessage): AssistantMessage {
8
+ if (message.stopReason !== "error" || !message.errorMessage) {
9
+ return message;
10
+ }
11
+ if (isRetryableAssistantError(message) || !CLOSED_NETWORK_CONNECTION_PATTERN.test(message.errorMessage)) {
12
+ return message;
13
+ }
14
+
15
+ return {
16
+ ...message,
17
+ errorMessage: `${NETWORK_ERROR_PREFIX} ${message.errorMessage}`,
18
+ };
19
+ }
20
+
21
+ export function registerTransientNetworkErrorRetry(pi: ExtensionAPI, providerId: string): void {
22
+ pi.on("message_end", (event) => {
23
+ const message = event.message;
24
+ if (message.role !== "assistant" || message.provider !== providerId) {
25
+ return;
26
+ }
27
+
28
+ const normalized = normalizeTransientNetworkError(message);
29
+ if (normalized === message) {
30
+ return;
31
+ }
32
+ return { message: normalized };
33
+ });
34
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@router-for-me/pi-cliproxyapi-provider",
3
- "version": "1.4.7",
3
+ "version": "1.4.9",
4
4
  "description": "Pi provider extension that auto-registers CLIProxyAPI models, plus TUI elapsed/TPS status",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -39,12 +39,12 @@
39
39
  },
40
40
  "peerDependencies": {
41
41
  "@earendil-works/pi-ai": "*",
42
- "@earendil-works/pi-coding-agent": ">=0.80.9 <0.81.0"
42
+ "@earendil-works/pi-coding-agent": ">=0.82.0"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@biomejs/biome": "2.5.3",
46
- "@earendil-works/pi-ai": "0.80.9",
47
- "@earendil-works/pi-coding-agent": "0.80.9",
46
+ "@earendil-works/pi-ai": "0.82.0",
47
+ "@earendil-works/pi-coding-agent": "0.82.0",
48
48
  "@types/node": "^22.15.21",
49
49
  "typescript": "6.0.3",
50
50
  "vitest": "4.1.9"