@router-for-me/pi-cliproxyapi-provider 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Router-For.ME
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,175 @@
1
+ # pi-cliproxyapi-provider
2
+
3
+ Pi provider extension that discovers models from [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) and registers them for use with the `openai-codex-responses` API.
4
+
5
+ ## What it does
6
+
7
+ 1. Registers a provider that always appears in `/login` (subscription path) and via `/cliproxyapi` / `/cpa`.
8
+ 2. Interactive setup collects `baseUrl` + `apiKey`.
9
+ 3. Fetches `{root}/v1/models?client_version=pi`.
10
+ 4. Maps the Codex client catalog into pi models.
11
+ 5. Registers inference against `{root}/backend-api/` using a **patched** Codex Responses protocol (`cliproxyapi-codex-responses`).
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ # from npm
17
+ pi install npm:@router-for-me/pi-cliproxyapi-provider
18
+
19
+ # from a local checkout
20
+ pi install /absolute/path/to/pi-cliproxyapi-provider
21
+
22
+ # or temporarily for one run
23
+ pi -e /absolute/path/to/pi-cliproxyapi-provider
24
+ ```
25
+
26
+ ## Login-style setup (recommended)
27
+
28
+ This plugin needs both **baseUrl** and **apiKey**. pi's built-in `/login` only supports multi-field prompts on the OAuth/subscription path, so CLIProxyAPI appears under **Use a subscription** (not API key).
29
+
30
+ ### Preferred: dedicated command (when not yet authenticated)
31
+
32
+ ```text
33
+ /cliproxyapi
34
+ ```
35
+
36
+ or short alias:
37
+
38
+ ```text
39
+ /cpa
40
+ ```
41
+
42
+ These slash commands appear only when setup is needed. After a successful login they are **hidden** from the `/` menu. They reappear when:
43
+
44
+ - you run `/logout` and remove CLIProxyAPI credentials
45
+ - a models request returns **HTTP 401**
46
+
47
+ To reconfigure while still authenticated, use `/login CLIProxyAPI`.
48
+
49
+ ### Or use /login shortcuts (skip the menu)
50
+
51
+ ```text
52
+ /login CLIProxyAPI
53
+ ```
54
+
55
+ or:
56
+
57
+ ```text
58
+ /login cliproxyapi
59
+ ```
60
+
61
+ ### Menu path
62
+
63
+ ```text
64
+ /login
65
+ ```
66
+
67
+ Then choose:
68
+
69
+ 1. **Use a subscription**
70
+ (required for multi-field baseUrl + API key prompts)
71
+ 2. **CLIProxyAPI**
72
+ 3. Enter:
73
+ - base URL — preferred form is host:port, e.g. `http://127.0.0.1:8317`
74
+ - API key
75
+
76
+ Final login validation calls `{root}/v1/models?client_version=pi`:
77
+
78
+ - **HTTP 200** → login succeeds (empty model list is still OK)
79
+ - **non-200 / network error** → login fails and you are prompted to re-enter base URL + API key
80
+
81
+ On success (any of the paths above):
82
+
83
+ - models are registered immediately in the current session (0 models is allowed)
84
+ - credentials are stored in `~/.pi/agent/auth.json`
85
+ - `baseUrl` / `apiKey` are also written to `~/.pi/agent/cliproxyapi.json`
86
+
87
+ Re-run `/cliproxyapi`, `/cpa`, or `/login CLIProxyAPI` anytime to reconfigure.
88
+
89
+ ## Non-interactive configuration
90
+
91
+ You can still configure without `/login`.
92
+
93
+ ### Config file
94
+
95
+ `~/.pi/agent/cliproxyapi.json`:
96
+
97
+ ```json
98
+ {
99
+ "baseUrl": "http://127.0.0.1:8317",
100
+ "apiKey": "12345"
101
+ }
102
+ ```
103
+
104
+ Optional fields:
105
+
106
+ | Field | Default | Description |
107
+ |-------|---------|-------------|
108
+ | `baseUrl` | `http://127.0.0.1:8317` | CLIProxyAPI address |
109
+ | `apiKey` | _(required unless set via /login or env)_ | Bearer token / CPA API key |
110
+ | `providerId` | `cliproxyapi` | Provider id shown in `/model` |
111
+ | `providerName` | `CLIProxyAPI` | Display name in `/login` and UI |
112
+
113
+ ### Environment overrides
114
+
115
+ | Variable | Overrides |
116
+ |----------|-----------|
117
+ | `CLIPROXYAPI_BASE_URL` | `baseUrl` |
118
+ | `CLIPROXYAPI_API_KEY` | `apiKey` |
119
+ | `CLIPROXYAPI_PROVIDER_ID` | `providerId` |
120
+ | `CLIPROXYAPI_PROVIDER_NAME` | `providerName` |
121
+
122
+ Resolution order for connection settings:
123
+
124
+ 1. Environment variables
125
+ 2. `cliproxyapi.json`
126
+ 3. `/login` credentials in `auth.json`
127
+ 4. Default baseUrl `http://127.0.0.1:8317`
128
+
129
+ ### baseUrl normalization
130
+
131
+ Preferred form is **host:port only**:
132
+
133
+ | Input | Inference baseUrl | Models URL |
134
+ |-------|-------------------|------------|
135
+ | `http://127.0.0.1:8317` | `http://127.0.0.1:8317/backend-api/` | `http://127.0.0.1:8317/v1/models?client_version=pi` |
136
+ | `http://127.0.0.1:8317/backend-api` | `http://127.0.0.1:8317/backend-api/` | same models URL |
137
+ | `http://127.0.0.1:8317/v1` | `http://127.0.0.1:8317/backend-api/` | same models URL |
138
+ | `127.0.0.1:8317` | `http://127.0.0.1:8317/backend-api/` | same models URL |
139
+
140
+ pi then calls `{inference}/codex/responses` via this package's patched Codex Responses stream implementation.
141
+
142
+ ## Model mapping
143
+
144
+ From CPA Codex catalog entry → pi model:
145
+
146
+ | CPA field | Pi field |
147
+ |-----------|----------|
148
+ | `slug` | `id` |
149
+ | `display_name` | `name` |
150
+ | `context_window` | `contextWindow` |
151
+ | `input_modalities` | `input` (`text` / `image`) |
152
+ | `supported_reasoning_levels[].effort` | `thinkingLevelMap` + `reasoning` |
153
+ | `visibility: "hide"` | skipped |
154
+
155
+ Unsupported pi thinking levels are set to `null` so they are hidden in the UI. Cost is reported as zero (proxy pricing is unknown).
156
+
157
+ ## Migration from static models.json
158
+
159
+ If you previously maintained a static provider such as `cpa-responses` in `~/.pi/agent/models.json`:
160
+
161
+ 1. Install this package and run `/cliproxyapi` or `/login CLIProxyAPI` (or set `cliproxyapi.json`).
162
+ 2. Point `defaultProvider` / `enabledModels` at `cliproxyapi/<model-id>` (or set `providerId` to `cpa-responses` for a drop-in id).
163
+ 3. Remove the hand-maintained models array once the dynamic list looks correct.
164
+
165
+ ## Failure behavior
166
+
167
+ - Before setup / without credentials: provider still appears in `/login`; `/cliproxyapi` and `/cpa` are shown; no models are listed yet.
168
+ - After successful login: `/cliproxyapi` and `/cpa` are hidden; reconfigure via `/login CLIProxyAPI` if needed.
169
+ - After `/logout` for CLIProxyAPI: setup commands reappear for reconfiguration.
170
+ - If a models request returns **HTTP 401**: setup commands reappear for reconfiguration.
171
+ - If CPA is unreachable during startup (non-401): a warning is logged; setup commands stay available via `/cliproxyapi` or `/login`.
172
+ - Login/setup final step validates credentials by requesting models:
173
+ - HTTP 200 (including empty catalog) → credentials are persisted; setup commands hidden
174
+ - non-200 / network / invalid baseUrl → nothing is persisted; re-enter baseUrl + API key
175
+ - If CPA returns HTTP 200 with zero usable models: login still succeeds; re-run setup later after models become available.
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Load a patched openai-codex-responses implementation for CLIProxyAPI.
3
+ *
4
+ * Differences from stock pi-ai:
5
+ * - extractAccountId never throws; plain API keys are allowed
6
+ * - chatgpt-account-id header is omitted when account id is unavailable
7
+ * - provider id(s) are added to CODEX_TOOL_CALL_PROVIDERS for tool-call id handling
8
+ * - model/message api id uses cliproxyapi-codex-responses
9
+ *
10
+ * The patched module is derived at runtime from the installed
11
+ * @earendil-works/pi-ai openai-codex-responses implementation so we track
12
+ * upstream protocol fixes without vendoring 1200+ lines.
13
+ */
14
+
15
+ import { createHash } from "node:crypto";
16
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
17
+ import { tmpdir } from "node:os";
18
+ import { dirname, join } from "node:path";
19
+ import { fileURLToPath, pathToFileURL } from "node:url";
20
+ import type { Api, AssistantMessageEventStream, Context, Model, SimpleStreamOptions } from "@earendil-works/pi-ai";
21
+
22
+ export const CLIPROXYAPI_CODEX_API = "cliproxyapi-codex-responses" as const;
23
+
24
+ export type CliproxyCodexStreamSimple = (
25
+ model: Model<Api>,
26
+ context: Context,
27
+ options?: SimpleStreamOptions,
28
+ ) => AssistantMessageEventStream;
29
+
30
+ export type CliproxyCodexStreams = {
31
+ streamSimple: CliproxyCodexStreamSimple;
32
+ stream: CliproxyCodexStreamSimple;
33
+ api: typeof CLIPROXYAPI_CODEX_API;
34
+ };
35
+
36
+ const EXTRACT_ACCOUNT_ID_PATCH = `function extractAccountId(token) {
37
+ // CLIProxyAPI accepts plain API keys as well as ChatGPT JWTs.
38
+ // Never throw: missing account id simply means no chatgpt-account-id header.
39
+ try {
40
+ const parts = token.split(".");
41
+ if (parts.length !== 3)
42
+ return "";
43
+ const payload = JSON.parse(atob(parts[1]));
44
+ const accountId = payload?.[JWT_CLAIM_PATH]?.chatgpt_account_id;
45
+ return typeof accountId === "string" && accountId.trim() ? accountId : "";
46
+ }
47
+ catch {
48
+ return "";
49
+ }
50
+ }`;
51
+
52
+ function rewriteRelativeImports(source: string, originalDir: string): string {
53
+ return source.replace(/from\s+"((?:\.\.?\/)[^"]+)"/g, (_full, relPath: string) => {
54
+ const absolute = pathToFileURL(join(originalDir, relPath)).href;
55
+ return `from ${JSON.stringify(absolute)}`;
56
+ });
57
+ }
58
+
59
+ function patchCodexSource(source: string, providerIds: string[]): string {
60
+ let src = source;
61
+
62
+ if (!/function extractAccountId\(token\) \{/.test(src)) {
63
+ throw new Error("openai-codex-responses source no longer contains extractAccountId(token)");
64
+ }
65
+ src = src.replace(/function extractAccountId\(token\) \{[\s\S]*?\n\}/, EXTRACT_ACCOUNT_ID_PATCH);
66
+
67
+ if (!src.includes(`headers.set("chatgpt-account-id", accountId);`)) {
68
+ throw new Error("openai-codex-responses source no longer sets chatgpt-account-id");
69
+ }
70
+ src = src.replace(
71
+ `headers.set("chatgpt-account-id", accountId);`,
72
+ `if (accountId) {\n headers.set("chatgpt-account-id", accountId);\n }`,
73
+ );
74
+
75
+ const providersMatch = src.match(/const CODEX_TOOL_CALL_PROVIDERS = new Set\(\[([^\]]*)\]\);/);
76
+ if (!providersMatch) {
77
+ throw new Error("openai-codex-responses source no longer defines CODEX_TOOL_CALL_PROVIDERS");
78
+ }
79
+ const existing = providersMatch[1];
80
+ const extras = providerIds
81
+ .filter((id) => id.trim())
82
+ .map((id) => JSON.stringify(id.trim()))
83
+ .join(", ");
84
+ src = src.replace(
85
+ /const CODEX_TOOL_CALL_PROVIDERS = new Set\(\[([^\]]*)\]\);/,
86
+ `const CODEX_TOOL_CALL_PROVIDERS = new Set([${existing}${extras ? `, ${extras}` : ""}]);`,
87
+ );
88
+
89
+ // Keep assistant message api metadata aligned with the registered custom api id.
90
+ src = src.replaceAll(`api: "openai-codex-responses"`, `api: ${JSON.stringify(CLIPROXYAPI_CODEX_API)}`);
91
+
92
+ return src;
93
+ }
94
+
95
+ function resolveOriginalCodexModulePath(): { path: string; dir: string } {
96
+ // Under pi's extension loader, `@earendil-works/pi-ai` may resolve to dist/compat.js
97
+ // and package subpath resolve for `/api/*` can fail. Prefer locating the physical
98
+ // dist file next to the resolved package entry.
99
+ const candidates: string[] = [];
100
+
101
+ try {
102
+ const subpath = import.meta.resolve("@earendil-works/pi-ai/api/openai-codex-responses");
103
+ candidates.push(fileURLToPath(subpath));
104
+ } catch {
105
+ // ignore and try filesystem candidates
106
+ }
107
+
108
+ try {
109
+ const main = fileURLToPath(import.meta.resolve("@earendil-works/pi-ai"));
110
+ const distDir = dirname(main);
111
+ candidates.push(join(distDir, "api/openai-codex-responses.js"));
112
+ candidates.push(join(distDir, "openai-codex-responses.js"));
113
+ } catch {
114
+ // ignore
115
+ }
116
+
117
+ for (const path of candidates) {
118
+ if (path && existsSync(path)) {
119
+ return { path, dir: dirname(path) };
120
+ }
121
+ }
122
+
123
+ throw new Error(`Cannot resolve openai-codex-responses.js (tried: ${candidates.join(", ") || "none"})`);
124
+ }
125
+
126
+ export async function loadCliproxyCodexStreams(providerIds: string[] = ["cliproxyapi"]): Promise<CliproxyCodexStreams> {
127
+ const { path: originalPath, dir: originalDir } = resolveOriginalCodexModulePath();
128
+ const originalSource = readFileSync(originalPath, "utf8");
129
+ const patched = rewriteRelativeImports(patchCodexSource(originalSource, providerIds), originalDir);
130
+
131
+ const hash = createHash("sha1").update(patched).digest("hex").slice(0, 16);
132
+ const cacheDir = join(tmpdir(), "pi-cliproxyapi-provider");
133
+ mkdirSync(cacheDir, { recursive: true });
134
+ const outPath = join(cacheDir, `openai-codex-responses-cpa-${hash}.mjs`);
135
+ if (!existsSync(outPath)) {
136
+ writeFileSync(outPath, patched, "utf8");
137
+ }
138
+
139
+ const mod = (await import(pathToFileURL(outPath).href)) as {
140
+ streamSimple: CliproxyCodexStreamSimple;
141
+ stream: CliproxyCodexStreamSimple;
142
+ };
143
+
144
+ if (typeof mod.streamSimple !== "function" || typeof mod.stream !== "function") {
145
+ throw new Error("patched openai-codex-responses module missing streamSimple/stream exports");
146
+ }
147
+
148
+ return {
149
+ api: CLIPROXYAPI_CODEX_API,
150
+ streamSimple: mod.streamSimple,
151
+ stream: mod.stream,
152
+ };
153
+ }