pi-yandex-bridge 0.2.5 → 0.2.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
@@ -4,13 +4,19 @@ Pi Coding Agent provider bridge for Yandex Cloud AI (YandexGPT).
4
4
 
5
5
  ## Models
6
6
 
7
- | Model | Context | Max output |
8
- | ----------------- | ------- | ---------- |
9
- | YandexGPT Pro 5.1 | 128k | 8k |
10
- | YandexGPT Pro | 128k | 8k |
11
- | YandexGPT Lite | 32k | 4k |
7
+ All models available in your Yandex Cloud folder are fetched dynamically after authentication. Model names are displayed as `name{folder_last5/tag}` — e.g. `yandexgpt-5.1{cffev/l}`.
12
8
 
13
- Unknown models discovered via the API are displayed as `slug {last4ofFolderId}`.
9
+ ## Installation
10
+
11
+ Add to `~/.pi/agent/settings.json`:
12
+
13
+ ```json
14
+ {
15
+ "extensions": ["/path/to/pi-yandex-bridge/dist/index.js"]
16
+ }
17
+ ```
18
+
19
+ Then restart Pi and run `/yalogin`.
14
20
 
15
21
  ## Auth: OAuth (default)
16
22
 
@@ -20,9 +26,9 @@ In the [Yandex Cloud console](https://console.yandex.cloud), select your folder.
20
26
 
21
27
  ### 2. Log in
22
28
 
23
- Run `/yalogin` in Pi. A browser window will open automatically — authorize the app, and the token is captured without any pasting. Pi then prompts for your folder ID.
29
+ Run `/yalogin` in Pi. A browser window opens automatically — authorize the app, and the token is captured without any pasting. Pi then prompts for your folder ID. Available models are fetched immediately after login.
24
30
 
25
- **IAM tokens expire after 12 hours** and are refreshed automatically using the stored OAuth token.
31
+ **IAM tokens expire after 12 hours** and are refreshed automatically using the stored OAuth token. The model list is re-fetched on each refresh.
26
32
 
27
33
  To skip the browser flow, set env vars before starting Pi:
28
34
 
@@ -40,11 +46,4 @@ export YANDEX_API_KEY="your-api-key"
40
46
  export YANDEX_FOLDER_ID="your-folder-id"
41
47
  ```
42
48
 
43
- You can generate an API key in the Yandex Cloud console under **Service accounts → your account → API keys**. The key is shown only once, so copy it immediately.
44
-
45
- Env vars also work for OAuth to skip interactive prompts:
46
-
47
- ```sh
48
- export YANDEX_OAUTH_TOKEN="y0_AgAAAA..."
49
- export YANDEX_FOLDER_ID="b1g..."
50
- ```
49
+ Models are fetched at startup using the API key. You can generate an API key in the [Yandex AI Studio](https://aistudio.yandex.ru) or in the Yandex Cloud console under **Service accounts → your account → API keys**.
package/index.ts CHANGED
@@ -17,6 +17,7 @@ import { readFileSync, writeFileSync } from "fs";
17
17
  import { homedir } from "os";
18
18
  import { join } from "path";
19
19
  import { spawnSync } from "child_process";
20
+ import type { AddressInfo } from "net";
20
21
 
21
22
  import type {
22
23
  ExtensionAPI,
@@ -31,6 +32,7 @@ import type {
31
32
  // ─── constants ────────────────────────────────────────────────────────────────
32
33
 
33
34
  const IAM_TOKEN_URL = "https://iam.api.cloud.yandex.net/iam/v1/tokens";
35
+ const AI_FETCH_URL = "https://llm.api.cloud.yandex.net/v1";
34
36
  const AI_BASE_URL = "https://ai.api.cloud.yandex.net/v1";
35
37
  const AUTH_PATH = join(homedir(), ".pi", "agent", "auth.json");
36
38
 
@@ -42,32 +44,6 @@ const OAUTH_URL =
42
44
  `&client_id=${OAUTH_CLIENT_ID}` +
43
45
  `&redirect_uri=${encodeURIComponent(OAUTH_REDIRECT_URI)}`;
44
46
 
45
- // ─── model catalogue ──────────────────────────────────────────────────────────
46
-
47
- const KNOWN_MODELS = [
48
- {
49
- slug: "yandexgpt-5.1",
50
- name: "YandexGPT Pro 5.1",
51
- contextWindow: 128_000,
52
- maxTokens: 8_192,
53
- cost: { input: 8.8, output: 8.8, cacheRead: 0, cacheWrite: 0 },
54
- },
55
- {
56
- slug: "yandexgpt",
57
- name: "YandexGPT Pro",
58
- contextWindow: 128_000,
59
- maxTokens: 8_192,
60
- cost: { input: 8.8, output: 8.8, cacheRead: 0, cacheWrite: 0 },
61
- },
62
- {
63
- slug: "yandexgpt-lite",
64
- name: "YandexGPT Lite",
65
- contextWindow: 32_000,
66
- maxTokens: 4_096,
67
- cost: { input: 2.2, output: 2.2, cacheRead: 0, cacheWrite: 0 },
68
- },
69
- ] as const;
70
-
71
47
  // ─── helpers ──────────────────────────────────────────────────────────────────
72
48
 
73
49
  interface IamTokenResponse {
@@ -75,15 +51,34 @@ interface IamTokenResponse {
75
51
  expiresAt: string;
76
52
  }
77
53
 
78
- /** Turns `gpt://<folderId>/<slug>/latest` into a readable display name.
79
- * Known slugs get their canonical name; unknown ones get `slug {last4ofFolderId}`. */
54
+ // Only applies to yandex gpt:// URIs leaves all other model IDs untouched.
80
55
  function prettyModelName(id: string): string {
81
- const match = id.match(/^gpt:\/\/([^/]+)\/(.+?)(?:\/latest)?$/);
56
+ const match = id.match(/^gpt:\/\/([^/]+)\/(.+?)(?:(\/latest))?$/);
82
57
  if (!match) return id;
83
- const [, folderId, slug] = match;
84
- const known = KNOWN_MODELS.find((m) => m.slug === slug);
85
- if (known) return known.name;
86
- return `${slug} {${folderId.slice(-4)}}`;
58
+ const [, folderId, slug, hasLatest] = match;
59
+ const tag = hasLatest ? "/l" : "";
60
+ return `${slug}{${folderId.slice(-5)}${tag}}`;
61
+ }
62
+
63
+ function modelEntry(id: string, folderId: string) {
64
+ return {
65
+ id,
66
+ name: prettyModelName(id),
67
+ api: "openai-responses" as const,
68
+ provider: "yandex",
69
+ baseUrl: AI_BASE_URL,
70
+ reasoning: true,
71
+ input: ["text"] as ("text" | "image")[],
72
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
73
+ contextWindow: 128_000,
74
+ maxTokens: 8_192,
75
+ headers: { "OpenAI-Project": folderId },
76
+ compat: {
77
+ supportsDeveloperRole: false,
78
+ supportsReasoningEffort: false,
79
+ maxTokensField: "max_tokens" as const,
80
+ },
81
+ };
87
82
  }
88
83
 
89
84
  function openBrowser(url: string) {
@@ -104,12 +99,10 @@ async function exchangeOAuthForIam(
104
99
  headers: { "Content-Type": "application/json" },
105
100
  body: JSON.stringify({ yandexPassportOauthToken: oauthToken }),
106
101
  });
107
-
108
102
  if (!res.ok) {
109
103
  const text = await res.text().catch(() => res.statusText);
110
104
  throw new Error(`IAM token exchange failed (${res.status}): ${text}`);
111
105
  }
112
-
113
106
  const data = (await res.json()) as IamTokenResponse;
114
107
  return {
115
108
  token: data.iamToken,
@@ -117,25 +110,29 @@ async function exchangeOAuthForIam(
117
110
  };
118
111
  }
119
112
 
120
- function buildModels(folderId: string) {
121
- return KNOWN_MODELS.map((m) => ({
122
- id: `gpt://${folderId}/${m.slug}/latest`,
123
- name: m.name,
124
- api: "openai-responses" as const,
125
- provider: "yandex",
126
- baseUrl: AI_BASE_URL,
127
- reasoning: false,
128
- input: ["text"] as ("text" | "image")[],
129
- cost: m.cost,
130
- contextWindow: m.contextWindow,
131
- maxTokens: m.maxTokens,
132
- headers: { "OpenAI-Project": folderId },
133
- compat: {
134
- supportsDeveloperRole: false,
135
- supportsReasoningEffort: false,
136
- maxTokensField: "max_tokens" as const,
137
- },
138
- }));
113
+ // authHeader: 'Bearer <iam_token>' for OAuth, 'Api-Key <api_key>' for static key
114
+ async function fetchModelIds(
115
+ folderId: string,
116
+ authHeader: string,
117
+ ): Promise<string[]> {
118
+ const ac = new AbortController();
119
+ const timer = setTimeout(() => ac.abort(), 5_000);
120
+ try {
121
+ const res = await fetch(`${AI_FETCH_URL}/models`, {
122
+ headers: {
123
+ Authorization: authHeader,
124
+ "OpenAI-Project": folderId,
125
+ },
126
+ signal: ac.signal,
127
+ });
128
+ clearTimeout(timer);
129
+ if (!res.ok) return [];
130
+ const payload = (await res.json()) as { data: Array<{ id: string }> };
131
+ return payload.data.map((m) => m.id);
132
+ } catch {
133
+ clearTimeout(timer);
134
+ return [];
135
+ }
139
136
  }
140
137
 
141
138
  function readAuthJson(): Record<string, unknown> {
@@ -194,11 +191,7 @@ function captureOAuthToken(): Promise<string> {
194
191
 
195
192
  server.on("error", (err: NodeJS.ErrnoException) => {
196
193
  if (err.code === "EADDRINUSE") {
197
- reject(
198
- new Error(
199
- `Port ${OAUTH_CALLBACK_PORT} is already in use. Stop the process using it and try again.`,
200
- ),
201
- );
194
+ reject(new Error(`Port ${OAUTH_CALLBACK_PORT} is already in use.`));
202
195
  } else {
203
196
  reject(new Error(`Local auth server error: ${err.message}`));
204
197
  }
@@ -213,6 +206,7 @@ function captureOAuthToken(): Promise<string> {
213
206
  );
214
207
 
215
208
  server.listen(OAUTH_CALLBACK_PORT, "127.0.0.1", () => {
209
+ void (server.address() as AddressInfo).port;
216
210
  openBrowser(OAUTH_URL);
217
211
  });
218
212
 
@@ -238,13 +232,22 @@ async function yandexLogin(
238
232
  placeholder: "b1g...",
239
233
  });
240
234
  }
235
+
241
236
  const iam = await exchangeOAuthForIam(oauthToken);
242
237
 
238
+ // Fetch available models while we have fresh credentials.
239
+ const modelIds = await fetchModelIds(
240
+ folderId as string,
241
+ `Bearer ${iam.token}`,
242
+ );
243
+
243
244
  return {
244
245
  refresh: oauthToken,
245
246
  access: iam.token,
246
247
  expires: iam.expiresAt,
247
- folderId,
248
+ folderId: folderId as string,
249
+ // Store fetched model IDs so modifyModels can stay synchronous.
250
+ modelIds: JSON.stringify(modelIds),
248
251
  };
249
252
  }
250
253
 
@@ -252,7 +255,17 @@ async function yandexRefreshToken(
252
255
  credentials: OAuthCredentials,
253
256
  ): Promise<OAuthCredentials> {
254
257
  const iam = await exchangeOAuthForIam(credentials.refresh);
255
- return { ...credentials, access: iam.token, expires: iam.expiresAt };
258
+ // Re-fetch models on token refresh to pick up any new models.
259
+ const modelIds = await fetchModelIds(
260
+ credentials.folderId as string,
261
+ `Bearer ${iam.token}`,
262
+ );
263
+ return {
264
+ ...credentials,
265
+ access: iam.token,
266
+ expires: iam.expiresAt,
267
+ modelIds: JSON.stringify(modelIds),
268
+ };
256
269
  }
257
270
 
258
271
  // ─── /yalogin command ─────────────────────────────────────────────────────────
@@ -260,7 +273,6 @@ async function yandexRefreshToken(
260
273
  async function runYaLogin(ctx: ExtensionCommandContext) {
261
274
  try {
262
275
  ctx.ui.notify("Opening browser for Yandex authorization…", "info");
263
-
264
276
  const oauthToken = await captureOAuthToken();
265
277
 
266
278
  let folderId = process.env.YANDEX_FOLDER_ID ?? "";
@@ -276,6 +288,9 @@ async function runYaLogin(ctx: ExtensionCommandContext) {
276
288
  ctx.ui.notify("Exchanging OAuth token for IAM token…", "info");
277
289
  const iam = await exchangeOAuthForIam(oauthToken);
278
290
 
291
+ ctx.ui.notify("Fetching available models…", "info");
292
+ const modelIds = await fetchModelIds(folderId, `Bearer ${iam.token}`);
293
+
279
294
  const auth = readAuthJson();
280
295
  auth.yandex = {
281
296
  type: "oauth",
@@ -283,11 +298,12 @@ async function runYaLogin(ctx: ExtensionCommandContext) {
283
298
  access: iam.token,
284
299
  expires: iam.expiresAt,
285
300
  folderId,
301
+ modelIds: JSON.stringify(modelIds),
286
302
  };
287
303
  writeAuthJson(auth);
288
304
 
289
305
  ctx.ui.notify(
290
- "✓ Yandex credentials saved. Restart Pi to activate the models.",
306
+ `✓ Yandex credentials saved (${modelIds.length} models). Restart Pi to activate.`,
291
307
  "info",
292
308
  );
293
309
  } catch (err) {
@@ -304,72 +320,32 @@ export default async function (pi: ExtensionAPI) {
304
320
  const apiKey = process.env.YANDEX_API_KEY;
305
321
  const folderId = process.env.YANDEX_FOLDER_ID;
306
322
 
307
- // Static API key path — both env vars must be present.
308
323
  if (apiKey && folderId) {
309
- const modelIds = new Set(
310
- KNOWN_MODELS.map((m) => `gpt://${folderId}/${m.slug}/latest`),
311
- );
312
-
313
- try {
314
- const ac = new AbortController();
315
- const timer = setTimeout(() => ac.abort(), 5_000);
316
- const res = await fetch(`${AI_BASE_URL}/models`, {
317
- headers: {
318
- Authorization: `Bearer ${apiKey}`,
319
- "OpenAI-Project": folderId,
320
- },
321
- signal: ac.signal,
322
- });
323
- clearTimeout(timer);
324
- if (res.ok) {
325
- const payload = (await res.json()) as { data: Array<{ id: string }> };
326
- for (const { id } of payload.data) modelIds.add(id);
327
- }
328
- } catch {
329
- /* static list is enough */
330
- }
331
-
332
- const models = [...modelIds].map((id) => {
333
- const slug = id.replace(/^gpt:\/\/[^/]+\//, "").replace(/\/latest$/, "");
334
- const known = KNOWN_MODELS.find((m) => m.slug === slug);
335
- return {
336
- id,
337
- name: prettyModelName(id),
338
- api: "openai-responses" as const,
339
- provider: "yandex",
340
- baseUrl: AI_BASE_URL,
341
- reasoning: false,
342
- input: ["text"] as ("text" | "image")[],
343
- cost: known?.cost ?? {
344
- input: 0,
345
- output: 0,
346
- cacheRead: 0,
347
- cacheWrite: 0,
348
- },
349
- contextWindow: known?.contextWindow ?? 128_000,
350
- maxTokens: known?.maxTokens ?? 8_192,
351
- headers: { "OpenAI-Project": folderId },
352
- compat: {
353
- supportsDeveloperRole: false,
354
- supportsReasoningEffort: false,
355
- maxTokensField: "max_tokens" as const,
356
- },
357
- };
358
- });
359
-
324
+ // Static API key — fetch models immediately, we have credentials.
325
+ const modelIds = await fetchModelIds(folderId, `Api-Key ${apiKey}`);
360
326
  pi.registerProvider("yandex", {
361
327
  name: "Yandex Cloud",
362
328
  baseUrl: AI_BASE_URL,
363
329
  apiKey,
364
330
  api: "openai-responses",
365
- models,
331
+ models: modelIds.map((id) => modelEntry(id, folderId)),
366
332
  } satisfies ProviderConfig);
367
333
  } else {
368
- // OAuth path — seed models from auth.json if folderId is already stored.
369
- let storedFolderId: string | undefined;
334
+ // OAuth path — seed from auth.json if credentials are already stored.
335
+ let seedModels: ReturnType<typeof modelEntry>[] = [];
370
336
  try {
371
- const auth = readAuthJson() as Record<string, { folderId?: string }>;
372
- storedFolderId = auth.yandex?.folderId;
337
+ const auth = readAuthJson() as Record<
338
+ string,
339
+ {
340
+ folderId?: string;
341
+ modelIds?: string;
342
+ }
343
+ >;
344
+ const stored = auth.yandex;
345
+ if (stored?.folderId && stored?.modelIds) {
346
+ const ids = JSON.parse(stored.modelIds) as string[];
347
+ seedModels = ids.map((id) => modelEntry(id, stored.folderId!));
348
+ }
373
349
  } catch {
374
350
  /* auth.json absent or unreadable */
375
351
  }
@@ -378,14 +354,22 @@ export default async function (pi: ExtensionAPI) {
378
354
  name: "Yandex Cloud",
379
355
  baseUrl: AI_BASE_URL,
380
356
  api: "openai-responses",
381
- models: storedFolderId ? buildModels(storedFolderId) : [],
357
+ models: seedModels,
382
358
  oauth: {
383
359
  name: "Yandex Cloud (OAuth)",
384
360
  login: yandexLogin,
385
361
  refreshToken: yandexRefreshToken,
386
362
  getApiKey: (credentials) => credentials.access,
387
- modifyModels: (_, credentials) =>
388
- buildModels(credentials.folderId as string),
363
+ modifyModels: (models, credentials) => {
364
+ const fId = credentials.folderId as string;
365
+ const ids: string[] = credentials.modelIds
366
+ ? (JSON.parse(credentials.modelIds as string) as string[])
367
+ : [];
368
+ return [
369
+ ...models.filter((m) => m.provider !== "yandex"),
370
+ ...ids.map((id) => modelEntry(id, fId)),
371
+ ];
372
+ },
389
373
  },
390
374
  } satisfies ProviderConfig);
391
375
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-yandex-bridge",
3
- "version": "0.2.5",
3
+ "version": "0.2.9",
4
4
  "description": "Pi Coding Agent provider bridge for Yandex Cloud AI (YandexGPT)",
5
5
  "main": "./dist/index.js",
6
6
  "type": "module",
@@ -1,7 +0,0 @@
1
- {
2
- "success": true,
3
- "clones": [],
4
- "duplicatedLines": 0,
5
- "totalLines": 400,
6
- "percentage": 0
7
- }
@@ -1,4 +0,0 @@
1
- {
2
- "timestamp": "2026-05-09T06:22:47.142Z",
3
- "scanDurationMs": 1316
4
- }
@@ -1,21 +0,0 @@
1
- {
2
- "success": true,
3
- "issues": [
4
- {
5
- "type": "file",
6
- "name": "dist/index.d.ts",
7
- "file": "dist/index.d.ts"
8
- }
9
- ],
10
- "unusedExports": [],
11
- "unusedFiles": [
12
- {
13
- "type": "file",
14
- "name": "dist/index.d.ts",
15
- "file": "dist/index.d.ts"
16
- }
17
- ],
18
- "unusedDeps": [],
19
- "unlistedDeps": [],
20
- "summary": "Found 1 issues"
21
- }
@@ -1,3 +0,0 @@
1
- {
2
- "timestamp": "2026-05-09T06:42:14.808Z"
3
- }
@@ -1 +0,0 @@
1
- null
@@ -1,3 +0,0 @@
1
- {
2
- "timestamp": "2026-05-09T06:23:50.558Z"
3
- }
@@ -1,3 +0,0 @@
1
- {
2
- "items": []
3
- }
@@ -1,3 +0,0 @@
1
- {
2
- "timestamp": "2026-05-09T06:22:45.815Z"
3
- }
@@ -1,4 +0,0 @@
1
- {
2
- "signature": "index.ts::🔴 New unresolved imports/deps in modified code (Knip):\n index.ts:29 — unlisted: @earendil-works/pi-ai\n First location: index.ts\n",
3
- "sessionId": "lens-moxfkr7l-92597cdf"
4
- }
@@ -1,3 +0,0 @@
1
- {
2
- "timestamp": "2026-05-08T21:37:51.694Z"
3
- }
@@ -1 +0,0 @@
1
- null
@@ -1,3 +0,0 @@
1
- {
2
- "timestamp": "2026-05-08T21:37:55.621Z"
3
- }