pi-connect 0.1.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +95 -0
  3. package/index.ts +272 -0
  4. package/package.json +44 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
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,95 @@
1
+ # pi-connect
2
+
3
+ **Unified OAuth & API key login for pi** — OpenCode-inspired UI to connect 15+ providers from one `/connect` command.
4
+
5
+ Paste & save API keys, or login with OAuth, for providers supported by pi like Anthropic, OpenAI, OpenCode, OpenRouter, Gemini, Groq, and more.
6
+
7
+ Official pi providers list:
8
+ - https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/providers.md
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pi install git:github.com/hk-vk/pi-connect
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ### `/connect` — connect any provider
19
+
20
+ **OAuth** (browser login) or **API key** (paste your key) — one unified UI for all providers supported by pi.
21
+
22
+ ```bash
23
+ /connect
24
+ ```
25
+
26
+ Opens a picker like this:
27
+
28
+ ```text
29
+ ╭───────────────────────────────────╮
30
+ │ Connect provider │
31
+ │ │
32
+ │ ○ Anthropic OAuth │
33
+ │ ○ ChatGPT OAuth │
34
+ │ ○ Copilot OAuth │
35
+ │ ○ OpenAI API key │
36
+ │ ○ OpenRouter API key │
37
+ │ ○ OpenCode API key │
38
+ │ ○ Gemini API key │
39
+ │ ○ Groq API key │
40
+ │ │
41
+ │ ● connected ◌ env ○ new │
42
+ ╰───────────────────────────────────╯
43
+ ```
44
+
45
+ Status:
46
+ - `● connected` = saved in `auth.json`
47
+ - `◌ env` = available from environment variable
48
+ - `○ new` = not configured yet
49
+
50
+ ### Direct connect
51
+
52
+ ```bash
53
+ /connect openai
54
+ /connect anthropic
55
+ /connect openrouter
56
+ ```
57
+
58
+ ### `/disconnect` — remove a saved credential
59
+
60
+ ```bash
61
+ /disconnect
62
+ ```
63
+
64
+ ## Supported — 15+ providers
65
+
66
+ **OAuth:**
67
+ - Anthropic (Claude Pro/Max)
68
+ - ChatGPT Plus/Pro (Codex)
69
+ - GitHub Copilot
70
+ - Google Gemini CLI
71
+ - Google Antigravity
72
+
73
+ **API key:**
74
+ - Anthropic
75
+ - OpenAI
76
+ - OpenCode
77
+ - OpenRouter
78
+ - Google Gemini
79
+ - Groq
80
+ - Mistral
81
+ - Cerebras
82
+ - xAI
83
+ - ZAI
84
+ - Azure OpenAI
85
+ - Vercel AI Gateway
86
+ - Hugging Face
87
+ - Kimi
88
+ - MiniMax
89
+
90
+ See the official pi provider documentation for the full list and auth details:
91
+ - https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/providers.md
92
+
93
+ ## License
94
+
95
+ MIT
package/index.ts ADDED
@@ -0,0 +1,272 @@
1
+ import { DynamicBorder, type ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
+ import { getEnvApiKey } from "@mariozechner/pi-ai";
3
+ import { Container, SelectList, Text, type SelectItem } from "@mariozechner/pi-tui";
4
+ import { exec as execCb } from "node:child_process";
5
+
6
+ const API_KEY_PROVIDERS: Record<string, { label: string; env?: string; hint?: string }> = {
7
+ anthropic: { label: "Anthropic", env: "ANTHROPIC_API_KEY" },
8
+ "azure-openai-responses": { label: "Azure OpenAI Responses", env: "AZURE_OPENAI_API_KEY" },
9
+ openai: { label: "OpenAI", env: "OPENAI_API_KEY" },
10
+ google: { label: "Google Gemini", env: "GEMINI_API_KEY" },
11
+ mistral: { label: "Mistral", env: "MISTRAL_API_KEY" },
12
+ groq: { label: "Groq", env: "GROQ_API_KEY" },
13
+ cerebras: { label: "Cerebras", env: "CEREBRAS_API_KEY" },
14
+ xai: { label: "xAI", env: "XAI_API_KEY" },
15
+ openrouter: { label: "OpenRouter", env: "OPENROUTER_API_KEY" },
16
+ "vercel-ai-gateway": { label: "Vercel AI Gateway", env: "AI_GATEWAY_API_KEY" },
17
+ zai: { label: "ZAI", env: "ZAI_API_KEY" },
18
+ opencode: { label: "OpenCode Zen", env: "OPENCODE_API_KEY" },
19
+ "opencode-go": { label: "OpenCode Go", env: "OPENCODE_API_KEY" },
20
+ huggingface: { label: "Hugging Face", env: "HF_TOKEN" },
21
+ "kimi-coding": { label: "Kimi For Coding", env: "KIMI_API_KEY" },
22
+ minimax: { label: "MiniMax", env: "MINIMAX_API_KEY" },
23
+ "minimax-cn": { label: "MiniMax (China)", env: "MINIMAX_CN_API_KEY" },
24
+ };
25
+
26
+ const PRIORITY: Record<string, number> = {
27
+ anthropic: 0,
28
+ openai: 1,
29
+ "openai-codex": 2,
30
+ "github-copilot": 3,
31
+ google: 4,
32
+ "google-gemini-cli": 5,
33
+ openrouter: 6,
34
+ opencode: 7,
35
+ "opencode-go": 8,
36
+ };
37
+
38
+ const LABELS: Record<string, string> = {
39
+ ...Object.fromEntries(Object.entries(API_KEY_PROVIDERS).map(([id, value]) => [id, value.label])),
40
+ anthropic: "Anthropic",
41
+ "openai-codex": "ChatGPT Plus/Pro (Codex)",
42
+ "github-copilot": "GitHub Copilot",
43
+ "google-gemini-cli": "Google Gemini CLI",
44
+ "google-antigravity": "Google Antigravity",
45
+ };
46
+
47
+ function prettyProviderName(providerId: string): string {
48
+ return LABELS[providerId] ?? providerId.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
49
+ }
50
+
51
+ function openUrl(url: string): void {
52
+ const command = process.platform === "darwin"
53
+ ? `open ${JSON.stringify(url)}`
54
+ : process.platform === "win32"
55
+ ? `start "" ${JSON.stringify(url)}`
56
+ : `xdg-open ${JSON.stringify(url)}`;
57
+ execCb(command, () => {});
58
+ }
59
+
60
+ async function pickItem(ctx: any, title: string, subtitle: string | undefined, items: SelectItem[]): Promise<SelectItem | null> {
61
+ return ctx.ui.custom<SelectItem | null>((tui, theme, _kb, done) => {
62
+ const container = new Container();
63
+
64
+ // Top border
65
+ container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
66
+
67
+ // Title (bold)
68
+ container.addChild(new Text(theme.fg("text", theme.bold(title)), 1, 0));
69
+
70
+ // Subtitle if provided (muted, smaller hint)
71
+ if (subtitle) {
72
+ container.addChild(new Text(theme.fg("dim", subtitle), 1, 0));
73
+ }
74
+
75
+ // Spacing before list
76
+ container.addChild(new Text("", 0, 0));
77
+
78
+ // Calculate visible items based on terminal height
79
+ const maxVisible = Math.max(6, Math.min(items.length, Math.floor((tui.terminal.rows - 12) / 2)));
80
+
81
+ const list = new SelectList(items, maxVisible, {
82
+ selectedPrefix: (t) => theme.fg("accent", t),
83
+ selectedText: (t) => theme.fg("accent", theme.bold(t)),
84
+ description: (t) => theme.fg("muted", t),
85
+ scrollInfo: (t) => theme.fg("dim", t),
86
+ noMatch: (t) => theme.fg("warning", t),
87
+ });
88
+ list.onSelect = (item) => done(item);
89
+ list.onCancel = () => done(null);
90
+ container.addChild(list);
91
+
92
+ // Spacing before legend
93
+ container.addChild(new Text("", 0, 0));
94
+
95
+ // Legend for status icons - on ONE clean line
96
+ container.addChild(new Text(
97
+ `${theme.fg("success", "●")} connected ${theme.fg("warning", "◌")} env ${theme.fg("muted", "○")} new`,
98
+ 1, 0
99
+ ));
100
+
101
+ // Keyboard hints
102
+ container.addChild(new Text(theme.fg("dim", "↑↓ navigate • Enter select • Esc cancel"), 1, 0));
103
+
104
+ // Bottom border
105
+ container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
106
+
107
+ return {
108
+ render: (w) => container.render(w),
109
+ invalidate: () => container.invalidate(),
110
+ handleInput: (data) => {
111
+ list.handleInput(data);
112
+ tui.requestRender();
113
+ },
114
+ };
115
+ });
116
+ }
117
+
118
+ export default function piConnectExtension(pi: ExtensionAPI) {
119
+ async function chooseProvider(ctx: any) {
120
+ const authStorage = ctx.modelRegistry.authStorage;
121
+ const oauthProviders = authStorage.getOAuthProviders();
122
+ const modelProviderIds = new Set(ctx.modelRegistry.getAll().map((model) => model.provider));
123
+
124
+ const apiProviders = Object.keys(API_KEY_PROVIDERS)
125
+ .filter((providerId) => modelProviderIds.has(providerId) || authStorage.has(providerId) || !!getEnvApiKey(providerId))
126
+ .sort((a, b) => (PRIORITY[a] ?? 99) - (PRIORITY[b] ?? 99) || prettyProviderName(a).localeCompare(prettyProviderName(b)));
127
+
128
+ const statusIcon = (providerId: string) => {
129
+ if (authStorage.has(providerId)) return ctx.ui.theme.fg("success", "●");
130
+ if (getEnvApiKey(providerId)) return ctx.ui.theme.fg("warning", "◌");
131
+ return ctx.ui.theme.fg("muted", "○");
132
+ };
133
+
134
+ const items: SelectItem[] = [];
135
+
136
+ // OAuth section
137
+ if (oauthProviders.length > 0) {
138
+ items.push({
139
+ value: "__section_oauth",
140
+ label: ctx.ui.theme.bold("OAuth providers"),
141
+ description: "login via browser subscription",
142
+ });
143
+ for (const provider of oauthProviders) {
144
+ items.push({
145
+ value: `oauth:${provider.id}`,
146
+ label: `${statusIcon(provider.id)} ${provider.name}`,
147
+ description: "subscription",
148
+ });
149
+ }
150
+ }
151
+
152
+ // API key section
153
+ if (apiProviders.length > 0) {
154
+ items.push({
155
+ value: "__section_api",
156
+ label: ctx.ui.theme.bold("API key providers"),
157
+ description: "paste your key directly",
158
+ });
159
+ for (const providerId of apiProviders) {
160
+ const envName = API_KEY_PROVIDERS[providerId]?.env;
161
+ items.push({
162
+ value: `api:${providerId}`,
163
+ label: `${statusIcon(providerId)} ${prettyProviderName(providerId)}`,
164
+ description: envName || "key",
165
+ });
166
+ }
167
+ }
168
+
169
+ const selected = await pickItem(ctx, "Connect provider", "OAuth first, API key providers below", items);
170
+ if (!selected || selected.value.startsWith("__section_")) return;
171
+
172
+ const [kind, providerId] = selected.value.split(":", 2);
173
+ if (!providerId) return;
174
+
175
+ if (kind === "oauth") {
176
+ await loginWithOAuth(providerId, ctx);
177
+ return;
178
+ }
179
+
180
+ await promptApiKey(providerId, ctx);
181
+ }
182
+
183
+ async function promptApiKey(providerId: string, ctx: any) {
184
+ const authStorage = ctx.modelRegistry.authStorage;
185
+ const provider = API_KEY_PROVIDERS[providerId];
186
+ const label = prettyProviderName(providerId);
187
+ const prompt = provider?.env
188
+ ? `${label} API key (${provider.env})`
189
+ : `${label} API key`;
190
+ const value = await ctx.ui.input(prompt, "Paste API key");
191
+ if (!value) {
192
+ ctx.ui.notify("Cancelled", "info");
193
+ return;
194
+ }
195
+ authStorage.set(providerId, { type: "api_key", key: value.trim() });
196
+ ctx.ui.notify(`Saved ${prettyProviderName(providerId)}`, "info");
197
+ }
198
+
199
+ async function loginWithOAuth(providerId: string, ctx: any) {
200
+ const authStorage = ctx.modelRegistry.authStorage;
201
+ await authStorage.login(providerId, {
202
+ onAuth: ({ url, instructions }) => {
203
+ openUrl(url);
204
+ ctx.ui.notify(instructions ? `${instructions}\n${url}` : url, "info");
205
+ },
206
+ onPrompt: async ({ message, placeholder }) => {
207
+ return (await ctx.ui.input(message, placeholder)) ?? "";
208
+ },
209
+ onManualCodeInput: async () => {
210
+ return (await ctx.ui.input("Paste the callback URL or code", "code or redirect URL")) ?? "";
211
+ },
212
+ onProgress: (message) => {
213
+ ctx.ui.notify(message, "info");
214
+ },
215
+ });
216
+ ctx.ui.notify(`Connected ${prettyProviderName(providerId)}`, "info");
217
+ }
218
+
219
+ pi.registerCommand("connect", {
220
+ description: "Connect a provider with OAuth or an API key",
221
+ handler: async (args, ctx) => {
222
+ const providerId = args.trim();
223
+ if (!providerId) {
224
+ await chooseProvider(ctx);
225
+ return;
226
+ }
227
+
228
+ const normalized = providerId.toLowerCase();
229
+ const oauthIds = new Set(ctx.modelRegistry.authStorage.getOAuthProviders().map((provider) => provider.id));
230
+ if (oauthIds.has(normalized)) {
231
+ if (API_KEY_PROVIDERS[normalized]) {
232
+ const method = await pickItem(ctx, prettyProviderName(normalized), "Choose how to connect", [
233
+ { value: "oauth", label: `${ctx.ui.theme.bold("OAuth")}`, description: "Subscription login" },
234
+ { value: "api", label: `${ctx.ui.theme.bold("API key")}`, description: "Paste a provider key" },
235
+ ]);
236
+ if (!method) return;
237
+ if (method.value === "oauth") {
238
+ await loginWithOAuth(normalized, ctx);
239
+ return;
240
+ }
241
+ } else {
242
+ await loginWithOAuth(normalized, ctx);
243
+ return;
244
+ }
245
+ }
246
+
247
+ await promptApiKey(normalized, ctx);
248
+ },
249
+ });
250
+
251
+ pi.registerCommand("disconnect", {
252
+ description: "Remove saved provider credentials",
253
+ handler: async (_args, ctx) => {
254
+ const authStorage = ctx.modelRegistry.authStorage;
255
+ const providers = authStorage.list().sort((a, b) => prettyProviderName(a).localeCompare(prettyProviderName(b)));
256
+ if (providers.length === 0) {
257
+ ctx.ui.notify("No saved credentials", "info");
258
+ return;
259
+ }
260
+ const items: SelectItem[] = providers.map((providerId) => ({
261
+ value: providerId,
262
+ label: `${ctx.ui.theme.fg("success", "●")} ${ctx.ui.theme.bold(prettyProviderName(providerId))}`,
263
+ description: "Connected",
264
+ }));
265
+ const selected = await pickItem(ctx, "Disconnect provider", "Remove a saved credential", items);
266
+ const providerId = selected?.value;
267
+ if (!providerId) return;
268
+ authStorage.remove(providerId);
269
+ ctx.ui.notify(`Removed ${prettyProviderName(providerId)}`, "info");
270
+ },
271
+ });
272
+ }
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "pi-connect",
3
+ "version": "0.1.0",
4
+ "description": "Unified OAuth & API key login for pi — OpenCode-inspired UI to connect 15+ providers from one /connect command.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "pi-package",
9
+ "pi-extension",
10
+ "oauth",
11
+ "api-key",
12
+ "provider-login",
13
+ "auth"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/hk-vk/pi-connect.git"
18
+ },
19
+ "homepage": "https://github.com/hk-vk/pi-connect#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/hk-vk/pi-connect/issues"
22
+ },
23
+ "engines": {
24
+ "node": ">=18.0.0"
25
+ },
26
+ "files": [
27
+ "index.ts",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "pi": {
35
+ "extensions": [
36
+ "./index.ts"
37
+ ]
38
+ },
39
+ "peerDependencies": {
40
+ "@mariozechner/pi-coding-agent": "*",
41
+ "@mariozechner/pi-ai": "*",
42
+ "@mariozechner/pi-tui": "*"
43
+ }
44
+ }