@lks347/dsh-oauth 1.0.1 → 1.0.2

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/src/grants.js CHANGED
@@ -79,7 +79,7 @@ export function createGrantResolver(credentials, modelsFactory = builtinModels)
79
79
  if (!payload) throw new Error("OAuth 登录已断开,请重新登录");
80
80
  }
81
81
  const resolved = await models.getAuth(id, { signal: AbortSignal.timeout(20000) });
82
- if (typeof resolved?.auth?.apiKey !== "string" || resolved.auth.apiKey.length === 0) {
82
+ if (!resolved?.auth) {
83
83
  throw new Error(`${id} 的 OAuth 请求凭据不可用,请重新登录`);
84
84
  }
85
85
  payload = await store.read(id);
@@ -88,12 +88,13 @@ export function createGrantResolver(credentials, modelsFactory = builtinModels)
88
88
  // Derive request auth from the same payload we remember for recovery.
89
89
  const oauth = models.getProvider?.(id)?.auth?.oauth;
90
90
  const auth = typeof oauth?.toAuth === "function" ? await oauth.toAuth(payload) : resolved.auth;
91
- if (typeof auth?.apiKey !== "string" || !auth.apiKey) {
91
+ const access = auth?.apiKey ?? (id === "kimi-coding" && auth?.headers ? payload.access : undefined);
92
+ if (typeof access !== "string" || !access) {
92
93
  throw new Error(`${id} 的 OAuth 请求凭据不可用,请重新登录`);
93
94
  }
94
95
  return remember(id, {
95
96
  ...payload,
96
- access: auth.apiKey,
97
+ access,
97
98
  ...(auth.headers ? { requestHeaders: auth.headers } : {}),
98
99
  ...(auth.baseUrl ? { apiBase: auth.baseUrl } : {}),
99
100
  }, payload);
@@ -325,3 +325,16 @@ test("a disconnect while waiting for the forced-refresh lock never restores an o
325
325
  assert.equal(exchanges, 0);
326
326
  assert.equal(credentials.records.has(key), false);
327
327
  });
328
+
329
+ test("Kimi accepts the installed OAuth adapter's header-based authorization", async () => {
330
+ const key = "llm-pi-ai/kimi-coding";
331
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: { type: "oauth", access: "fixture-kimi" } } });
332
+ const auth = { headers: { Authorization: "Bearer fixture-kimi" } };
333
+ const resolveGrant = createGrantResolver(credentials, () => ({
334
+ getAuth: async () => ({ auth }),
335
+ getProvider: () => ({ auth: { oauth: { toAuth: async () => auth } } }),
336
+ }));
337
+ const result = await resolveGrant("kimi-coding");
338
+ assert.equal(result.access, "fixture-kimi");
339
+ assert.deepEqual(result.requestHeaders, auth.headers);
340
+ });
package/src/index.js CHANGED
@@ -13,7 +13,7 @@ import { accountClientFrom, loginCallbackOrigin, loginSource, signInFailed } fro
13
13
  import { registerMediaTools } from "./media.js";
14
14
  import { fetchAccountModels } from "./models.js";
15
15
  import { createPullStore } from "./pulls.js";
16
- import { loginQwen, qwenEndpoint } from "./qwen.js";
16
+ import { qwenEndpoint } from "./qwen.js";
17
17
  import { createAuthorizationSessions } from "./authorization.js";
18
18
  import { createGrantResolver, QWEN_KEY_NAME } from "./grants.js";
19
19
  import { restoreRoute, writeRoute } from "./routes.js";
@@ -24,7 +24,7 @@ import { createConnectionRuntime } from "./connection-runtime.js";
24
24
  import { connectionRef, connectionMetadata, validSecret } from "./connections.js";
25
25
  import { createUsageService, usageIds } from "./usage/index.js";
26
26
  import { providerDefinitions, getProviderDefinition } from "./catalog.js";
27
- import { discoverLocalSources, readLocalSource } from "./local-imports.js";
27
+ import { discoverLocalSources, fetchAntigravityCliModels, readLocalSource } from "./local-imports.js";
28
28
 
29
29
  const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
30
30
  const VERSION = JSON.parse(await readFile(join(ROOT, "package.json"), "utf8")).version;
