magpie-gemini-web 0.4.1 → 0.5.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "magpie-gemini-web",
3
- "version": "0.4.1",
4
- "description": "Gemini Web provider for Magpie, backed by gemini-web2api-go",
3
+ "version": "0.5.0",
4
+ "description": "Gemini Web and Google AI Studio provider for Magpie, backed by gemini-web2api-go and AIStudio2API",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "exports": "./index.mjs",
@@ -23,6 +23,8 @@
23
23
  "scripts/backend.mjs",
24
24
  "scripts/backend-argon.mjs",
25
25
  "scripts/backend-release.mjs",
26
+ "scripts/studio-smoke.mjs",
27
+ "scripts/studio.mjs",
26
28
  "patches/",
27
29
  "native-task/lib/",
28
30
  "native-task/bridge/",
@@ -58,7 +60,14 @@
58
60
  "backend:status": "node scripts/backend.mjs status",
59
61
  "backend:build:argon": "node scripts/backend-argon.mjs build",
60
62
  "backend:install:argon": "node scripts/backend-argon.mjs install",
61
- "backend:start:argon": "node scripts/backend-argon.mjs start"
63
+ "backend:start:argon": "node scripts/backend-argon.mjs start",
64
+ "studio:install": "node scripts/studio.mjs install",
65
+ "studio:start": "node scripts/studio.mjs start",
66
+ "studio:status": "node scripts/studio.mjs status",
67
+ "studio:stop": "node scripts/studio.mjs stop",
68
+ "studio:login": "node scripts/studio.mjs login",
69
+ "studio:relogin": "node scripts/studio.mjs relogin",
70
+ "studio:smoke": "node scripts/studio-smoke.mjs"
62
71
  },
