usegrunt 0.6.3 → 0.6.5
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 +5 -3
- package/dist/local/apinex.js +104 -0
- package/dist/local/data-sharing.js +12 -0
- package/dist/local/fallback-setup.js +52 -0
- package/dist/local/free-api.js +8 -4
- package/dist/local/livekit-setup.js +269 -0
- package/dist/local/livekit.js +219 -0
- package/dist/local/main.js +5 -1
- package/dist/local/mistral-vibe-setup.js +305 -0
- package/dist/local/mistral-vibe.js +306 -0
- package/dist/local/provider-grant.js +49 -0
- package/dist/local/registry.js +14 -3
- package/dist/local/runcrate.js +64 -0
- package/dist/local/setup.js +50 -2
- package/dist/local/wizard.js +3 -2
- package/dist/registry/adapters.json +50 -2
- package/dist/registry.js +3 -3
- package/package.json +1 -1
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { access, lstat, mkdir, mkdtemp, open, rename, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join, resolve } from 'node:path';
|
|
7
|
+
import { FreeApi } from './free-api.js';
|
|
8
|
+
import { verifiedDeepSeekFetch } from './deepseek-response.js';
|
|
9
|
+
import { SourceError } from './source.js';
|
|
10
|
+
export const LIVEKIT_CLI_VERSION = '2.19.4';
|
|
11
|
+
export const LIVEKIT_DEEPSEEK = 'deepseek-ai/deepseek-v4.1-flash';
|
|
12
|
+
export const LIVEKIT_GATEWAY = 'https://agent-gateway.livekit.cloud';
|
|
13
|
+
export const LIVEKIT_RECEIPT_MAX_AGE_MS = 30 * 86400000;
|
|
14
|
+
const configDirectory = () => process.env.MILO_CONFIG_DIR || join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
|
|
15
|
+
export function livekitPaths(directory = configDirectory(), nativeDirectory = join(homedir(), '.livekit')) {
|
|
16
|
+
const home = resolve(directory, 'livekit');
|
|
17
|
+
return { home, binary: join(home, 'bin', process.platform === 'win32' ? 'lk.exe' : 'lk'),
|
|
18
|
+
work: join(home, 'work'), receipt: join(home, 'free-build.json'), nativeHome: nativeDirectory, nativeConfig: join(nativeDirectory, 'cli-config.yaml') };
|
|
19
|
+
}
|
|
20
|
+
// A shell's LiveKit credentials or project must not override the native project
|
|
21
|
+
// chosen in the verified receipt. Keep HOME unchanged for standard CLI auth.
|
|
22
|
+
export function livekitEnvironment() {
|
|
23
|
+
return Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(?:livekit_|lk_)/i.test(key)));
|
|
24
|
+
}
|
|
25
|
+
// The official CLI's normal table includes an API-key column. Project only
|
|
26
|
+
// public identity metadata and never use its secret-bearing JSON output.
|
|
27
|
+
export function parseLiveKitProjects(output) {
|
|
28
|
+
const result = [];
|
|
29
|
+
const clean = output.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '').replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replaceAll('\r', '');
|
|
30
|
+
for (const line of clean.split('\n')) {
|
|
31
|
+
const columns = line.split(/[│┃|]/).map(value => value.trim()).filter(Boolean);
|
|
32
|
+
if (columns.length < 4)
|
|
33
|
+
continue;
|
|
34
|
+
const [label, id, url] = columns;
|
|
35
|
+
if (!label || !id || !url || !/^wss:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.livekit\.cloud\/?$/i.test(url))
|
|
36
|
+
continue;
|
|
37
|
+
const selector = label.replace(/^\*\s*/, '');
|
|
38
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9 _.-]{0,127}$/.test(selector) || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(id))
|
|
39
|
+
continue;
|
|
40
|
+
result.push({ selector, id, url: new URL(url).origin, default: label.startsWith('*') });
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
function validateReceipt(value) {
|
|
45
|
+
const receipt = value;
|
|
46
|
+
const checked = typeof receipt?.checkedAt === 'string' ? Date.parse(receipt.checkedAt) : NaN;
|
|
47
|
+
let url;
|
|
48
|
+
try {
|
|
49
|
+
url = new URL(typeof receipt?.projectURL === 'string' ? receipt.projectURL : '');
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
throw new SourceError('logged_out', 'LiveKit Free Build project verification is missing or expired; rerun usegrunt setup');
|
|
53
|
+
}
|
|
54
|
+
if (!receipt || receipt.version !== 1 || receipt.plan !== 'Build' || receipt.payAsYouGo !== false || receipt.paymentMethodPresent !== false || receipt.purchasedCredits !== 0
|
|
55
|
+
|| typeof receipt.projectSelector !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9 _.-]{0,127}$/.test(receipt.projectSelector)
|
|
56
|
+
|| typeof receipt.projectId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(receipt.projectId)
|
|
57
|
+
|| url.protocol !== 'wss:' || !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.livekit\.cloud$/.test(url.hostname)
|
|
58
|
+
|| url.username || url.password || url.port || url.search || url.hash || url.pathname !== '/'
|
|
59
|
+
|| !Number.isFinite(checked) || checked > Date.now() + 60000 || Date.now() - checked > LIVEKIT_RECEIPT_MAX_AGE_MS) {
|
|
60
|
+
throw new SourceError('logged_out', 'LiveKit Free Build project verification is missing or expired; rerun usegrunt setup');
|
|
61
|
+
}
|
|
62
|
+
return { version: 1, plan: 'Build', payAsYouGo: false, paymentMethodPresent: false, purchasedCredits: 0,
|
|
63
|
+
projectSelector: receipt.projectSelector, projectId: receipt.projectId, projectURL: url.origin, checkedAt: receipt.checkedAt };
|
|
64
|
+
}
|
|
65
|
+
async function privateDirectory(path, create = false) {
|
|
66
|
+
if (create)
|
|
67
|
+
await mkdir(path, { recursive: true, mode: 0o700 });
|
|
68
|
+
const stat = await lstat(path);
|
|
69
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o700) {
|
|
70
|
+
throw new SourceError('logged_out', 'Unsafe LiveKit private directory; rerun usegrunt setup');
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export async function readLiveKitFreeBuildReceipt(directory = configDirectory()) {
|
|
74
|
+
await privateDirectory(livekitPaths(directory).home);
|
|
75
|
+
const file = await open(livekitPaths(directory).receipt, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
76
|
+
try {
|
|
77
|
+
const stat = await file.stat();
|
|
78
|
+
if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || stat.size > 4096)
|
|
79
|
+
throw new SourceError('logged_out', 'Unsafe LiveKit Free Build receipt; rerun usegrunt setup');
|
|
80
|
+
return validateReceipt(JSON.parse(await file.readFile('utf8')));
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
await file.close();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// Setup supplies these public metadata and billing facts only after an actual
|
|
87
|
+
// browser check. The receipt never contains the CLI-owned API key or secret.
|
|
88
|
+
export async function writeLiveKitFreeBuildReceipt(directory, receipt) {
|
|
89
|
+
const value = validateReceipt(receipt), paths = livekitPaths(directory), temporary = join(paths.home, `.free-build-${randomUUID()}.tmp`);
|
|
90
|
+
await privateDirectory(paths.home, true);
|
|
91
|
+
try {
|
|
92
|
+
await writeFile(temporary, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
|
|
93
|
+
await rename(temporary, paths.receipt);
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
await rm(temporary, { force: true });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
// Inspect metadata only. The official CLI remains the only code reading its
|
|
100
|
+
// native API keys and signing its short-lived inference token.
|
|
101
|
+
export async function validateLiveKitNativeConfig(nativeDirectory = join(homedir(), '.livekit')) {
|
|
102
|
+
const home = await lstat(nativeDirectory), auth = await lstat(join(nativeDirectory, 'cli-config.yaml'));
|
|
103
|
+
if (!home.isDirectory() || home.isSymbolicLink() || home.uid !== process.getuid?.() || (home.mode & 0o777) !== 0o700
|
|
104
|
+
|| !auth.isFile() || auth.isSymbolicLink() || auth.uid !== process.getuid?.() || (auth.mode & 0o777) !== 0o600 || auth.size === 0) {
|
|
105
|
+
throw new SourceError('logged_out', 'Unsafe LiveKit native login; rerun usegrunt setup');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async function cliOutput(binary, args, cwd, signal, maxBuffer) {
|
|
109
|
+
signal.throwIfAborted();
|
|
110
|
+
const deadline = AbortSignal.timeout(10000), tokenSignal = AbortSignal.any([signal, deadline]);
|
|
111
|
+
return await new Promise((resolveOutput, reject) => {
|
|
112
|
+
const child = execFile(binary, args, { cwd, env: livekitEnvironment(), encoding: 'utf8', signal: tokenSignal, killSignal: 'SIGKILL', maxBuffer, windowsHide: true }, (error, stdout) => {
|
|
113
|
+
if (error) {
|
|
114
|
+
reject(new SourceError(signal.aborted ? 'cancelled' : deadline.aborted ? 'timeout' : 'logged_out', 'LiveKit native CLI command failed; rerun usegrunt setup'));
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
resolveOutput(stdout);
|
|
118
|
+
});
|
|
119
|
+
child.stdin?.end();
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
async function inferenceToken(binary, receipt, cwd, signal) {
|
|
123
|
+
const config = join(cwd, 'livekit.toml');
|
|
124
|
+
const output = await cliOutput(binary, ['--config', config, 'project', 'list'], cwd, signal, 262144);
|
|
125
|
+
const selected = parseLiveKitProjects(output).filter(project => project.selector === receipt.projectSelector);
|
|
126
|
+
if (selected.length !== 1 || selected[0].id !== receipt.projectId || selected[0].url !== receipt.projectURL) {
|
|
127
|
+
throw new SourceError('logged_out', 'LiveKit native project differs from its verified free Build project; rerun usegrunt setup');
|
|
128
|
+
}
|
|
129
|
+
const token = (await cliOutput(binary, ['--project', receipt.projectSelector, '--config', config, 'token', 'create',
|
|
130
|
+
'--inference', '--token-only', '--valid-for', '10m', '--identity', 'agent'], cwd, signal, 32768)).trim();
|
|
131
|
+
if (!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token) || token.length > 16384) {
|
|
132
|
+
throw new SourceError('logged_out', 'LiveKit CLI returned no inference token; rerun usegrunt setup');
|
|
133
|
+
}
|
|
134
|
+
return token;
|
|
135
|
+
}
|
|
136
|
+
export class LiveKit {
|
|
137
|
+
options;
|
|
138
|
+
id = 'livekit';
|
|
139
|
+
supportsFunctionTools = true;
|
|
140
|
+
shutdown = new AbortController();
|
|
141
|
+
pending = new Set();
|
|
142
|
+
constructor(options = {}) {
|
|
143
|
+
this.options = options;
|
|
144
|
+
}
|
|
145
|
+
async ready() {
|
|
146
|
+
const paths = livekitPaths(this.options.directory, this.options.nativeDirectory);
|
|
147
|
+
try {
|
|
148
|
+
const receipt = await readLiveKitFreeBuildReceipt(this.options.directory);
|
|
149
|
+
await validateLiveKitNativeConfig(paths.nativeHome);
|
|
150
|
+
await access(this.options.binary ?? paths.binary, constants.X_OK);
|
|
151
|
+
return { paths, receipt };
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
if (error instanceof SourceError)
|
|
155
|
+
throw error;
|
|
156
|
+
throw new SourceError('logged_out', 'LiveKit native Free Build login is unavailable; rerun usegrunt setup');
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
async available() { try {
|
|
160
|
+
await this.ready();
|
|
161
|
+
return !this.shutdown.signal.aborted;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return false;
|
|
165
|
+
} }
|
|
166
|
+
async healthCheck() { return this.available(); }
|
|
167
|
+
async complete(request, caller) {
|
|
168
|
+
caller.throwIfAborted();
|
|
169
|
+
const task = this.completeOnce(request, caller);
|
|
170
|
+
this.pending.add(task);
|
|
171
|
+
try {
|
|
172
|
+
return await task;
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
this.pending.delete(task);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async completeOnce(request, caller) {
|
|
179
|
+
const signal = AbortSignal.any([caller, this.shutdown.signal, AbortSignal.timeout(this.options.timeout ?? 180000)]);
|
|
180
|
+
let temporary;
|
|
181
|
+
try {
|
|
182
|
+
signal.throwIfAborted();
|
|
183
|
+
if (request.imageInput)
|
|
184
|
+
throw new SourceError('upstream', 'LiveKit requires text input');
|
|
185
|
+
if (request.tools.some(tool => tool.type !== 'function'))
|
|
186
|
+
throw new SourceError('upstream', 'LiveKit requires function tools');
|
|
187
|
+
const { paths, receipt } = await this.ready();
|
|
188
|
+
signal.throwIfAborted();
|
|
189
|
+
await privateDirectory(paths.work, true);
|
|
190
|
+
temporary = await mkdtemp(join(paths.work, '.token-'));
|
|
191
|
+
await writeFile(join(temporary, 'livekit.toml'), '', { mode: 0o600, flag: 'wx' });
|
|
192
|
+
const token = await inferenceToken(this.options.binary ?? paths.binary, receipt, temporary, signal);
|
|
193
|
+
signal.throwIfAborted();
|
|
194
|
+
const source = new FreeApi('livekit', { fetcher: verifiedDeepSeekFetch(this.options.fetcher), timeout: this.options.timeout ?? 180000,
|
|
195
|
+
loadGrant: async () => ({ base_url: LIVEKIT_GATEWAY, token }) });
|
|
196
|
+
try {
|
|
197
|
+
return await source.complete({ ...request, model: this.id }, signal);
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
await source.close();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
caller.throwIfAborted();
|
|
205
|
+
if (this.shutdown.signal.aborted)
|
|
206
|
+
throw new SourceError('cancelled', 'LiveKit request cancelled during shutdown');
|
|
207
|
+
if (signal.aborted)
|
|
208
|
+
throw new SourceError('timeout', 'LiveKit request timed out');
|
|
209
|
+
if (error instanceof SourceError)
|
|
210
|
+
throw error;
|
|
211
|
+
throw new SourceError('upstream', 'LiveKit request failed; rerun usegrunt setup');
|
|
212
|
+
}
|
|
213
|
+
finally {
|
|
214
|
+
if (temporary)
|
|
215
|
+
await rm(temporary, { recursive: true, force: true });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
async close() { this.shutdown.abort(); await Promise.allSettled([...this.pending]); }
|
|
219
|
+
}
|
package/dist/local/main.js
CHANGED
|
@@ -11,6 +11,10 @@ import { FreeLLMAPI } from './freellmapi.js';
|
|
|
11
11
|
import { Nvidia } from './nvidia.js';
|
|
12
12
|
import { Zro } from './zro.js';
|
|
13
13
|
import { TokenHarbor } from './tokenharbor.js';
|
|
14
|
+
import { Runcrate } from './runcrate.js';
|
|
15
|
+
import { Apinex } from './apinex.js';
|
|
16
|
+
import { MistralVibe } from './mistral-vibe.js';
|
|
17
|
+
import { LiveKit } from './livekit.js';
|
|
14
18
|
import { RegistrySource } from './registry-source.js';
|
|
15
19
|
import { ManagedRouter } from './managed-router.js';
|
|
16
20
|
import { ConsentSource } from './consent-source.js';
|
|
@@ -47,7 +51,7 @@ export function configure(env = process.env, registry = () => bundledRegistry) {
|
|
|
47
51
|
// default while retaining explicit environment and custom-model overrides.
|
|
48
52
|
return adapter?.models ?? (adapter?.model && adapter.model !== 'big-pickle' ? [adapter.model] : DEFAULT_OPENCODE_MODELS);
|
|
49
53
|
};
|
|
50
|
-
const registered = [dots, new Codex(env.MILO_CODEX_MODEL ? { model: env.MILO_CODEX_MODEL } : {}), new ManagedRouter(new FreeLLMAPI(connection), url, configDir(env)), new FreeLLMAPI({ ...connection, id: 'kilo', model: 'kilo-auto/free' }), new Nvidia({ directory: configDir(env) }), new Zro({ directory: configDir(env) }), new TokenHarbor({ directory: configDir(env) }), new OpenCode({ models: opencodeModels, ...(env.MILO_OPENCODE_URL ? { url: env.MILO_OPENCODE_URL } : {}) }), new Freebuff({ toolBridge: env.MILO_FREEBUFF_JSON_BRIDGE === '1' })];
|
|
54
|
+
const registered = [dots, new Codex(env.MILO_CODEX_MODEL ? { model: env.MILO_CODEX_MODEL } : {}), new ManagedRouter(new FreeLLMAPI(connection), url, configDir(env)), new FreeLLMAPI({ ...connection, id: 'kilo', model: 'kilo-auto/free' }), new Nvidia({ directory: configDir(env) }), new Zro({ directory: configDir(env) }), new TokenHarbor({ directory: configDir(env) }), new Runcrate({ directory: configDir(env) }), new Apinex({ directory: configDir(env) }), new MistralVibe({ directory: configDir(env) }), new LiveKit({ directory: configDir(env) }), new OpenCode({ models: opencodeModels, ...(env.MILO_OPENCODE_URL ? { url: env.MILO_OPENCODE_URL } : {}) }), new Freebuff({ toolBridge: env.MILO_FREEBUFF_JSON_BRIDGE === '1' })];
|
|
51
55
|
const ids = env.MILO_SOURCES?.split(',').map(id => id.trim()) ?? registry().adapters.filter(adapter => knownAdapters.has(adapter.id)).map(adapter => adapter.id);
|
|
52
56
|
const routing = ids.every(id => knownAdapters.has(id)) ? { registry } : undefined;
|
|
53
57
|
return new Sources(ids.map(id => {
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { access, chmod, lstat, mkdir, rm, symlink } from 'node:fs/promises';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { executable } from './multiplexer.js';
|
|
6
|
+
import { MISTRAL_VIBE_VERSION, mistralVibeEnvironment, mistralVibePaths, readMistralVibeFreePlanReceipt, writeMistralVibeFreePlanReceipt } from './mistral-vibe.js';
|
|
7
|
+
// Pinned Vibe owns the PKCE exchange, account lookup and credential persistence.
|
|
8
|
+
// Its key never crosses stdout or enters the Node process. Only a pairing URL
|
|
9
|
+
// and an allow-listed success event leave this subprocess.
|
|
10
|
+
const nativeAuthentication = String.raw `
|
|
11
|
+
import asyncio, contextlib, json, logging, os, sys
|
|
12
|
+
os.umask(0o077)
|
|
13
|
+
logging.disable(logging.CRITICAL)
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from vibe.core.config import DEFAULT_PROVIDERS, build_default_orchestrator
|
|
16
|
+
from vibe.core.platform_auth import ApiKeyPlatformCredentialProvider
|
|
17
|
+
from vibe.setup.auth.api_key_persistence import persist_api_key
|
|
18
|
+
from vibe.setup.auth.browser_sign_in import BrowserSignInService
|
|
19
|
+
from vibe.setup.auth.http_browser_sign_in_gateway import HttpBrowserSignInGateway
|
|
20
|
+
from vibe.setup.auth.whoami import HttpAccountGateway
|
|
21
|
+
from vibe.utils.api_keys import resolve_api_key
|
|
22
|
+
from dotenv import load_dotenv
|
|
23
|
+
|
|
24
|
+
def emit(event, **data):
|
|
25
|
+
sys.stdout.write(json.dumps(dict(event=event, **data)) + "\n")
|
|
26
|
+
sys.stdout.flush()
|
|
27
|
+
|
|
28
|
+
async def verify(key):
|
|
29
|
+
account = await HttpAccountGateway().read(
|
|
30
|
+
base_url="https://console.mistral.ai",
|
|
31
|
+
credentials=ApiKeyPlatformCredentialProvider.from_api_key(key), timeout=15)
|
|
32
|
+
if account.plan_name.strip().upper() != "FREE" or account.has_paid_vibe_entitlement:
|
|
33
|
+
raise RuntimeError("free_plan_required")
|
|
34
|
+
|
|
35
|
+
async def main():
|
|
36
|
+
with contextlib.redirect_stdout(sys.stderr):
|
|
37
|
+
if (Path(os.environ["VIBE_HOME"]) / ".env").is_symlink():
|
|
38
|
+
raise RuntimeError("unsafe_native_credential_file")
|
|
39
|
+
if sys.argv[1] == "check":
|
|
40
|
+
load_dotenv(Path(os.environ["VIBE_HOME"]) / ".env", override=False)
|
|
41
|
+
key = resolve_api_key("MISTRAL_API_KEY")
|
|
42
|
+
if not key:
|
|
43
|
+
raise RuntimeError("native_login_required")
|
|
44
|
+
await verify(key)
|
|
45
|
+
else:
|
|
46
|
+
service = BrowserSignInService(HttpBrowserSignInGateway(
|
|
47
|
+
browser_base_url="https://console.mistral.ai",
|
|
48
|
+
api_base_url="https://console.mistral.ai/api"))
|
|
49
|
+
try:
|
|
50
|
+
attempt = await service.start_attempt()
|
|
51
|
+
# stdout is temporarily restored only for this safe event.
|
|
52
|
+
with contextlib.redirect_stdout(sys.__stdout__):
|
|
53
|
+
emit("authorize", url=attempt.sign_in_url)
|
|
54
|
+
key = await service.complete_attempt(attempt)
|
|
55
|
+
await verify(key)
|
|
56
|
+
orchestrator = await build_default_orchestrator()
|
|
57
|
+
provider = next(p for p in DEFAULT_PROVIDERS if p.name == "mistral")
|
|
58
|
+
outcome = persist_api_key(provider, key, orchestrator=orchestrator)
|
|
59
|
+
if outcome != "completed":
|
|
60
|
+
raise RuntimeError("native_persistence_failed")
|
|
61
|
+
finally:
|
|
62
|
+
await service.aclose()
|
|
63
|
+
emit("ready", plan="Free", hasPaidVibeEntitlement=False)
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
asyncio.run(main())
|
|
67
|
+
except BaseException:
|
|
68
|
+
emit("failed")
|
|
69
|
+
sys.exit(1)
|
|
70
|
+
`;
|
|
71
|
+
/** Kill only a subprocess group created by this module, including its children. */
|
|
72
|
+
function stop(child, force = false) {
|
|
73
|
+
if (!child.pid)
|
|
74
|
+
return;
|
|
75
|
+
try {
|
|
76
|
+
if (process.platform === 'win32')
|
|
77
|
+
child.kill(force ? 'SIGKILL' : 'SIGTERM');
|
|
78
|
+
else
|
|
79
|
+
process.kill(-child.pid, force ? 'SIGKILL' : 'SIGTERM');
|
|
80
|
+
}
|
|
81
|
+
catch { /* The owned process group has already exited. */ }
|
|
82
|
+
}
|
|
83
|
+
async function command(binary, args, env, signal, cwd) {
|
|
84
|
+
signal?.throwIfAborted();
|
|
85
|
+
const child = spawn(binary, args, { env, ...(cwd ? { cwd } : {}), stdio: ['ignore', 'pipe', 'ignore'], detached: process.platform !== 'win32' });
|
|
86
|
+
let output = '', exceeded = false;
|
|
87
|
+
child.stdout.on('data', (chunk) => {
|
|
88
|
+
if (output.length + chunk.length > 65536) {
|
|
89
|
+
exceeded = true;
|
|
90
|
+
abort();
|
|
91
|
+
}
|
|
92
|
+
else
|
|
93
|
+
output += chunk.toString();
|
|
94
|
+
});
|
|
95
|
+
let force;
|
|
96
|
+
const abort = () => { stop(child); force ??= setTimeout(() => stop(child, true), 1000); force.unref(); };
|
|
97
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
98
|
+
const deadline = setTimeout(abort, 600000);
|
|
99
|
+
if (signal?.aborted)
|
|
100
|
+
abort();
|
|
101
|
+
try {
|
|
102
|
+
const code = await new Promise((resolve, reject) => {
|
|
103
|
+
child.once('error', () => reject(new Error('Mistral Vibe command could not start')));
|
|
104
|
+
child.once('close', resolve);
|
|
105
|
+
});
|
|
106
|
+
signal?.throwIfAborted();
|
|
107
|
+
if (code !== 0 || exceeded)
|
|
108
|
+
throw new Error('Mistral Vibe command did not complete');
|
|
109
|
+
return output;
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
clearTimeout(deadline);
|
|
113
|
+
if (force)
|
|
114
|
+
clearTimeout(force);
|
|
115
|
+
signal?.removeEventListener('abort', abort);
|
|
116
|
+
stop(child, true);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** Install only under Grunt's private Mistral directory; never modify PATH or a global Python environment. */
|
|
120
|
+
export async function installMistralVibe(directory, signal) {
|
|
121
|
+
const paths = mistralVibePaths(directory), env = mistralVibeEnvironment(directory);
|
|
122
|
+
await mkdir(paths.home, { recursive: true, mode: 0o700 });
|
|
123
|
+
await chmod(paths.home, 0o700);
|
|
124
|
+
await mkdir(paths.work, { recursive: true, mode: 0o700 });
|
|
125
|
+
try {
|
|
126
|
+
const version = await command(paths.binary, ['--version'], env, signal, paths.work);
|
|
127
|
+
await access(paths.python, constants.X_OK);
|
|
128
|
+
if (new RegExp(`(?:^|\\s)v?${MISTRAL_VIBE_VERSION.replaceAll('.', '\\.')}\\s*$`).test(version.trim()))
|
|
129
|
+
return paths;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
signal?.throwIfAborted();
|
|
133
|
+
}
|
|
134
|
+
let uv;
|
|
135
|
+
try {
|
|
136
|
+
uv = await executable('uv');
|
|
137
|
+
}
|
|
138
|
+
catch { /* A managed venv is the fallback. */ }
|
|
139
|
+
if (uv) {
|
|
140
|
+
await command(uv, ['tool', 'install', '--no-config', '--force', `mistral-vibe==${MISTRAL_VIBE_VERSION}`], {
|
|
141
|
+
...env, UV_TOOL_DIR: join(paths.home, 'tools'), UV_TOOL_BIN_DIR: dirname(paths.binary),
|
|
142
|
+
UV_CACHE_DIR: join(paths.home, 'cache'), UV_PYTHON_INSTALL_DIR: join(paths.home, 'python')
|
|
143
|
+
}, signal, paths.work);
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
let python;
|
|
147
|
+
try {
|
|
148
|
+
python = await executable('python3');
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
throw new Error('Mistral Vibe needs uv or Python 3.12+. Install either, then rerun usegrunt setup.');
|
|
152
|
+
}
|
|
153
|
+
const version = await command(python, ['-I', '-c', 'import sys; print("%d.%d" % sys.version_info[:2])'], env, signal, paths.work);
|
|
154
|
+
const [major, minor] = version.trim().split('.').map(Number);
|
|
155
|
+
if (major !== 3 || !minor || minor < 12)
|
|
156
|
+
throw new Error('Mistral Vibe needs uv or Python 3.12+. Install either, then rerun usegrunt setup.');
|
|
157
|
+
const environment = dirname(dirname(paths.python));
|
|
158
|
+
await command(python, ['-I', '-m', 'venv', environment], env, signal, paths.work);
|
|
159
|
+
await command(paths.python, ['-I', '-m', 'pip', '--isolated', '--disable-pip-version-check', 'install', `mistral-vibe==${MISTRAL_VIBE_VERSION}`], env, signal, paths.work);
|
|
160
|
+
await mkdir(dirname(paths.binary), { recursive: true, mode: 0o700 });
|
|
161
|
+
try {
|
|
162
|
+
await symlink(join(dirname(paths.python), 'vibe'), paths.binary);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
if (error.code !== 'EEXIST')
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const version = await command(paths.binary, ['--version'], env, signal, paths.work);
|
|
170
|
+
if (!new RegExp(`(?:^|\\s)v?${MISTRAL_VIBE_VERSION.replaceAll('.', '\\.')}\\s*$`).test(version.trim()))
|
|
171
|
+
throw new Error('Mistral Vibe installation did not provide the pinned CLI version');
|
|
172
|
+
await access(paths.python, constants.X_OK);
|
|
173
|
+
return paths;
|
|
174
|
+
}
|
|
175
|
+
async function awaitBrowser(promise, signal) {
|
|
176
|
+
signal?.throwIfAborted();
|
|
177
|
+
if (!signal)
|
|
178
|
+
return await promise;
|
|
179
|
+
let abort = () => { };
|
|
180
|
+
const cancelled = new Promise((_, reject) => { abort = () => reject(signal.reason); signal.addEventListener('abort', abort, { once: true }); });
|
|
181
|
+
try {
|
|
182
|
+
signal.throwIfAborted();
|
|
183
|
+
return await Promise.race([promise, cancelled]);
|
|
184
|
+
}
|
|
185
|
+
finally {
|
|
186
|
+
signal.removeEventListener('abort', abort);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
async function nativeLogin(options, mode) {
|
|
190
|
+
const paths = mistralVibePaths(options.directory), env = mistralVibeEnvironment(options.directory);
|
|
191
|
+
const lifetime = new AbortController();
|
|
192
|
+
const signal = options.signal ? AbortSignal.any([options.signal, lifetime.signal]) : lifetime.signal;
|
|
193
|
+
signal.throwIfAborted();
|
|
194
|
+
const child = spawn(paths.python, ['-I', '-c', nativeAuthentication, mode], {
|
|
195
|
+
cwd: paths.work, env, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'ignore']
|
|
196
|
+
});
|
|
197
|
+
let buffer = '', ready = false, paired = false, failure;
|
|
198
|
+
let pairing;
|
|
199
|
+
let force;
|
|
200
|
+
const abort = () => { stop(child); force ??= setTimeout(() => stop(child, true), 1000); force.unref(); };
|
|
201
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
202
|
+
const deadline = setTimeout(() => lifetime.abort(new Error('Mistral Vibe sign-in timed out; rerun usegrunt setup to resume')), 600000);
|
|
203
|
+
const protocolFailure = () => { failure = new Error('Mistral Vibe native sign-in did not complete'); abort(); };
|
|
204
|
+
child.stdout.on('data', (chunk) => {
|
|
205
|
+
buffer += chunk.toString();
|
|
206
|
+
if (buffer.length > 32768) {
|
|
207
|
+
protocolFailure();
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
let newline;
|
|
211
|
+
while ((newline = buffer.indexOf('\n')) >= 0) {
|
|
212
|
+
const line = buffer.slice(0, newline);
|
|
213
|
+
buffer = buffer.slice(newline + 1);
|
|
214
|
+
let event;
|
|
215
|
+
try {
|
|
216
|
+
event = JSON.parse(line);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
protocolFailure();
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (event.event === 'authorize' && mode === 'login' && !paired) {
|
|
223
|
+
let url;
|
|
224
|
+
try {
|
|
225
|
+
url = new URL(String(event.url));
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
protocolFailure();
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (url.origin !== 'https://console.mistral.ai' || url.pathname !== '/codestral/cli/authenticate' || url.username || url.password || url.hash) {
|
|
232
|
+
protocolFailure();
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
paired = true;
|
|
236
|
+
pairing = options.squire.signup('mistral-vibe', url.href, 'Finish the Mistral Vibe CLI browser pairing started by this setup process, using the same Free account just verified. Authorize only this pairing. Do not create a general API key or enable API or Vibe Code pay-as-you-go. No paid plan, card, credits, account switching or extra account. Stop if the account is paid or signup is refused. Report human verification for browser handoff; do not bypass it. Never reveal, copy or store the native CLI key: the CLI owns its credential exchange.');
|
|
237
|
+
void pairing.catch(() => { failure = new Error('Mistral Vibe browser pairing did not complete; rerun usegrunt setup to resume'); abort(); });
|
|
238
|
+
}
|
|
239
|
+
else if (event.event === 'ready' && event.plan === 'Free' && event.hasPaidVibeEntitlement === false)
|
|
240
|
+
ready = true;
|
|
241
|
+
else {
|
|
242
|
+
protocolFailure();
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
if (signal.aborted)
|
|
248
|
+
abort();
|
|
249
|
+
try {
|
|
250
|
+
const code = await new Promise((resolve, reject) => {
|
|
251
|
+
child.once('error', () => reject(new Error('Mistral Vibe native sign-in could not start')));
|
|
252
|
+
child.once('close', resolve);
|
|
253
|
+
});
|
|
254
|
+
signal.throwIfAborted();
|
|
255
|
+
if (failure || code !== 0 || !ready || (mode === 'login' && !paired))
|
|
256
|
+
throw failure ?? new Error('Mistral Vibe native Free account could not be verified');
|
|
257
|
+
try {
|
|
258
|
+
if (pairing)
|
|
259
|
+
await awaitBrowser(pairing, signal);
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
signal.throwIfAborted();
|
|
263
|
+
throw failure ?? new Error('Mistral Vibe browser pairing did not complete; rerun usegrunt setup to resume');
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
finally {
|
|
267
|
+
clearTimeout(deadline);
|
|
268
|
+
if (force)
|
|
269
|
+
clearTimeout(force);
|
|
270
|
+
signal.removeEventListener('abort', abort);
|
|
271
|
+
stop(child, true);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/** Verify a card-free Free account in Squire, then let the native CLI own login. */
|
|
275
|
+
export async function setupMistralVibe(options) {
|
|
276
|
+
const paths = await installMistralVibe(options.directory, options.signal);
|
|
277
|
+
try {
|
|
278
|
+
await readMistralVibeFreePlanReceipt(options.directory);
|
|
279
|
+
const credential = await lstat(join(paths.home, '.env'));
|
|
280
|
+
if (!credential.isFile() || (credential.mode & 0o077) !== 0)
|
|
281
|
+
throw new Error('Native login needs repair');
|
|
282
|
+
await nativeLogin(options, 'check');
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
// A failed native identity check revokes the saved eligibility immediately.
|
|
287
|
+
// A later browser refusal must not leave an old Free receipt usable.
|
|
288
|
+
await rm(paths.receipt, { force: true });
|
|
289
|
+
options.signal?.throwIfAborted();
|
|
290
|
+
}
|
|
291
|
+
options.notify?.('Mistral Vibe: verifying the Free account and native CLI login');
|
|
292
|
+
try {
|
|
293
|
+
await awaitBrowser(options.squire.signup('mistral-vibe', 'https://admin.mistral.ai/subscription', "Use the user's existing Mistral account or normal Google sign-up for a Free account. Before finishing, verify Current plan Free at https://admin.mistral.ai/subscription; both API pay-as-you-go and Vibe Code pay-as-you-go must be off (the page offers Enable). Verify https://admin.mistral.ai/organization/billing has no payment method, zero purchased credits and automatic recharge disabled. The Free Vibe Code allowance renews monthly; it is not a purchased credit balance. If an existing account is paid, has a card, purchased credits or enabled pay-as-you-go, stop and report it without changing anything. Do not downgrade, remove a card, switch account, create another identity, subscribe, top up or enable billing. Optional marketing remains off. Required unrelated consent, refusal, CAPTCHA, phone, email or passkey verification needs human handoff; do not bypass it. Do not create or reveal a general API key. Finish only after these Free account checks succeed; a separate native CLI pairing will follow."), options.signal);
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
options.signal?.throwIfAborted();
|
|
297
|
+
throw new Error('Mistral Vibe Free account verification did not complete; rerun usegrunt setup to resume');
|
|
298
|
+
}
|
|
299
|
+
await nativeLogin(options, 'login');
|
|
300
|
+
await writeMistralVibeFreePlanReceipt(options.directory, {
|
|
301
|
+
version: 1, plan: 'Free', payAsYouGo: false, paymentMethodPresent: false,
|
|
302
|
+
purchasedCredits: 0, checkedAt: new Date().toISOString()
|
|
303
|
+
});
|
|
304
|
+
options.notify?.('Mistral Vibe: Free native CLI login connected; GLM-5.3 Flash is ready');
|
|
305
|
+
}
|