@stage-labs/metro 0.1.0-beta.145 → 0.1.0-beta.147

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/dist/route.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { agentsDir } from './local.js';
4
- const PROVIDERS = ['bedrock', 'openrouter', 'codex'];
4
+ const PROVIDERS = ['bedrock', 'openrouter', 'codex', 'gemini'];
5
5
  export function currentRoute(dir = agentsDir()) {
6
6
  const path = join(dir, 'model.json');
7
7
  if (!existsSync(path))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stage-labs/metro",
3
- "version": "0.1.0-beta.145",
3
+ "version": "0.1.0-beta.147",
4
4
  "description": "The metro command line. Sign in once per machine, then hand your MCP connector list to Claude Code without the credentials touching disk, argv or shell history.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "metro",
3
- "version": "0.1.0-beta.145",
3
+ "version": "0.1.0-beta.147",
4
4
  "description": "Metro for Claude Code, installed by the metro daemon on this machine: every connector the agent holds as its own MCP server relayed through the daemon, the orchestrator-only guard on the main thread, and the standing rules loaded at each session start. No vendor credential ever sits in a config file.",
5
5
  "author": {
6
6
  "name": "Bonustrack",
@@ -24,10 +24,6 @@ export interface OwnedAgent {
24
24
 
25
25
  export type DeletedAgent = OwnedAgent;
26
26
 
27
- export interface ResetAgentKey extends OwnedAgent {
28
- key: string;
29
- }
30
-
31
27
  export function normalizeAgentName(raw: unknown): string {
32
28
  const name = typeof raw === 'string' ? raw.trim() : '';
33
29
  if (!AGENT_NAME_RE.test(name))
@@ -19,7 +19,6 @@ import {
19
19
  import {
20
20
  type AgentSummary,
21
21
  type DeletedAgent,
22
- type ResetAgentKey,
23
22
  } from './admin.js';
24
23
 
25
24
  const PREFIX = '/api/agents';
@@ -30,10 +29,6 @@ export interface AgentApiDeps extends AccountApiDeps {
30
29
  subject: string,
31
30
  id: string,
32
31
  ) => Promise<DeletedAgent>;
33
- resetKey: (
34
- subject: string,
35
- id: string,
36
- ) => Promise<ResetAgentKey>;
37
32
  gatherAccounts: (allowed: Set<string>) => Promise<{
38
33
  accounts: Record<string, unknown[]>;
39
34
  unavailable: string[];
@@ -47,14 +42,12 @@ export interface AgentApiDeps extends AccountApiDeps {
47
42
  type Routable =
48
43
  | { kind: 'collection' }
49
44
  | { kind: 'agent'; id: string }
50
- | { kind: 'key'; id: string }
51
45
  | { kind: 'accounts'; id: string; route: AccountRoute };
52
46
 
53
47
  type Target = Routable | { kind: 'unknown' } | null;
54
48
 
55
49
  function subTarget(id: string, rest: string[]): Target {
56
50
  if (rest.length === 0) return { kind: 'agent', id };
57
- if (rest.length === 1 && rest[0] === 'key') return { kind: 'key', id };
58
51
  if (rest[0] !== 'accounts') return { kind: 'unknown' };
59
52
  const route = accountRoute(rest.slice(1));
60
53
  return route === null ? { kind: 'unknown' } : { kind: 'accounts', id, route };
@@ -145,26 +138,6 @@ async function handleList(
145
138
  sendJson(req, res, 200, { ...base, accounts, unavailable });
146
139
  }
147
140
 
148
- async function handleResetKey(
149
- req: IncomingMessage,
150
- res: ServerResponse,
151
- deps: AgentApiDeps,
152
- session: ApiSession,
153
- id: string,
154
- ): Promise<void> {
155
- const reset = await deps.resetKey(session.subject, id);
156
- log.info(
157
- { agent: reset.name, id: reset.id, owner: session.subject },
158
- 'agent-api: reset agent key',
159
- );
160
- sendJson(req, res, 200, {
161
- id: reset.id,
162
- name: reset.name,
163
- reset: true,
164
- ...credentials(reset.key),
165
- });
166
- }
167
-
168
141
  async function handleDelete(
169
142
  req: IncomingMessage,
170
143
  res: ServerResponse,
@@ -190,11 +163,10 @@ async function routeAgent(
190
163
  tgt: AgentTarget,
191
164
  ): Promise<void> {
192
165
  try {
193
- if (tgt.kind !== 'collection') requireAdmin(session);
194
- if (tgt.kind === 'key') await handleResetKey(req, res, deps, session, tgt.id);
195
- else if (tgt.kind === 'agent')
166
+ if (tgt.kind === 'agent') {
167
+ requireAdmin(session);
196
168
  await handleDelete(req, res, deps, session, tgt.id);
197
- else await handleList(req, res, deps, session);
169
+ } else await handleList(req, res, deps, session);
198
170
  } catch (err) {
199
171
  apiFailure(req, res, err);
200
172
  }
@@ -203,7 +175,6 @@ async function routeAgent(
203
175
  const ALLOWED: Record<AgentTarget['kind'], string[]> = {
204
176
  collection: ['GET'],
205
177
  agent: ['DELETE'],
206
- key: ['POST'],
207
178
  };
208
179
 
209
180
  function methodAllowed(tgt: Routable, method: string | undefined): boolean {
@@ -4,14 +4,13 @@ import { ApiError } from '@metro-labs/http/api-error';
4
4
  import { isOrganizationId } from '@metro-labs/http/workos-token';
5
5
  import { ensureSecureDir, writeSecure } from '@metro-labs/core/secure-fs';
6
6
  import {
7
- AgentAdminError,
8
7
  newApiKey,
8
+ AgentAdminError,
9
9
  normalizeAgentName,
10
10
  type AgentSummary,
11
11
  type CreatedAgent,
12
12
  type DeletedAgent,
13
13
  type OwnedAgent,
14
- type ResetAgentKey,
15
14
  } from './admin.js';
16
15
  import type { AccountRef } from './account-attach.js';
17
16
  import {
@@ -24,7 +23,7 @@ import {
24
23
  type AgentFile,
25
24
  } from './files.js';
26
25
  import { newId } from '@metro-labs/core/ids';
27
- import { registerKey, rotateAgentKey, unregisterAgentKey } from './keys.js';
26
+ import { registerKey, unregisterAgentKey } from './keys.js';
28
27
  import { MOVABLE_STATIONS, type LoadedAgent } from '../stations/materialize.js';
29
28
  import type { StationName } from '@metro-labs/core/station-names';
30
29
  import { normalizeAddress } from '@metro-labs/core/address';
@@ -144,19 +143,6 @@ export async function ensureLocalAgent(dir = agentsDir()): Promise<Ensured> {
144
143
  return 'created';
145
144
  }
146
145
 
147
- export async function localResetAgentKey(
148
- subject: string,
149
- id: string,
150
- dir = agentsDir(),
151
- ): Promise<ResetAgentKey> {
152
- const stored = ownedOrThrow(subject, id, dir);
153
- const key = newApiKey();
154
- stored.file.key = key;
155
- save(stored);
156
- rotateAgentKey(id, key);
157
- return Promise.resolve({ id, name: stored.file.name, key });
158
- }
159
-
160
146
  export async function localDeleteAgent(
161
147
  subject: string,
162
148
  id: string,
@@ -30,11 +30,6 @@ export function unregisterAgentKey(agentId: string): void {
30
30
  if (id === agentId) agentIdByKeyHash.delete(hash);
31
31
  }
32
32
 
33
- export function rotateAgentKey(agentId: string, key: string | null): void {
34
- unregisterAgentKey(agentId);
35
- if (key !== null) registerKey(key, agentId);
36
- }
37
-
38
33
  export function agentIdForKey(token: string): string | undefined {
39
34
  if (token === '') return undefined;
40
35
  return agentIdByKeyHash.get(digest(token));
@@ -23,7 +23,7 @@ import { agentsDir, fileSource } from '../agents/files.js';
23
23
  import { syncPluginServers } from '../connectors/plugin-sync.js';
24
24
  import { readLocalConnectors } from '../connectors/store.js';
25
25
  import { ensureMetroPlugin } from '../claude/plugin-install.js';
26
- import { sessionRunning, stopSession, unwatchSession, watchSession } from '../claude/session.js';
26
+ import { unwatchSession, watchSession } from '../claude/session.js';
27
27
  import { tryClaudeSetup } from '../claude/setup.js';
28
28
  import { applyLocalOwner } from './local-owner.js';
29
29
  import { installBearerSessions } from '../routes/bearer.js';
@@ -34,7 +34,6 @@ import { localSessionApis } from '../routes/local-mode.js';
34
34
  import type { SessionApis } from '../routes/session-apis.js';
35
35
  import {
36
36
  agentLiveness,
37
- closeAgentSession,
38
37
  createMetroMcp,
39
38
  } from '../mcp/index.js';
40
39
  import { metroCall } from '../mcp/ctx.js';
@@ -116,12 +115,6 @@ function sessionApis(): SessionApis {
116
115
  exitCode = HOLD_EXIT;
117
116
  onShutdown();
118
117
  },
119
- closeAgentSession,
120
- restartClaudeSession: () => {
121
- if (!sessionRunning()) return false;
122
- stopSession();
123
- return true;
124
- },
125
118
  gatherAccounts: gatherAccountsForAgents,
126
119
  capabilities: accountStationCapabilities,
127
120
  liveness: agentLiveness,
@@ -10,8 +10,12 @@ import {
10
10
  type Adaptations,
11
11
  } from './bedrock.js';
12
12
  import { anthropicHeaders, forwardedHeaders, GatewayError, parseJson, pipeResponse, readBody, sendError, watchUpstream } from './forward.js';
13
- import { notReady, readModelConfig, resolveRoute, routeLabel, setCodexAuth, writeModelConfig, type ModelConfig, type Route } from './model-config.js';
14
- import { codexCount, codexMessages, freshCodexState, type CodexDeps } from './codex.js';
13
+ import { notReady, readModelConfig, resolveRoute, routeLabel, setCodexAuth, setGeminiAuth, writeModelConfig, type ModelConfig, type Route } from './model-config.js';
14
+ import { codexCount, codexMessages, freshCodexState } from './codex.js';
15
+ import { freshGeminiState, geminiCount, geminiMessages } from './gemini.js';
16
+ import type { GeminiDeps } from './gemini.js';
17
+ import type { CodexDeps } from './codex.js';
18
+ import type { GeminiTokens } from './gemini-auth.js';
15
19
  import { OPENROUTER_BASE } from './openrouter.js';
16
20
  import { isRecord } from '@metro-labs/core/is-record';
17
21
  import { forgetServed, noteServed } from './served.js';
@@ -32,10 +36,12 @@ export interface GatewayDeps {
32
36
  bedrockBase?: string;
33
37
  openrouterBase?: string;
34
38
  codex?: Partial<CodexDeps>;
39
+ gemini?: Partial<GeminiDeps>;
35
40
  }
36
41
 
37
42
  const learned: Adaptations = freshAdaptations();
38
43
  const codexState = freshCodexState();
44
+ const geminiState = freshGeminiState();
39
45
 
40
46
  export function resetGatewayState(): void {
41
47
  forgetServed();
@@ -43,12 +49,17 @@ export function resetGatewayState(): void {
43
49
  learned.fields.clear();
44
50
  learned.dropBetas = false;
45
51
  Object.assign(codexState, freshCodexState());
52
+ Object.assign(geminiState, freshGeminiState());
46
53
  }
47
54
 
48
55
  const saveCodexTokens = (tokens: CodexTokens): void => {
49
56
  writeModelConfig(setCodexAuth(readModelConfig(), tokens));
50
57
  };
51
58
 
59
+ const saveGeminiTokens = (tokens: GeminiTokens): void => {
60
+ writeModelConfig(setGeminiAuth(readModelConfig(), tokens));
61
+ };
62
+
52
63
  const keyOf = (req: IncomingMessage): string => {
53
64
  const raw = req.headers['x-metro-key'];
54
65
  return (Array.isArray(raw) ? raw[0] : raw)?.trim() ?? '';
@@ -64,6 +75,8 @@ function modelsBody(cfg: ModelConfig): Record<string, unknown> {
64
75
  data.push({ id: `openrouter:${cfg.openrouter.model}`, display_name: `OpenRouter · ${cfg.openrouter.model}`, description: 'Through metro, billed to OpenRouter' });
65
76
  if (cfg.codex.model !== '')
66
77
  data.push({ id: `codex:${cfg.codex.model}`, display_name: `Codex · ${cfg.codex.model}`, description: 'Through metro, on your ChatGPT subscription' });
78
+ if (cfg.gemini.model !== '')
79
+ data.push({ id: `gemini:${cfg.gemini.model}`, display_name: `Gemini · ${cfg.gemini.model}`, description: 'Through metro, on your Google account' });
67
80
  return { data, has_more: false, first_id: data[0]?.id ?? null, last_id: data.at(-1)?.id ?? null };
68
81
  }
69
82
 
@@ -94,7 +107,7 @@ async function toAnthropic(
94
107
  throw new GatewayError(
95
108
  403,
96
109
  'permission_error',
97
- 'Claude Code on this machine has no Anthropic login of its own; choose Bedrock, OpenRouter or Codex on the Model page, or sign in on the Claude tab',
110
+ 'Claude Code on this machine has no Anthropic login of its own; choose Bedrock, OpenRouter, Codex or Gemini on the Model page, or sign in on the Claude tab',
98
111
  );
99
112
  const watch = watchUpstream(res);
100
113
  const upstream = await fetch(url, {
@@ -156,6 +169,16 @@ function noteRefusal(provider: string, model: string, upstream: Response): void
156
169
  if (!upstream.ok) log.warn({ provider, model, status: upstream.status }, 'gateway: the provider refused the request');
157
170
  }
158
171
 
172
+ async function toSubscription(req: IncomingMessage, res: ServerResponse, path: string, body: Record<string, unknown>, route: Route, cfg: ModelConfig, deps: GatewayDeps): Promise<void> {
173
+ if (route.provider === 'gemini') {
174
+ if (path === COUNT) geminiCount(res, body);
175
+ else await geminiMessages(req, res, body, route.model, cfg, { save: saveGeminiTokens, ...deps.gemini }, geminiState, watchUpstream(res));
176
+ return;
177
+ }
178
+ if (path === COUNT) codexCount(res, body);
179
+ else await codexMessages(req, res, body, route.model, cfg, { save: saveCodexTokens, ...deps.codex }, codexState, watchUpstream(res));
180
+ }
181
+
159
182
  async function dispatch(req: IncomingMessage, res: ServerResponse, path: string, deps: GatewayDeps): Promise<void> {
160
183
  const cfg = deps.config();
161
184
  const raw = await readBody(req);
@@ -175,13 +198,8 @@ async function dispatch(req: IncomingMessage, res: ServerResponse, path: string,
175
198
  await toOpenRouter(req, res, body, route, cfg, deps);
176
199
  return;
177
200
  }
178
- if (route.provider === 'codex') {
179
- if (path === COUNT) {
180
- codexCount(res, body);
181
- return;
182
- }
183
- const codexDeps: CodexDeps = { save: saveCodexTokens, ...deps.codex };
184
- await codexMessages(req, res, body, route.model, cfg, codexDeps, codexState, watchUpstream(res));
201
+ if (route.provider === 'codex' || route.provider === 'gemini') {
202
+ await toSubscription(req, res, path, body, route, cfg, deps);
185
203
  return;
186
204
  }
187
205
  await toAnthropic(req, res, raw, body, route, deps);
@@ -0,0 +1,160 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { isRecord } from '@metro-labs/core/is-record';
3
+
4
+ export const GEMINI_CLIENT_ID = '681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com';
5
+ export const GEMINI_CLIENT_SECRET = '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';
6
+ export const GEMINI_AUTH_BASE = 'https://accounts.google.com';
7
+ export const GEMINI_TOKEN_BASE = 'https://oauth2.googleapis.com';
8
+ export const GEMINI_REDIRECT = 'https://codeassist.google.com/authcode';
9
+ const SCOPE = 'https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile';
10
+ const PENDING_TTL_MS = 10 * 60_000;
11
+ const EXPIRY_MARGIN_MS = 5 * 60_000;
12
+ const DEFAULT_TTL_MS = 55 * 60_000;
13
+
14
+ export interface GeminiTokens {
15
+ accessToken: string;
16
+ refreshToken: string;
17
+ expiresAt: number;
18
+ email: string | null;
19
+ project: string;
20
+ tier: string | null;
21
+ savedAt: string;
22
+ }
23
+
24
+ export class GeminiAuthError extends Error {}
25
+
26
+ interface Pending {
27
+ verifier: string;
28
+ at: number;
29
+ }
30
+
31
+ const pending = new Map<string, Pending>();
32
+
33
+ const b64url = (buf: Buffer): string => buf.toString('base64url');
34
+
35
+ export function newPkce(): { verifier: string; challenge: string } {
36
+ const verifier = b64url(randomBytes(32));
37
+ return { verifier, challenge: b64url(createHash('sha256').update(verifier).digest()) };
38
+ }
39
+
40
+ export function authorizeUrl(state: string, challenge: string, base = GEMINI_AUTH_BASE): string {
41
+ const params = new URLSearchParams({
42
+ client_id: GEMINI_CLIENT_ID,
43
+ redirect_uri: GEMINI_REDIRECT,
44
+ response_type: 'code',
45
+ scope: SCOPE,
46
+ access_type: 'offline',
47
+ prompt: 'consent',
48
+ code_challenge: challenge,
49
+ code_challenge_method: 'S256',
50
+ state,
51
+ });
52
+ return `${base}/o/oauth2/v2/auth?${params.toString()}`;
53
+ }
54
+
55
+ function sweep(now: number): void {
56
+ for (const [state, entry] of pending) if (now - entry.at > PENDING_TTL_MS) pending.delete(state);
57
+ }
58
+
59
+ export function beginLogin(base = GEMINI_AUTH_BASE, now = Date.now()): { url: string; state: string } {
60
+ sweep(now);
61
+ const { verifier, challenge } = newPkce();
62
+ const state = b64url(randomBytes(16));
63
+ pending.set(state, { verifier, at: now });
64
+ return { url: authorizeUrl(state, challenge, base), state };
65
+ }
66
+
67
+ const text = (value: unknown): string | null => (typeof value === 'string' && value !== '' ? value : null);
68
+
69
+ const refusalIn = (body: Record<string, unknown>): string => text(body.error_description) ?? text(body.error) ?? 'Google answered without an access token';
70
+
71
+ function grantedTokens(body: unknown, previous: GeminiTokens | null): { accessToken: string; refreshToken: string; ttl: number } {
72
+ if (!isRecord(body)) throw new GeminiAuthError('Google answered without tokens');
73
+ const accessToken = text(body.access_token);
74
+ if (accessToken === null) throw new GeminiAuthError(refusalIn(body));
75
+ const refreshToken = text(body.refresh_token) ?? previous?.refreshToken ?? '';
76
+ if (refreshToken === '') throw new GeminiAuthError('Google issued no refresh token; sign in again');
77
+ return { accessToken, refreshToken, ttl: typeof body.expires_in === 'number' ? body.expires_in * 1000 : DEFAULT_TTL_MS };
78
+ }
79
+
80
+ function tokensOf(body: unknown, previous: GeminiTokens | null, now: number): GeminiTokens {
81
+ const granted = grantedTokens(body, previous);
82
+ return {
83
+ accessToken: granted.accessToken,
84
+ refreshToken: granted.refreshToken,
85
+ expiresAt: now + granted.ttl,
86
+ email: previous?.email ?? null,
87
+ project: previous?.project ?? '',
88
+ tier: previous?.tier ?? null,
89
+ savedAt: new Date(now).toISOString(),
90
+ };
91
+ }
92
+
93
+ async function tokenCall(form: Record<string, string>, base: string, fetchImpl: typeof fetch): Promise<unknown> {
94
+ let res: Response;
95
+ try {
96
+ res = await fetchImpl(`${base}/token`, {
97
+ method: 'POST',
98
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
99
+ body: new URLSearchParams(form).toString(),
100
+ signal: AbortSignal.timeout(30_000),
101
+ });
102
+ } catch (err) {
103
+ throw new GeminiAuthError(`could not reach Google: ${err instanceof Error ? err.message : String(err)}`);
104
+ }
105
+ const body: unknown = await res.json().catch(() => null);
106
+ if (!res.ok) throw new GeminiAuthError(isRecord(body) ? (text(body.error_description) ?? text(body.error) ?? `Google answered ${String(res.status)}`) : `Google answered ${String(res.status)}`);
107
+ return body;
108
+ }
109
+
110
+ export async function exchangeCode(code: string, state: string, base = GEMINI_TOKEN_BASE, fetchImpl: typeof fetch = fetch, now = Date.now()): Promise<GeminiTokens> {
111
+ sweep(now);
112
+ const entry = pending.get(state);
113
+ if (entry === undefined) throw new GeminiAuthError('that sign-in has expired; start it again');
114
+ pending.delete(state);
115
+ const trimmed = code.trim();
116
+ if (trimmed === '') throw new GeminiAuthError('paste the code Google showed');
117
+ const body = await tokenCall(
118
+ { client_id: GEMINI_CLIENT_ID, client_secret: GEMINI_CLIENT_SECRET, grant_type: 'authorization_code', code: trimmed, code_verifier: entry.verifier, redirect_uri: GEMINI_REDIRECT },
119
+ base,
120
+ fetchImpl,
121
+ );
122
+ return tokensOf(body, null, now);
123
+ }
124
+
125
+ export async function refreshTokens(previous: GeminiTokens, base = GEMINI_TOKEN_BASE, fetchImpl: typeof fetch = fetch, now = Date.now()): Promise<GeminiTokens> {
126
+ const body = await tokenCall(
127
+ { client_id: GEMINI_CLIENT_ID, client_secret: GEMINI_CLIENT_SECRET, grant_type: 'refresh_token', refresh_token: previous.refreshToken },
128
+ base,
129
+ fetchImpl,
130
+ );
131
+ return tokensOf(body, previous, now);
132
+ }
133
+
134
+ export const tokensStale = (tokens: GeminiTokens, now = Date.now()): boolean => tokens.expiresAt - EXPIRY_MARGIN_MS <= now;
135
+
136
+ export async function userEmail(tokens: GeminiTokens, base = 'https://www.googleapis.com', fetchImpl: typeof fetch = fetch): Promise<string | null> {
137
+ try {
138
+ const res = await fetchImpl(`${base}/oauth2/v2/userinfo`, { headers: { authorization: `Bearer ${tokens.accessToken}` }, signal: AbortSignal.timeout(15_000) });
139
+ const body: unknown = await res.json().catch(() => null);
140
+ return res.ok && isRecord(body) ? text(body.email) : null;
141
+ } catch {
142
+ return null;
143
+ }
144
+ }
145
+
146
+ export function tokensFromDisk(raw: unknown): GeminiTokens | null {
147
+ if (!isRecord(raw)) return null;
148
+ const accessToken = text(raw.accessToken);
149
+ const refreshToken = text(raw.refreshToken);
150
+ if (accessToken === null || refreshToken === null) return null;
151
+ return {
152
+ accessToken,
153
+ refreshToken,
154
+ expiresAt: typeof raw.expiresAt === 'number' ? raw.expiresAt : 0,
155
+ email: text(raw.email),
156
+ project: text(raw.project) ?? '',
157
+ tier: text(raw.tier),
158
+ savedAt: text(raw.savedAt) ?? '',
159
+ };
160
+ }
@@ -0,0 +1,67 @@
1
+ import { isRecord } from '@metro-labs/core/is-record';
2
+ import { GeminiAuthError, type GeminiTokens } from './gemini-auth.js';
3
+
4
+ export const CODE_ASSIST_BASE = 'https://cloudcode-pa.googleapis.com';
5
+ const API = 'v1internal';
6
+ const METADATA = { ideType: 'IDE_UNSPECIFIED', platform: 'PLATFORM_UNSPECIFIED', pluginType: 'GEMINI' };
7
+ const FREE_TIER = 'free-tier';
8
+ const POLL_MS = 5000;
9
+ const POLL_MAX = 24;
10
+
11
+ export interface Onboarded {
12
+ project: string;
13
+ tier: string | null;
14
+ }
15
+
16
+ const text = (value: unknown): string | null => (typeof value === 'string' && value !== '' ? value : null);
17
+
18
+ async function call(base: string, method: string, token: string, body: unknown, fetchImpl: typeof fetch): Promise<Record<string, unknown>> {
19
+ let res: Response;
20
+ try {
21
+ res = await fetchImpl(`${base}/${API}:${method}`, {
22
+ method: 'POST',
23
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
24
+ body: JSON.stringify(body),
25
+ signal: AbortSignal.timeout(30_000),
26
+ });
27
+ } catch (err) {
28
+ throw new GeminiAuthError(`could not reach Google Code Assist: ${err instanceof Error ? err.message : String(err)}`);
29
+ }
30
+ const answer: unknown = await res.json().catch(() => null);
31
+ if (!res.ok) {
32
+ const detail = isRecord(answer) && isRecord(answer.error) ? text(answer.error.message) : null;
33
+ throw new GeminiAuthError(detail ?? `Google Code Assist answered ${String(res.status)} on ${method}`);
34
+ }
35
+ return isRecord(answer) ? answer : {};
36
+ }
37
+
38
+ const tierOf = (load: Record<string, unknown>): { id: string | null; name: string | null } => {
39
+ const tier = isRecord(load.paidTier) ? load.paidTier : isRecord(load.currentTier) ? load.currentTier : null;
40
+ return { id: tier === null ? null : text(tier.id), name: tier === null ? null : text(tier.name) };
41
+ };
42
+
43
+ async function waitOperation(base: string, token: string, first: Record<string, unknown>, fetchImpl: typeof fetch): Promise<Record<string, unknown>> {
44
+ let op = first;
45
+ for (let i = 0; op.done !== true && i < POLL_MAX; i += 1) {
46
+ const name = text(op.name);
47
+ if (name === null) break;
48
+ await new Promise((r) => setTimeout(r, POLL_MS));
49
+ const res = await fetchImpl(`${base}/${API}/${name}`, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(30_000) });
50
+ const answer: unknown = await res.json().catch(() => null);
51
+ op = isRecord(answer) ? answer : {};
52
+ }
53
+ return op;
54
+ }
55
+
56
+ export async function onboard(tokens: GeminiTokens, base = CODE_ASSIST_BASE, fetchImpl: typeof fetch = fetch): Promise<Onboarded> {
57
+ const load = await call(base, 'loadCodeAssist', tokens.accessToken, { metadata: METADATA }, fetchImpl);
58
+ const tier = tierOf(load);
59
+ const known = text(load.cloudaicompanionProject);
60
+ if (known !== null) return { project: known, tier: tier.name ?? tier.id };
61
+ const tierId = tier.id ?? FREE_TIER;
62
+ const op = await waitOperation(base, tokens.accessToken, await call(base, 'onboardUser', tokens.accessToken, { tierId, metadata: METADATA }, fetchImpl), fetchImpl);
63
+ const response = isRecord(op.response) ? op.response : {};
64
+ const project = isRecord(response.cloudaicompanionProject) ? text(response.cloudaicompanionProject.id) : null;
65
+ if (project === null) throw new GeminiAuthError('Google did not assign a Code Assist project to this account; sign in to https://geminicli.com once with the Gemini CLI, then try again');
66
+ return { project, tier: tier.name ?? tierId };
67
+ }