63
72
  "magpie": {
64
73
  "maxConcurrency": 1
@@ -0,0 +1,195 @@
1
+ // Opt-in live acceptance probe. Sends synthetic prompts to the local Magpie gateway.
2
+ // Never run by npm test; never executes a model-requested tool or shell command.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import assert from 'node:assert/strict';
6
+ import { execFileSync } from 'node:child_process';
7
+ import { localStudio, studioAdmin, stopStudio } from '../lib/studio-native.mjs';
8
+
9
+ const args = process.argv.slice(2);
10
+ function option(name, fallback) {
11
+ const i = args.indexOf(name);
12
+ if (i < 0) return fallback;
13
+ if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`Missing ${name} value`);
14
+ return args[i + 1];
15
+ }
16
+ const gateway = new URL(option('--gateway', 'http://127.0.0.1:3425/v1'));
17
+ assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(gateway.hostname), 'live probe requires a local gateway');
18
+ assert.ok(['http:', 'https:'].includes(gateway.protocol));
19
+ assert.ok(!gateway.username && !gateway.password && !gateway.search && !gateway.hash);
20
+ const base = gateway.href.replace(/\/$/, '');
21
+ const model = option('--model', 'ai-studio/gemini-4-argon');
22
+ assert.ok(model.startsWith('ai-studio/'), 'only the AI Studio provider may be tested');
23
+ const outputDir = path.resolve(option('--out', 'evidence/studio-acceptance'));
24
+ fs.mkdirSync(outputDir, { recursive: true, mode: 0o700 });
25
+ const resultPath = path.join(outputDir, 'results.json');
26
+ const headers = { 'Content-Type': 'application/json', ...(process.env.MAGPIE_GATEWAY_KEY ? { Authorization: `Bearer ${process.env.MAGPIE_GATEWAY_KEY}` } : {}) };
27
+ const report = { startedAt: new Date().toISOString(), gateway: base, model, checks: [], status: 'running', requestCount: 0 };
28
+ const local = localStudio();
29
+ assert.ok(local, 'install and sign in to the managed AI Studio backend first');
30
+ function save() { fs.writeFileSync(resultPath, JSON.stringify(report, null, 2) + '\n', { mode: 0o600 }); }
31
+ async function check(name, fn) {
32
+ const start = performance.now();
33
+ try {
34
+ const evidence = await fn();
35
+ report.checks.push({ name, status: 'pass', elapsedMs: Math.round(performance.now() - start), ...evidence });
36
+ console.log(`PASS ${name}`); save(); return evidence;
37
+ } catch (error) {
38
+ report.checks.push({ name, status: 'fail', elapsedMs: Math.round(performance.now() - start), error: String(error.message).slice(0, 2000) });
39
+ console.error(`FAIL ${name}: ${String(error.message).slice(0, 1000)}`); save(); throw error;
40
+ }
41
+ }
42
+ function browserProcesses() {
43
+ if (process.platform === 'win32') return null;
44
+ return execFileSync('ps', ['-axo', 'pid=,comm='], { encoding: 'utf8' }).split('\n').filter(l => /camoufox|firefox/i.test(l));
45
+ }
46
+ async function chat(payload, options = {}) {
47
+ report.requestCount++;
48
+ const started = performance.now();
49
+ const signal = options.signal || AbortSignal.timeout(180000);
50
+ const response = await fetch(base + '/chat/completions', { method: 'POST', headers, body: JSON.stringify({ model, ...payload }), signal, redirect: 'error' });
51
+ assert.equal(response.status, 200, `HTTP ${response.status}: ${response.ok ? '' : (await response.text()).slice(0, 1500)}`);
52
+ if (!payload.stream) {
53
+ const body = await response.json();
54
+ assert.ok(!body.error, JSON.stringify(body.error));
55
+ return { id: body.id, content: body.choices?.[0]?.message?.content ?? '', finish: body.choices?.[0]?.finish_reason, elapsedMs: Math.round(performance.now() - started) };
56
+ }
57
+ assert.match(response.headers.get('content-type') || '', /text\/event-stream/);
58
+ const reader = response.body.getReader();
59
+ const decoder = new TextDecoder();
60
+ let pending = '', content = '', finish = null, id, done = false, contentMs = null, chunkCount = 0;
61
+ const calls = new Map();
62
+ function parse() {
63
+ pending = pending.replace(/\r\n/g, '\n');
64
+ let boundary;
65
+ while ((boundary = pending.indexOf('\n\n')) >= 0) {
66
+ const event = pending.slice(0, boundary); pending = pending.slice(boundary + 2);
67
+ const data = event.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5).trimStart()).join('\n');
68
+ if (!data) continue;
69
+ if (data === '[DONE]') { done = true; continue; }
70
+ const c = JSON.parse(data);
71
+ assert.ok(!c.error, JSON.stringify(c.error));
72
+ id = c.id ?? id;
73
+ const choice = c.choices?.find(choice => choice.index === 0);
74
+ if (!choice) continue;
75
+ chunkCount++;
76
+ const delta = choice.delta ?? {};
77
+ if (delta.content || delta.tool_calls?.length) contentMs ??= Math.round(performance.now() - started);
78
+ content += delta.content ?? '';
79
+ finish = choice.finish_reason ?? finish;
80
+ for (const t of delta.tool_calls ?? []) {
81
+ const prior = calls.get(t.index) ?? { id: '', type: 'function', function: { name: '', arguments: '' } };
82
+ if (t.id) prior.id = t.id;
83
+ if (t.function?.name) prior.function.name += t.function.name;
84
+ if (t.function?.arguments) prior.function.arguments += t.function.arguments;
85
+ if (t.extra_content) prior.extra_content = t.extra_content;
86
+ calls.set(t.index, prior);
87
+ }
88
+ }
89
+ }
90
+ try {
91
+ for (;;) {
92
+ const r = await reader.read();
93
+ if (r.done) break;
94
+ pending += decoder.decode(r.value, { stream: true }); parse();
95
+ }
96
+ pending += decoder.decode(); parse();
97
+ assert.ok(done, 'missing SSE [DONE]');
98
+ return { id, content, finish, calls: [...calls.values()], firstContentOrToolMs: contentMs, chunkCount, elapsedMs: Math.round(performance.now() - started) };
99
+ } finally { await reader.cancel().catch(() => {}); }
100
+ }
101
+ const tools = [
102
+ { type: 'function', function: { name: 'read_probe', description: 'Return the token for a synthetic test key.', parameters: { type: 'object', properties: { key: { type: 'string', enum: ['first'] } }, required: ['key'], additionalProperties: false } } },
103
+ { type: 'function', function: { name: 'verify_probe', description: 'Return a receipt for the exact token from read_probe.', parameters: { type: 'object', properties: { token: { type: 'string' } }, required: ['token'], additionalProperties: false } } },
104
+ ];
105
+ const messages = [{ role: 'user', content: 'First call read_probe with key first. Then call verify_probe using the exact token returned by read_probe. After verify_probe returns, reply with its receipt exactly, with no formatting or extra text. Preserve every character of the receipt, including brackets.' }];
106
+ // Deliberately simulate an OpenAI client/SDK that drops provider extension fields.
107
+ function clientCall(t) { return { id: t.id, type: 'function', function: { ...t.function } }; }
108
+ function toolEvidence(out, name, expected) {
109
+ assert.equal(out.calls.length, 1);
110
+ const call = out.calls[0];
111
+ assert.ok(call.id); assert.equal(call.function.name, name);
112
+ assert.deepEqual(JSON.parse(call.function.arguments), expected);
113
+ assert.equal(out.finish, 'tool_calls');
114
+ return { requestId: out.id, function: name, arguments: expected, signatureExposedByGateway: !!call.extra_content?.google?.thought_signature, firstContentOrToolMs: out.firstContentOrToolMs, elapsedMs: out.elapsedMs };
115
+ }
116
+ try {
117
+ await check('Go backend ready without a login browser', async () => {
118
+ const state = await studioAdmin(local, 'GET', '/api/status');
119
+ assert.equal(state.ready, true); assert.ok(state.accounts.total >= 1);
120
+ const browsers = browserProcesses(); if (browsers) assert.equal(browsers.length, 0);
121
+ return { state: state.state, readyAccounts: state.accounts.ready, browserProcesses: browsers };
122
+ });
123
+ await check('first native tool call through Magpie, medium effort', async () => {
124
+ const out = await chat({ messages, tools, tool_choice: { type: 'function', function: { name: 'read_probe' } }, reasoning_effort: 'medium', stream: true });
125
+ const evidence = toolEvidence(out, 'read_probe', { key: 'first' });
126
+ messages.push({ role: 'assistant', content: out.content || null, tool_calls: out.calls.map(clientCall) }, { role: 'tool', tool_call_id: out.calls[0].id, content: '{"token":"studio-token-8214"}' });
127
+ return evidence;
128
+ });
129
+ await check('second tool call uses first result without echoed signature', async () => {
130
+ const out = await chat({ messages, tools, tool_choice: { type: 'function', function: { name: 'verify_probe' } }, reasoning_effort: 'medium', stream: true });
131
+ const evidence = toolEvidence(out, 'verify_probe', { token: 'studio-token-8214' });
132
+ messages.push({ role: 'assistant', content: out.content || null, tool_calls: out.calls.map(clientCall) }, { role: 'tool', tool_call_id: out.calls[0].id, content: '{"receipt":"STUDIO_CITATION_[cite: 1]_8214"}' });
133
+ return evidence;
134
+ });
135
+ await check('tool continuation preserves literal citation text', async () => {
136
+ const out = await chat({ messages, tools, tool_choice: 'none', reasoning_effort: 'medium', stream: true });
137
+ assert.equal(out.content.trim(), 'STUDIO_CITATION_[cite: 1]_8214'); assert.equal(out.finish, 'stop');
138
+ assert.equal(out.calls.length, 0); messages.push({ role: 'assistant', content: out.content });
139
+ return { requestId: out.id, content: out.content, firstContentOrToolMs: out.firstContentOrToolMs, elapsedMs: out.elapsedMs };
140
+ });
141
+ await check('next user turn retains both tool results', async () => {
142
+ const out = await chat({ messages: [...messages, { role: 'user', content: 'Reply with the token returned by read_probe, then a vertical bar, then the receipt returned by verify_probe. Preserve all characters; no extra text or spaces around the vertical bar.' }], stream: false });
143
+ assert.equal(out.content.trim(), 'studio-token-8214|STUDIO_CITATION_[cite: 1]_8214');
144
+ return { requestId: out.id, content: out.content, elapsedMs: out.elapsedMs };
145
+ });
146
+ await check('cancel an active Magpie request', async () => {
147
+ const controller = new AbortController();
148
+ let rejected = false, sawActive = false, requestError;
149
+ const pending = chat({ messages: [{ role: 'user', content: 'Write a numbered list of the integers 1 through 2000, with each integer written also as an English word. Continue until the whole list is complete.' }], stream: true, reasoning_effort: 'medium' }, { signal: controller.signal }).catch(error => { if (!controller.signal.aborted) requestError = error; else rejected = true; });
150
+ try {
151
+ const deadline = Date.now() + 15000;
152
+ while (Date.now() < deadline) {
153
+ const state = await studioAdmin(local, 'GET', '/api/status');
154
+ if (state.active_requests > 0) { sawActive = true; break; }
155
+ await new Promise(resolve => setTimeout(resolve, 200));
156
+ }
157
+ } finally { controller.abort(new DOMException('Acceptance probe cancellation', 'AbortError')); }
158
+ await pending; if (requestError) throw requestError;
159
+ assert.ok(sawActive, 'request never became active in Studio'); assert.ok(rejected, 'client did not observe cancellation');
160
+ const deadline = Date.now() + 15000;
161
+ let active;
162
+ do {
163
+ active = (await studioAdmin(local, 'GET', '/api/status')).active_requests;
164
+ if (!active) break;
165
+ await new Promise(resolve => setTimeout(resolve, 250));
166
+ } while (Date.now() < deadline);
167
+ assert.equal(active, 0, 'cancelled request still occupies upstream slot');
168
+ return { sawActive, clientAborted: rejected, activeAfterCancellation: active };
169
+ });
170
+ await check('request succeeds after cancellation', async () => {
171
+ const out = await chat({ messages: [{ role: 'user', content: 'Reply with exactly STUDIO_AFTER_CANCEL_8214 and nothing else.' }], stream: false });
172
+ assert.equal(out.content.trim(), 'STUDIO_AFTER_CANCEL_8214');
173
+ return { requestId: out.id, content: out.content, elapsedMs: out.elapsedMs };
174
+ });
175
+ await check('same Magpie sign-in resumes tool history after backend restart', async () => {
176
+ const pidPath = path.join(local.dataDir, 'backend.pid');
177
+ const before = Number(fs.readFileSync(pidPath, 'utf8').trim());
178
+ assert.ok(Number.isInteger(before) && before > 0);
179
+ await stopStudio();
180
+ const out = await chat({ messages: [...messages, { role: 'user', content: 'Reply with the token returned by read_probe, then a vertical bar, then the receipt returned by verify_probe. Preserve all characters; no extra text or spaces around the vertical bar.' }], stream: false });
181
+ assert.equal(out.content.trim(), 'studio-token-8214|STUDIO_CITATION_[cite: 1]_8214');
182
+ const after = Number(fs.readFileSync(pidPath, 'utf8').trim());
183
+ assert.ok(Number.isInteger(after) && after > 0); assert.notEqual(after, before);
184
+ const state = await studioAdmin(local, 'GET', '/api/status');
185
+ assert.equal(state.ready, true);
186
+ return { requestId: out.id, content: out.content, elapsedMs: out.elapsedMs, previousPid: before, currentPid: after, ready: state.ready };
187
+ });
188
+ await check('no login browser after gateway acceptance', async () => {
189
+ const browsers = browserProcesses(); if (browsers) assert.equal(browsers.length, 0);
190
+ return { browserProcesses: browsers };
191
+ });
192
+ report.status = 'pass';
193
+ } catch (error) {
194
+ report.status = 'failed'; report.error = String(error.message).slice(0, 2000); process.exitCode = 1;
195
+ } finally { report.finishedAt = new Date().toISOString(); save(); console.log(`RESULT ${report.status} ${resultPath}`); }
@@ -0,0 +1,377 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+ import {
6
+ studioDataDir,
7
+ localStudio,
8
+ installStudio,
9
+ ensureStudio,
10
+ studioAdmin,
11
+ studioAccounts,
12
+ stopStudio,
13
+ studioStatus,
14
+ validateConfig,
15
+ validateProxy,
16
+ generateEnv,
17
+ studioCommand
18
+ } from '../lib/studio-native.mjs';
19
+
20
+ const LOGIN_TIMEOUT_MS = 15 * 60 * 1000;
21
+
22
+ function printHelp() {
23
+ console.log(`magpie-gemini-web AI Studio management CLI
24
+
25
+ Usage:
26
+ node scripts/studio.mjs <command> [options]
27
+
28
+ Commands:
29
+ install [--archive <path>] [--proxy <url>] Install AIStudio2API binary and configure environment
30
+ start [--proxy <url>] Start local AIStudio2API service in the background
31
+ status Check service and accounts status
32
+ stop Stop local AIStudio2API service
33
+ login Open isolated browser login for a new Google account
34
+ relogin [<account>] Sign an account that needs it in again (its label or id)
35
+ import <auth-directory> Import accounts from an existing auth directory (service must be stopped)
36
+
37
+ Options:
38
+ --data-dir <path> Custom data directory
39
+ --proxy <url> HTTP, HTTPS, or SOCKS5 proxy URL
40
+ --archive <path> Local release archive file (.tar.gz or .zip)
41
+ `);
42
+ }
43
+
44
+ function parseArgs(args) {
45
+ const flags = { _: [] };
46
+ for (let i = 0; i < args.length; i++) {
47
+ const arg = args[i];
48
+ if (arg === '--help' || arg === '-h') {
49
+ flags.help = true;
50
+ } else if (arg === '--data-dir' || arg === '--proxy' || arg === '--archive') {
51
+ const next = args[i + 1];
52
+ if (!next || next.startsWith('--')) {
53
+ throw new Error(`Missing required value for option: ${arg}`);
54
+ }
55
+ const key = arg.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
56
+ flags[key] = args[++i];
57
+ } else if (arg.startsWith('--')) {
58
+ throw new Error(`Unknown option: ${arg}`);
59
+ } else {
60
+ flags._.push(arg);
61
+ }
62
+ }
63
+ return flags;
64
+ }
65
+
66
+ async function updateProxyConfig(dataDir, proxy) {
67
+ const configPath = path.join(dataDir, 'config.json');
68
+ if (!fs.existsSync(configPath)) return;
69
+ const config = validateConfig(JSON.parse(fs.readFileSync(configPath, 'utf8')));
70
+ config.proxy = validateProxy(proxy);
71
+ const tmp = `${configPath}.tmp.${Date.now()}.${crypto.randomBytes(4).toString('hex')}`;
72
+ fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
73
+ fs.renameSync(tmp, configPath);
74
+ fs.chmodSync(configPath, 0o600);
75
+
76
+ const envPath = path.join(dataDir, '.env');
77
+ const envContent = generateEnv(dataDir, config, { proxy: config.proxy });
78
+ const tmpEnv = `${envPath}.tmp.${Date.now()}.${crypto.randomBytes(4).toString('hex')}`;
79
+ fs.writeFileSync(tmpEnv, envContent, { mode: 0o600 });
80
+ fs.renameSync(tmpEnv, envPath);
81
+ fs.chmodSync(envPath, 0o600);
82
+ }
83
+
84
+ function validateStorageState(filePath) {
85
+ let content;
86
+ try {
87
+ content = JSON.parse(fs.readFileSync(filePath, 'utf8'));
88
+ } catch (err) {
89
+ throw new Error(`Invalid JSON in ${filePath}: ${err.message}`);
90
+ }
91
+
92
+ if (!content || typeof content !== 'object' || !Array.isArray(content.cookies) || !Array.isArray(content.origins)) {
93
+ throw new Error(`${filePath} must be an object with cookies and origins arrays`);
94
+ }
95
+
96
+ let hasAuthCookie = false;
97
+ for (const c of content.cookies) {
98
+ if (!c || typeof c !== 'object') {
99
+ throw new Error(`Invalid cookie entry in ${filePath}`);
100
+ }
101
+ if (typeof c.name !== 'string' || !c.name || typeof c.value !== 'string' || typeof c.domain !== 'string' || !c.domain) {
102
+ throw new Error(`Invalid cookie properties in ${filePath}`);
103
+ }
104
+ if (c.name === 'SAPISID' || c.name === '__Secure-3PAPISID') {
105
+ if (c.value.trim().length > 0) hasAuthCookie = true;
106
+ }
107
+ }
108
+
109
+ if (!hasAuthCookie) {
110
+ throw new Error(`${filePath} does not contain valid Google auth cookies (missing SAPISID or __Secure-3PAPISID)`);
111
+ }
112
+ }
113
+
114
+ async function main() {
115
+ const flags = parseArgs(process.argv.slice(2));
116
+ if (flags.help || flags._.length === 0) {
117
+ printHelp();
118
+ return;
119
+ }
120
+
121
+ const command = flags._[0];
122
+ const dataDir = flags.dataDir || studioDataDir();
123
+
124
+ switch (command) {
125
+ case 'install': {
126
+ const status = await studioStatus({ dataDir });
127
+ if (status.status === 'running' || status.status === 'outdated' || status.status === 'unresponsive') {
128
+ throw new Error('Cannot install or update AI Studio while service is running. Stop the service first.');
129
+ }
130
+ if (flags.proxy !== undefined) {
131
+ await updateProxyConfig(dataDir, flags.proxy);
132
+ }
133
+ console.log(`Installing AIStudio2API into ${dataDir}...`);
134
+ const local = await installStudio({
135
+ dataDir,
136
+ archivePath: flags.archive,
137
+ proxy: flags.proxy
138
+ });
139
+ console.log(`AIStudio2API installed successfully.`);
140
+ console.log(`Listen origin: ${local.origin}`);
141
+ console.log(`Data directory: ${local.dataDir}`);
142
+ break;
143
+ }
144
+ case 'start': {
145
+ const status = await studioStatus({ dataDir });
146
+ if (status.status === 'running') {
147
+ if (flags.proxy !== undefined) {
148
+ throw new Error('Cannot update proxy while service is running. Stop the service first.');
149
+ }
150
+ const local = await ensureStudio({ dataDir });
151
+ console.log(`AIStudio2API service is running.`);
152
+ console.log(`API Base URL: ${local.baseURL}`);
153
+ console.log(`Management URL: ${local.origin}`);
154
+ return;
155
+ }
156
+ if (flags.proxy !== undefined) {
157
+ await updateProxyConfig(dataDir, flags.proxy);
158
+ }
159
+ if (status.status === 'outdated') {
160
+ console.log(`Replacing AIStudio2API ${status.version} from an earlier install with ${status.expected}...`);
161
+ }
162
+ console.log(`Starting AIStudio2API service in ${dataDir}...`);
163
+ const local = await ensureStudio({ dataDir, proxy: flags.proxy });
164
+ console.log(`AIStudio2API service is running.`);
165
+ console.log(`API Base URL: ${local.baseURL}`);
166
+ console.log(`Management URL: ${local.origin}`);
167
+ break;
168
+ }
169
+ case 'status': {
170
+ const status = await studioStatus({ dataDir });
171
+ console.log(`Service status: ${status.status}`);
172
+ if (status.status === 'running') {
173
+ console.log(`State: ${status.state || 'RUNNING'}`);
174
+ console.log(`Listen port: ${status.port}`);
175
+ console.log(`Accounts: ready=${status.accounts?.ready ?? 0}, total=${status.accounts?.total ?? 0}`);
176
+ const accounts = await studioAccounts({ dataDir });
177
+ if (accounts.length > 0) {
178
+ console.log(`Enabled accounts:`);
179
+ for (const a of accounts) {
180
+ console.log(` - ${a.label || a.id} (${a.state || 'active'})`);
181
+ }
182
+ }
183
+ } else if (status.status === 'outdated') {
184
+ console.log(`Running version: ${status.version} from an earlier install (this plugin uses ${status.expected})`);
185
+ console.log(`To replace it, run: ${studioCommand('start')}`);
186
+ console.log(`To stop it, run: ${studioCommand('stop')}`);
187
+ } else if (status.status === 'unresponsive') {
188
+ console.log(`Port ${status.port} answers but not properly (${status.reason})`);
189
+ console.log(`If the service is stuck, run: ${studioCommand('stop')}`);
190
+ } else if (status.status === 'foreign') {
191
+ console.log(`Warning: Foreign listener on port ${status.port} (${status.reason})`);
192
+ } else {
193
+ console.log(`Data directory: ${status.dataDir}`);
194
+ }
195
+ break;
196
+ }
197
+ case 'stop': {
198
+ console.log(`Stopping AIStudio2API service in ${dataDir}...`);
199
+ const res = await stopStudio({ dataDir });
200
+ if (!res.stopped) {
201
+ throw new Error(res.reported || 'Failed to stop AI Studio service');
202
+ }
203
+ console.log(`AIStudio2API service stopped.`);
204
+ break;
205
+ }
206
+ case 'login': {
207
+ console.log(`Preparing login...`);
208
+ const local = await ensureStudio({ dataDir, managementOnly: true });
209
+ console.log(`Opening isolated browser window for Google AI Studio login...`);
210
+ const res = await studioAdmin(local, 'POST', '/api/accounts', {}, { timeoutMs: LOGIN_TIMEOUT_MS });
211
+ const account = res?.account || res;
212
+ console.log(`Login completed successfully.`);
213
+ console.log(`Account: ${account.label || account.id || 'new'}`);
214
+ break;
215
+ }
216
+ case 'relogin': {
217
+ const local = await ensureStudio({ dataDir, managementOnly: true });
218
+ const expired = (await studioAccounts({ dataDir })).filter(a => a.state === 'auth_required');
219
+ if (!expired.length) {
220
+ console.log('No account needs to sign in again.');
221
+ return;
222
+ }
223
+ const wanted = flags._[1];
224
+ const chosen = wanted
225
+ ? expired.find(a => a.id === wanted || a.label === wanted)
226
+ : expired.length === 1 ? expired[0] : undefined;
227
+ if (!chosen) {
228
+ const names = expired.map(a => a.label || a.id).join(', ');
229
+ throw new Error(wanted
230
+ ? `${wanted} doesn't need to sign in again; these do: ${names}`
231
+ : `Several accounts need to sign in again; name one: ${studioCommand('relogin <account>')} (${names})`);
232
+ }
233
+ console.log(`Opening isolated browser window to sign ${chosen.label || chosen.id} in again...`);
234
+ const res = await studioAdmin(local, 'POST', `/api/accounts/${encodeURIComponent(chosen.id)}/login`, {}, { timeoutMs: LOGIN_TIMEOUT_MS });
235
+ const account = res?.account || chosen;
236
+ console.log(`Signed in again: ${account.label || account.id} (${account.state || 'unknown'})`);
237
+ break;
238
+ }
239
+ case 'import': {
240
+ const sourceDir = flags._[1];
241
+ if (!sourceDir) {
242
+ throw new Error('Usage: node scripts/studio.mjs import <auth-directory>');
243
+ }
244
+ const resolvedSource = path.resolve(sourceDir);
245
+ if (!fs.existsSync(resolvedSource)) {
246
+ throw new Error(`Source auth directory not found: ${resolvedSource}`);
247
+ }
248
+ const srcLstat = fs.lstatSync(resolvedSource);
249
+ if (srcLstat.isSymbolicLink() || !srcLstat.isDirectory()) {
250
+ throw new Error(`Source auth directory must be a regular directory: ${resolvedSource}`);
251
+ }
252
+
253
+ const status = await studioStatus({ dataDir });
254
+ if (status.status === 'foreign') {
255
+ throw new Error(`Port ${status.port} is occupied by an unknown/foreign listener. Cannot import accounts.`);
256
+ }
257
+ if (status.status !== 'stopped' && status.status !== 'not_installed') {
258
+ throw new Error('Service is currently running. Stop the AI Studio service before importing accounts.');
259
+ }
260
+
261
+ const entries = fs.readdirSync(resolvedSource);
262
+ const accountDirs = [];
263
+ for (const entryName of entries) {
264
+ const fullEntry = path.join(resolvedSource, entryName);
265
+ const lstat = fs.lstatSync(fullEntry);
266
+ if (lstat.isSymbolicLink()) {
267
+ throw new Error(`Symlink rejected in source directory: ${fullEntry}`);
268
+ }
269
+ if (!lstat.isDirectory()) continue;
270
+
271
+ const storageState = path.join(fullEntry, 'storage-state.json');
272
+ if (!fs.existsSync(storageState)) continue;
273
+ const stateLstat = fs.lstatSync(storageState);
274
+ if (stateLstat.isSymbolicLink() || !stateLstat.isFile()) {
275
+ throw new Error(`storage-state.json must be a regular file: ${storageState}`);
276
+ }
277
+
278
+ validateStorageState(storageState);
279
+ accountDirs.push(entryName);
280
+ }
281
+
282
+ if (accountDirs.length === 0) {
283
+ throw new Error(`No account directories with valid storage-state.json found in ${resolvedSource}`);
284
+ }
285
+
286
+ const destAuthDir = path.join(dataDir, 'auth');
287
+ fs.mkdirSync(destAuthDir, { recursive: true, mode: 0o700 });
288
+ fs.chmodSync(destAuthDir, 0o700);
289
+
290
+ // Preflight ALL conflicts across all accounts before writing
291
+ for (const dirName of accountDirs) {
292
+ const srcAccPath = path.join(resolvedSource, dirName);
293
+ const destAccPath = path.join(destAuthDir, dirName);
294
+
295
+ if (fs.existsSync(destAccPath) && fs.lstatSync(destAccPath).isSymbolicLink()) {
296
+ throw new Error(`Destination account directory is a symlink: ${destAccPath}`);
297
+ }
298
+
299
+ const files = fs.readdirSync(srcAccPath);
300
+ for (const f of files) {
301
+ const srcFile = path.join(srcAccPath, f);
302
+ const flstat = fs.lstatSync(srcFile);
303
+ if (flstat.isSymbolicLink() || !flstat.isFile()) {
304
+ throw new Error(`Non-regular file or symlink in account directory rejected: ${srcFile}`);
305
+ }
306
+
307
+ if (fs.existsSync(destAccPath)) {
308
+ const destFile = path.join(destAccPath, f);
309
+ if (fs.existsSync(destFile)) {
310
+ if (fs.lstatSync(destFile).isSymbolicLink() || !fs.lstatSync(destFile).isFile()) {
311
+ throw new Error(`Destination file is not a regular file: ${destFile}`);
312
+ }
313
+ const srcBytes = fs.readFileSync(srcFile);
314
+ const destBytes = fs.readFileSync(destFile);
315
+ if (!srcBytes.equals(destBytes)) {
316
+ throw new Error(`Conflict: ${f} in account ${dirName} already exists with different contents. Overwrite refused.`);
317
+ }
318
+ }
319
+ }
320
+ }
321
+ }
322
+
323
+ // Safe stage-and-copy
324
+ const stageBase = path.join(dataDir, `.import.tmp.${crypto.randomBytes(4).toString('hex')}`);
325
+ fs.mkdirSync(stageBase, { recursive: true, mode: 0o700 });
326
+
327
+ let importedCount = 0;
328
+ try {
329
+ for (const dirName of accountDirs) {
330
+ const srcAccPath = path.join(resolvedSource, dirName);
331
+ const destAccPath = path.join(destAuthDir, dirName);
332
+ const stageAccPath = path.join(stageBase, dirName);
333
+ fs.mkdirSync(stageAccPath, { recursive: true, mode: 0o700 });
334
+ fs.chmodSync(stageAccPath, 0o700);
335
+
336
+ const files = fs.readdirSync(srcAccPath);
337
+ for (const f of files) {
338
+ const srcFile = path.join(srcAccPath, f);
339
+ const stageFile = path.join(stageAccPath, f);
340
+ const srcBytes = fs.readFileSync(srcFile);
341
+ fs.writeFileSync(stageFile, srcBytes, { mode: 0o600 });
342
+ fs.chmodSync(stageFile, 0o600);
343
+ }
344
+
345
+ if (!fs.existsSync(destAccPath)) {
346
+ fs.renameSync(stageAccPath, destAccPath);
347
+ fs.chmodSync(destAccPath, 0o700);
348
+ } else {
349
+ // Already existed with verified identical bytes, ensure modes
350
+ for (const f of files) {
351
+ const destFile = path.join(destAccPath, f);
352
+ if (!fs.existsSync(destFile)) {
353
+ fs.copyFileSync(path.join(stageAccPath, f), destFile);
354
+ }
355
+ fs.chmodSync(destFile, 0o600);
356
+ }
357
+ fs.chmodSync(destAccPath, 0o700);
358
+ }
359
+ importedCount++;
360
+ console.log(`Imported account: ${dirName}`);
361
+ }
362
+ } finally {
363
+ fs.rmSync(stageBase, { recursive: true, force: true });
364
+ }
365
+
366
+ console.log(`Successfully imported ${importedCount} account(s) into ${destAuthDir}.`);
367
+ break;
368
+ }
369
+ default:
370
+ throw new Error(`Unknown command: ${command}`);
371
+ }
372
+ }
373
+
374
+ main().catch(err => {
375
+ console.error(`Error: ${err.message}`);
376
+ process.exitCode = 1;
377
+ });