@@ -69,6 +69,9 @@ export async function apply(ctx) {
69
69
  await mutateProvider(ctx, options.provider, async () => {
70
70
  const connection = await connectionRuntime.connections.read(options.provider);
71
71
  const pull = await currentPull(ctx, options.provider);
72
+ if (options.provider === 'anthropic' && pull && (!connection || connection.mode === 'oauth')) {
73
+ throw new Error('Connect a Claude Console API key and refresh this plugin’s Claude model configuration.');
74
+ }
72
75
  if (connection?.mode === 'local' || connection?.mode === 'key') {
73
76
  if (!pull) throw new Error('Import the selected connection’s models before using this provider.');
74
77
  await resolveGrant(options.provider);
@@ -96,9 +99,6 @@ export async function apply(ctx) {
96
99
  });
97
100
  else res.end();
98
101
  });
99
- ctx.inject(["authorization"], (scoped) => {
100
- scoped.effect(() => registerCodingPlanFlows(ctx, scoped.authorization ?? scoped.get?.("authorization")));
101
- });
102
102
  ctx.inject(["tools", "systemPrompt"], (scoped) => {
103
103
  registerMediaTools(scoped, resolveGrant, pulls);
104
104
  });
@@ -174,7 +174,7 @@ async function handle(ctx, req, res) {
174
174
  for (const source of sources) {
175
175
  source.providers = source.providers.map(row => {
176
176
  const definition = getProviderDefinition(row.provider);
177
- const supported = !!definition && (row.authType === 'oauth' || definition.keyConnect);
177
+ const supported = !!definition && (row.authType === 'oauth' ? definition.oauthConnect !== false : definition.keyConnect);
178
178
  return supported ? row : { ...row, available: false, reasonCode: 'unsupported-provider' };
179
179
  });
180
180
  source.available = source.providers.some(row => row.available);
@@ -187,6 +187,7 @@ async function handle(ctx, req, res) {
187
187
  if (!id) return json(res, 400, { error: '需要 provider id' });
188
188
  const runtime = runtimes.get(ctx);
189
189
  try {
190
+ if (url.pathname.endsWith('/usage') && id === 'anthropic') return json(res, 200, { status: 'unsupported' });
190
191
  if (url.pathname.endsWith('/usage')) return json(res, 200, await runtime.usage.get(id, { force: body.force === true }));
191
192
  await mutateProvider(ctx, id, async () => {
192
193
  if (runtime.sessions.get(id)?.status === 'pending') throw new Error('Cancel the pending login before replacing this connection.');
@@ -200,7 +201,7 @@ async function handle(ctx, req, res) {
200
201
  await runtime.connectionRuntime.connections.connect(id, body);
201
202
  } else if (url.pathname.endsWith('/import')) {
202
203
  const imported = await readLocalSource(body.source, id);
203
- if (!definition || imported.grant.type === 'api_key' && !definition.keyConnect) throw new Error('This local credential has no supported model route.');
204
+ if (!definition || (imported.grant.type === 'api_key' ? !definition.keyConnect : definition.oauthConnect === false)) throw new Error('This local credential has no supported model route.');
204
205
  await dropRoute(ctx, id);
205
206
  await runtime.connectionRuntime.connections.saveLocal(id, body.source, imported.label);
206
207
  await runtime.resolveGrant(id);
@@ -236,6 +237,7 @@ async function handle(ctx, req, res) {
236
237
  const id = providerId(body.provider);
237
238
  if (id === undefined) return json(res, 400, { error: "需要 provider id" });
238
239
  try {
240
+ if (id === 'google-antigravity' && body.source === 'agy') return json(res, 200, { models: await fetchAntigravityCliModels() });
239
241
  const models = await accountModels(ctx, id);
240
242
  return json(res, 200, { models });
241
243
  } catch (error) {
@@ -275,8 +277,7 @@ async function handle(ctx, req, res) {
275
277
  if (id === QWEN_ID && typeof ctx.credentials.unset === "function") await ctx.credentials.unset(QWEN_KEY_NAME);
276
278
  await dropRoute(ctx, id);
277
279
  };
278
- if (id === QWEN_ID) await mutateQwenLogin(ctx, disconnect);
279
- else await mutateProvider(ctx, id, disconnect);
280
+ await mutateProvider(ctx, id, disconnect);
280
281
  }
281
282
  return json(res, 200, { ok: true });
282
283
  }
@@ -348,11 +349,24 @@ async function listProviders(ctx) {
348
349
  const pull = await currentPull(ctx, row.id);
349
350
  const native = row.flow !== 'key';
350
351
  row.keyConnect = definition?.keyConnect === true || row.id === 'new-api' || row.id === 'aliyun-token-plan';
351
- row.authMethods = [...(native ? ['oauth'] : []), ...(row.keyConnect ? ['key'] : []), ...(definition ? ['local'] : [])];
352
- row.usageSupported = usageIds.has(row.id);
353
- row.credentialConfigured = !!connection?.access || row.loggedIn || connection?.mode === 'local';
352
+ const oauth = native && definition?.oauthConnect !== false && row.id !== QWEN_ID;
353
+ row.authMethods = [...(oauth ? ['oauth'] : []), ...(row.keyConnect ? ['key'] : []), ...(definition && row.id !== QWEN_ID ? ['local'] : [])];
354
+ row.usageSupported = usageIds.has(row.id) && row.id !== 'anthropic';
355
+ row.credentialConfigured = !!connection?.access || row.loggedIn && definition?.oauthConnect !== false || connection?.mode === 'local';
354
356
  row.billingCredentialConfigured = !!connection?.billingAccess;
355
357
  row.loggedIn = row.credentialConfigured;
358
+ if (connection?.mode === 'local') {
359
+ try {
360
+ const { grant } = await readLocalSource(connection.localSource, row.id);
361
+ if (grant.type === 'oauth' && definition?.oauthConnect === false) row.sourceStatus = 'unsupported-provider';
362
+ } catch (error) { row.sourceStatus = error.code ?? 'source-unavailable'; }
363
+ if (row.sourceStatus) row.loggedIn = false;
364
+ }
365
+ if (row.id === 'anthropic') {
366
+ row.name = definition.name;
367
+ row.cli = '';
368
+ }
369
+ if (definition?.docs) row.docs = definition.docs;
356
370
  row.connection = connection?.metadata ?? {};
357
371
  row.sourceLabel = connection?.mode === 'key' ? 'API Key' : connection?.mode === 'local' ? `${connection.sourceLabel} · external-managed` : row.sourceLabel;
358
372
  row.pullable = row.pullable || !!definition?.modelsURL || !!definition?.catalogProvider;
@@ -361,6 +375,7 @@ async function listProviders(ctx) {
361
375
  row.pullPermanent = !!pull && pull.expiresAt === null;
362
376
  row.modelSource = definition?.modelSource;
363
377
  row.supportReason = definition?.reason;
378
+ if (row.id === 'google-antigravity') row.cliCatalog = true;
364
379
  delete row.tokenPreview;
365
380
  }
366
381
  return rows;
@@ -373,50 +388,6 @@ function mutateProvider(ctx, id, operation) {
373
388
  return next;
374
389
  }
375
390
 
376
- function registerCodingPlanFlows(ctx, authorization) {
377
- if (authorization === undefined || typeof authorization.registerFlow !== "function") return;
378
- const key = credentialKey(OAUTH_SCOPE, QWEN_ID);
379
- try {
380
- return authorization.registerFlow({
381
- key,
382
- label: "通义千问",
383
- methods: [{ id: "oauth", label: "浏览器登录" }],
384
- async run(session) {
385
- const grant = await loginQwen(session);
386
- await mutateQwenLogin(ctx, async () => {
387
- session.signal.throwIfAborted();
388
- await ctx.credentials.modifyRecord(key, async () => {
389
- // A cancellation can win while this write waits for the record lock.
390
- session.signal.throwIfAborted();
391
- return {
392
- kind: "grant",
393
- payload: {
394
- access: grant.access,
395
- ...(grant.refresh === undefined ? {} : { refresh: grant.refresh }),
396
- expires: grant.expires,
397
- resourceUrl: grant.resourceUrl,
398
- },
399
- };
400
- });
401
- session.signal.throwIfAborted();
402
- if (typeof ctx.credentials.set === "function") await ctx.credentials.set(QWEN_KEY_NAME, grant.access);
403
- });
404
- },
405
- });
406
- } catch (error) {
407
- const message = error instanceof Error ? error.message : String(error);
408
- if (!message.includes("already registered")) throw error;
409
- }
410
- }
411
-
412
- /** Let an explicit disconnect clear both writes after any in-flight Qwen login commit. */
413
- function mutateQwenLogin(ctx, mutate) {
414
- const runtime = runtimes.get(ctx);
415
- const next = (runtime.qwenLoginWrite ?? Promise.resolve()).then(mutate);
416
- runtime.qwenLoginWrite = next.catch(() => {});
417
- return next;
418
- }
419
-
420
391
  async function qwenRow(ctx) {
421
392
  const { sessions } = runtimes.get(ctx);
422
393
  const key = credentialKey(OAUTH_SCOPE, QWEN_ID);
@@ -506,6 +477,8 @@ function deepseekAccount(ctx) {
506
477
  }
507
478
 
508
479
  async function startLogin(ctx, id, req, method) {
480
+ if (id === QWEN_ID) throw new Error("旧版通义千问 OAuth 已停止接受新连接,请使用阿里云 Token Plan 密钥。");
481
+ if (getProviderDefinition(id)?.oauthConnect === false) throw new Error("请使用 Claude Console API Key 连接。Claude 订阅登录由 Claude Code 管理。");
509
482
  const runtime = runtimes.get(ctx);
510
483
  if (runtime.sessions.get(id)?.status !== 'pending' && id !== DEEPSEEK_ACCOUNT) {
511
484
  await mutateProvider(ctx, id, async () => {
@@ -539,7 +512,6 @@ async function startLogin(ctx, id, req, method) {
539
512
  return runtime.authorizationSessions.begin(runtime.xaiBrowser, id, credentialKey(PI_AI, "xai"));
540
513
  }
541
514
  if (id === DEEPSEEK_ACCOUNT) return startDeepSeekLogin(ctx, req);
542
- if (id === QWEN_ID) return startScopedLogin(ctx, id, OAUTH_SCOPE);
543
515
  return startScopedLogin(ctx, id, PI_AI);
544
516
  }
545
517
 
@@ -1,19 +1,29 @@
1
1
  import { constants } from 'node:fs';
2
+ import { execFile } from 'node:child_process';
2
3
  import { open } from 'node:fs/promises';
3
- import { homedir } from 'node:os';
4
+ import { homedir, tmpdir } from 'node:os';
4
5
  import { isAbsolute, join } from 'node:path';
6
+ import { promisify } from 'node:util';
5
7
 
6
8
  const MAX_BYTES = 1024 * 1024;
7
9
  const NEAR_EXPIRY_MS = 60_000;
8
10
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
9
11
  const providerID = value => typeof value === 'string' && /^[a-z0-9][a-z0-9._-]{0,99}$/.test(value);
10
12
  const secret = value => typeof value === 'string' && value.length > 0 && value.length <= 262144 && !/[\x00-\x20\x7f]/.test(value) ? value : undefined;
11
- const labels = Object.freeze({ codex: 'Codex CLI', opencode: 'OpenCode CLI (auth.json)' });
13
+ const labels = Object.freeze({ codex: 'Codex CLI', opencode: 'OpenCode CLI' });
14
+ const exec = promisify(execFile);
12
15
 
13
16
  export class LocalSourceError extends Error {
14
17
  constructor(code, message) { super(message); this.name = 'LocalSourceError'; this.code = code; }
15
18
  }
16
19
  const error = (code, message) => new LocalSourceError(code, message);
20
+ const AGY_PROVIDER = 'google-antigravity';
21
+ const AGY_REASON = 'source-does-not-export-credentials';
22
+
23
+ function defaultCodexHome(home = homedir()) {
24
+ const codexHome = process.env.CODEX_HOME;
25
+ return codexHome && isAbsolute(codexHome) ? codexHome : join(home, '.codex');
26
+ }
17
27
 
18
28
  function expiryFromJWT(value) {
19
29
  const parts = value.split('.');
@@ -73,20 +83,81 @@ function openCodeEntries(data, now) {
73
83
  return entries;
74
84
  }
75
85
 
76
- async function readKnownJSON(path) {
86
+ function openCodeProvider(id, type) {
87
+ return id === 'openai' && type === 'oauth' ? 'openai-codex' : id;
88
+ }
89
+
90
+ async function openCodeCommand(args) {
91
+ const configured = process.env.DSH_OAUTH_OPENCODE_BIN;
92
+ const options = { cwd: homedir(), timeout: 8000, maxBuffer: MAX_BYTES, windowsHide: true,
93
+ env: { ...process.env, OPENCODE_DISABLE_EXTERNAL_PLUGINS: 'true' } };
94
+ if (configured && isAbsolute(configured)) return (await exec(configured, args, options)).stdout;
95
+ try { return (await exec('opencode', args, options)).stdout; }
96
+ catch (cause) {
97
+ if (cause.code !== 'ENOENT' || process.platform !== 'darwin') throw cause;
98
+ const prefix = process.arch === 'arm64' ? '/opt/homebrew' : '/usr/local';
99
+ return (await exec(join(prefix, 'bin', 'opencode'), args, options)).stdout;
100
+ }
101
+ }
102
+
103
+ async function openCodeV2(run) {
104
+ if (!run) return false;
105
+ try { return /^(?:opencode\s+)?(?:[2-9]|\d{2,})\.\d+\.\d+(?:[-+][\w.+-]+)?$/i.test((await run(['--version'])).trim()); }
106
+ catch { return false; }
107
+ }
108
+
109
+ async function openCodeJson(run, args) {
110
+ try {
111
+ const rows = JSON.parse(await run(args));
112
+ if (!Array.isArray(rows)) throw new Error('Unexpected result');
113
+ return rows;
114
+ } catch { throw error('source-unavailable', 'The OpenCode v2 CLI did not return usable authorization data.'); }
115
+ }
116
+
117
+ async function listOpenCodeV2(run) {
118
+ const rows = await openCodeJson(run, ['auth', 'list', '--format', 'json']);
119
+ const choices = new Map();
120
+ for (const row of rows) {
121
+ if (!providerID(row?.id) || !Array.isArray(row.connections)) continue;
122
+ const supported = row.connections.filter(item => item?.type === 'credential' && ['key', 'oauth'].includes(item.method));
123
+ for (const item of supported) {
124
+ const provider = openCodeProvider(row.id, item.method);
125
+ const reasonCode = item.status?.status === 'needs_auth' ? 'source-reauth-required' : undefined;
126
+ const previous = choices.get(provider);
127
+ choices.set(provider, { provider, authType: item.method === 'oauth' ? 'oauth' : 'api-key',
128
+ available: !previous && !reasonCode, ...(previous ? { reasonCode: 'ambiguous-source' } : reasonCode ? { reasonCode } : {}) });
129
+ }
130
+ }
131
+ return [...choices.values()];
132
+ }
133
+
134
+ async function readOpenCodeV2(run, provider, now) {
135
+ const id = provider === 'openai-codex' ? 'openai' : provider;
136
+ const rows = await openCodeJson(run, ['auth', 'export', id]);
137
+ const matches = rows.filter(row => row?.integrationID === id && object(row.value) &&
138
+ ['oauth', 'key'].includes(row.value.type) && openCodeProvider(id, row.value.type) === provider);
139
+ const active = matches.filter(row => row.active === true);
140
+ const selected = active.length ? active : matches;
141
+ if (!selected.length) throw error('source-unavailable', 'OpenCode v2 has no supported stored credential for this provider.');
142
+ if (selected.length !== 1) throw error('ambiguous-source', 'OpenCode v2 returned several accounts without an unambiguous active credential.');
143
+ const value = selected[0].value;
144
+ return value.type === 'key' ? apiKey(value.key) : oauth(value.access, value.expires, value.metadata?.accountId ?? value.metadata?.account_id, now);
145
+ }
146
+
147
+ async function readKnownJSON(path, maxBytes = MAX_BYTES) {
77
148
  let handle;
78
149
  try {
79
- handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
150
+ handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
80
151
  const stat = await handle.stat();
81
- if (!stat.isFile() || stat.size > MAX_BYTES) throw error('invalid-source', 'The CLI authorization source is not a bounded regular JSON file.');
82
- const buffer = Buffer.alloc(MAX_BYTES + 1);
152
+ if (!stat.isFile() || stat.size > maxBytes) throw error('invalid-source', 'The CLI authorization source is not a bounded regular JSON file.');
153
+ const buffer = Buffer.alloc(Math.min(stat.size + 1, maxBytes + 1));
83
154
  let total = 0;
84
155
  while (total < buffer.length) {
85
156
  const { bytesRead } = await handle.read(buffer, total, buffer.length - total, total);
86
157
  if (!bytesRead) break;
87
158
  total += bytesRead;
88
159
  }
89
- if (total > MAX_BYTES) throw error('invalid-source', 'The CLI authorization source exceeds the size limit.');
160
+ if (total > stat.size) throw error('invalid-source', 'The CLI authorization source changed while being read.');
90
161
  try { return JSON.parse(buffer.subarray(0, total).toString('utf8')); }
91
162
  catch { throw error('invalid-source', 'The CLI authorization source is not valid JSON.'); }
92
163
  } catch (cause) {
@@ -96,8 +167,42 @@ async function readKnownJSON(path) {
96
167
  } finally { await handle?.close().catch(() => {}); }
97
168
  }
98
169
 
170
+ /** Read only version metadata from the cache. Its catalog can belong to a different account. */
171
+ export async function readCodexCatalogClientVersion() {
172
+ try {
173
+ const cache = await readKnownJSON(join(defaultCodexHome(), 'models_cache.json'), 4 * MAX_BYTES);
174
+ return cache?.client_version;
175
+ } catch {
176
+ return undefined;
177
+ }
178
+ }
179
+
180
+ /** Ask the official CLI for its account catalog, without exporting its keyring credentials. */
181
+ export async function fetchAntigravityCliModels() {
182
+ const binary = join(homedir(), '.local', 'bin', process.platform === 'win32' ? 'agy.exe' : 'agy');
183
+ const options = { cwd: tmpdir(), timeout: 15000, maxBuffer: MAX_BYTES, windowsHide: true,
184
+ env: { ...process.env, AGY_CLI_DISABLE_AUTO_UPDATE: 'true' } };
185
+ try {
186
+ let result;
187
+ try { result = await exec(binary, ['models'], options); }
188
+ catch (cause) {
189
+ if (cause.code !== 'ENOENT') throw cause;
190
+ result = await exec('agy', ['models'], options);
191
+ }
192
+ const models = new Map();
193
+ for (const line of result.stdout.split(/\r?\n/)) {
194
+ const [id, name] = line.split('\t');
195
+ if (providerID(id) && name?.trim()) models.set(id, { id, name: name.trim().slice(0, 160), role: 'chat' });
196
+ }
197
+ if (models.size) return [...models.values()];
198
+ } catch {
199
+ // Child errors may include CLI logs or login links and must stay local.
200
+ }
201
+ throw error('source-unavailable', '无法从 AGY 读取模型目录。请确认宿主可运行 agy models,并在 AGY 中完成登录。');
202
+ }
203
+
99
204
  /** Roots are trusted server configuration only. HTTP bodies must never reach this factory. */
100
- export function createLocalSources({ home = homedir(), codexHome, openCodeDataHome, now = () => Date.now() } = {}) {
205
+ export function createLocalSources({ home = homedir(), codexHome, openCodeDataHome, runOpenCode, now = () => Date.now() } = {}) {
101
206
  if (!isAbsolute(home) || codexHome !== undefined && !isAbsolute(codexHome) || openCodeDataHome !== undefined && !isAbsolute(openCodeDataHome)) throw error('invalid-configuration', 'CLI source roots must be absolute server-configured directories.');
102
207
  const sources = {
103
208
  codex: { path: join(codexHome ?? join(home, '.codex'), 'auth.json'), parse: codexEntries },
@@ -109,8 +214,12 @@ export function createLocalSources({ home = homedir(), codexHome, openCodeDataHo
109
214
  return spec.parse(await readKnownJSON(spec.path), now());
110
215
  }
111
216
  async function discoverLocalSources() {
112
- return Promise.all(Object.keys(sources).map(async id => {
217
+ const fileSources = await Promise.all(Object.keys(sources).map(async id => {
113
218
  try {
219
+ if (id === 'opencode' && await openCodeV2(runOpenCode)) {
220
+ const providers = await listOpenCodeV2(runOpenCode);
221
+ return { id, label: labels[id], available: providers.some(item => item.available), providers };
222
+ }
114
223
  const list = await entries(id);
115
224
  const counts = new Map();
116
225
  for (const item of list) counts.set(item.provider, (counts.get(item.provider) ?? 0) + 1);
@@ -125,9 +234,17 @@ export function createLocalSources({ home = homedir(), codexHome, openCodeDataHo
125
234
  return { id, label: labels[id], available: false, reasonCode: cause instanceof LocalSourceError ? cause.code : 'invalid-source', providers: [] };
126
235
  }
127
236
  }));
237
+ return [...fileSources, { id: 'agy', label: 'Antigravity CLI (agy)', available: false, reasonCode: AGY_REASON,
238
+ providers: [{ provider: AGY_PROVIDER, authType: 'oauth', available: false, reasonCode: AGY_REASON }] }];
128
239
  }
129
240
  async function readLocalSource(source, provider) {
130
241
  if (!providerID(provider)) throw error('unsupported-provider', 'The selected source provider is not supported.');
242
+ if (source === 'agy' && provider === AGY_PROVIDER) {
243
+ throw error(AGY_REASON, 'Antigravity CLI manages its login in the system keyring and does not export reusable credentials. Use /usage in agy to view subscription quota.');
244
+ }
245
+ if (source === 'opencode' && await openCodeV2(runOpenCode)) {
246
+ return { provider, grant: await readOpenCodeV2(runOpenCode, provider, now()), owner: 'external-managed', source: { id: source, provider }, label: labels[source] };
247
+ }
131
248
  // Reread the same fixed source on every use: no cached token or refresh chain survives source logout.
132
249
  const matches = (await entries(source)).filter(item => item.provider === provider);
133
250
  if (!matches.length) throw error('source-unavailable', 'The selected provider is no longer present in the source CLI.');
@@ -138,8 +255,9 @@ export function createLocalSources({ home = homedir(), codexHome, openCodeDataHo
138
255
  }
139
256
 
140
257
  const defaults = createLocalSources({
141
- codexHome: process.env.CODEX_HOME && isAbsolute(process.env.CODEX_HOME) ? process.env.CODEX_HOME : undefined,
258
+ codexHome: defaultCodexHome(),
142
259
  openCodeDataHome: process.env.XDG_DATA_HOME && isAbsolute(process.env.XDG_DATA_HOME) ? process.env.XDG_DATA_HOME : undefined,
260
+ runOpenCode: openCodeCommand,
143
261
  });
144
262
  export const discoverLocalSources = () => defaults.discoverLocalSources();
145
263
  export const readLocalSource = (source, provider) => defaults.readLocalSource(source, provider);
@@ -17,11 +17,23 @@ async function fixture(t) {
17
17
 
18
18
  test('empty isolated roots discover known sources without leaking host paths', async t => {
19
19
  const f = await fixture(t), sources = await f.discoverLocalSources();
20
- assert.deepEqual(sources.map(x => x.id), ['codex', 'opencode']);
21
- assert.ok(sources.every(x => !x.available && x.reasonCode === 'source-unavailable'));
20
+ assert.deepEqual(sources.map(x => x.id), ['codex', 'opencode', 'agy']);
21
+ assert.ok(sources.slice(0, 2).every(x => !x.available && x.reasonCode === 'source-unavailable'));
22
22
  assert.equal(JSON.stringify(sources).includes(f.home), false);
23
23
  });
24
24
 
25
+ test('AGY reports the CLI credential constraint and leaves supported imports available', async t => {
26
+ const f = await fixture(t);
27
+ await f.put('opencode', { 'google-antigravity': { type: 'oauth', access: 'synthetic-opencode-access' } });
28
+ const sources = await f.discoverLocalSources();
29
+ const agy = sources.find(source => source.id === 'agy');
30
+ assert.equal(agy.available, false);
31
+ assert.deepEqual(agy.providers, [{ provider: 'google-antigravity', authType: 'oauth', available: false, reasonCode: 'source-does-not-export-credentials' }]);
32
+ assert.equal(sources.find(source => source.id === 'opencode').available, true);
33
+ await assert.rejects(f.readLocalSource('agy', 'google-antigravity'), { code: 'source-does-not-export-credentials' });
34
+ await assert.rejects(f.readLocalSource('agy', 'openai-codex'), { code: 'unsupported-source' });
35
+ });
36
+
25
37
  test('Codex ChatGPT token normalizes account and expiry, but never exports refresh or ID tokens', async t => {
26
38
  const f = await fixture(t), access = jwt();
27
39
  await f.put('codex', { auth_mode: 'chatgpt', tokens: { access_token: access, refresh_token: 'synthetic-refresh-secret', id_token: 'synthetic-id-secret', account_id: 'account-fixture' }, last_refresh: '2026-11-16T11:00:00Z' });
@@ -166,3 +178,24 @@ test('provider dictionary names cannot disclose another entry secret in preview'
166
178
  assert.equal(JSON.stringify(preview).includes('synthetic-token-value'), false);
167
179
  assert.deepEqual(preview[1].providers.map(x => x.provider), ['anthropic']);
168
180
  });
181
+
182
+ test('OpenCode v2 discovery uses redacted metadata; imports reread only the requested credential', async t => {
183
+ const f = await fixture(t);
184
+ await f.put('opencode', { openrouter: { type: 'api', key: 'obsolete-legacy-key' } });
185
+ let key = 'v2-first-key';
186
+ const calls = [];
187
+ const runOpenCode = async args => {
188
+ calls.push(args);
189
+ if (args[0] === '--version') return '2.1.0\n';
190
+ if (args[1] === 'list') return JSON.stringify([{ id: 'openrouter', connections: [{ type: 'credential', method: 'key' }] }]);
191
+ assert.deepEqual(args, ['auth', 'export', 'openrouter']);
192
+ return JSON.stringify([{ integrationID: 'openrouter', value: { type: 'key', key } }]);
193
+ };
194
+ const sources = createLocalSources({ home: f.home, runOpenCode });
195
+ const results = await sources.discoverLocalSources();
196
+ assert.deepEqual(results.find(source => source.id === 'opencode').providers, [{ provider: 'openrouter', authType: 'api-key', available: true }]);
197
+ assert.deepEqual(calls, [['--version'], ['auth', 'list', '--format', 'json']]);
198
+ assert.equal((await sources.readLocalSource('opencode', 'openrouter')).grant.access, 'v2-first-key');
199
+ key = 'v2-rotated-key';
200
+ assert.equal((await sources.readLocalSource('opencode', 'openrouter')).grant.access, key);
201
+ });
package/src/media.js CHANGED
@@ -22,6 +22,7 @@ export function registerMediaTools(ctx, resolveGrant, pulls) {
22
22
  description: "Generate an image with the signed-in account's image model. The current conversation and its chat model stay as they are.",
23
23
  parameters: {
24
24
  prompt: { type: "string", required: true, description: "What the image should show." },
25
+ model: { type: "string", description: "Optional image model ID from this connection's imported models." },
25
26
  aspect_ratio: { type: "string", description: "Optional ratio such as 1:1, 16:9, or 9:16." },
26
27
  image_url: { type: "string", description: "Optional source image URL when the user wants an edit rather than a new image." },
27
28
  },
@@ -31,7 +32,7 @@ export function registerMediaTools(ctx, resolveGrant, pulls) {
31
32
  },
32
33
  timeoutMs: 120000,
33
34
  async execute(args, exec) {
34
- return runMedia(ctx, "image", args.prompt, args.aspect_ratio, exec, undefined, args.image_url, resolveGrant, pulls);
35
+ return runMedia(ctx, "image", args, exec, resolveGrant, pulls);
35
36
  },
36
37
  })));
37
38
  ctx.effect(() => ctx.tools.register(defineTool({
@@ -39,6 +40,7 @@ export function registerMediaTools(ctx, resolveGrant, pulls) {
39
40
  description: "Generate a short video with the signed-in account's video model. The current conversation and its chat model stay as they are.",
40
41
  parameters: {
41
42
  prompt: { type: "string", required: true, description: "What the video should show." },
43
+ model: { type: "string", description: "Optional video model ID from this connection's imported models." },
42
44
  aspect_ratio: { type: "string", description: "Optional ratio such as 16:9 or 9:16." },
43
45
  duration: { type: "number", description: "Length in seconds, from 1 to 15." },
44
46
  image_url: { type: "string", description: "Optional still image URL to animate." },
@@ -49,7 +51,7 @@ export function registerMediaTools(ctx, resolveGrant, pulls) {
49
51
  },
50
52
  timeoutMs: 180000,
51
53
  async execute(args, exec) {
52
- return runMedia(ctx, "video", args.prompt, args.aspect_ratio, exec, args.duration, args.image_url, resolveGrant, pulls);
54
+ return runMedia(ctx, "video", args, exec, resolveGrant, pulls);
53
55
  },
54
56
  })));
55
57
  }
@@ -58,11 +60,12 @@ const MEDIA_BASE = {
58
60
  xai: "https://api.x.ai/v1",
59
61
  };
60
62
 
61
- async function runMedia(ctx, role, prompt, aspectRatio, exec, duration, imageUrl, resolveGrant, pulls) {
63
+ async function runMedia(ctx, role, args, exec, resolveGrant, pulls) {
62
64
  const chatProvider = exec.agent?.options?.provider;
63
65
  const chatModel = exec.agent?.options?.model;
64
- const target = await mediaTarget(chatProvider, role, pulls);
66
+ const target = await mediaTarget(chatProvider, role, args.model, pulls);
65
67
  if (target === undefined) {
68
+ if (args.model) throw new Error("所选媒体模型不在此连接已导入的对应目录中。");
66
69
  throw new Error(`当前对话还没有可用的${role === "image" ? "生图" : "生视频"}模型。对话模型保持不变。`);
67
70
  }
68
71
  if (target.base === undefined) {
@@ -72,16 +75,16 @@ async function runMedia(ctx, role, prompt, aspectRatio, exec, duration, imageUrl
72
75
  const access = grant.access;
73
76
  if (access.length === 0) throw new Error("OAuth 登录已失效,无法调用媒体模型。对话模型保持不变。");
74
77
  const url = role === "image"
75
- ? await generateImage(target.base, access, target.model, prompt, aspectRatio, imageUrl, exec.signal)
76
- : await generateVideo(target.base, access, target.model, prompt, aspectRatio, duration, imageUrl, exec.signal);
78
+ ? await generateImage(target.base, access, target.model, args.prompt, args.aspect_ratio, args.image_url, exec.signal)
79
+ : await generateVideo(target.base, access, target.model, args.prompt, args.aspect_ratio, args.duration, args.image_url, exec.signal);
77
80
  const stayed = chatModel ? `当前对话模型仍是 ${chatModel}。` : "当前对话模型未改变。";
78
81
  return `已用 ${target.model} 完成${role === "image" ? "生图" : "生视频"}。${stayed}\n${url}`;
79
82
  }
80
83
 
81
- async function mediaTarget(chatProvider, role, pulls) {
84
+ async function mediaTarget(chatProvider, role, selected, pulls) {
82
85
  if (typeof chatProvider !== "string" || chatProvider.length === 0) return undefined;
83
86
  const pull = (await pulls.list()).find((item) => item.id === chatProvider);
84
- const model = pull?.media?.find((item) => item.role === role);
87
+ const model = pull?.media?.find((item) => item.role === role && (!selected || item.id === selected));
85
88
  if (!model) return undefined;
86
89
  return { provider: chatProvider, model: model.id, base: MEDIA_BASE[chatProvider] };
87
90
  }