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.
@@ -0,0 +1,306 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { constants } from 'node:fs';
3
+ import { access, chmod, lstat, mkdir, mkdtemp, open, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { SourceError } from './source.js';
8
+ import { FreebuffTools } from './freebuff-tools.js';
9
+ export const MISTRAL_VIBE_VERSION = '3.1.2';
10
+ export const MISTRAL_VIBE_MODEL = 'zai-glm-5-3-flash';
11
+ export const MISTRAL_VIBE_WIRE_MODEL = 'zai-glm-5-3-flash-vibe-free';
12
+ export const MISTRAL_VIBE_RECEIPT_MAX_AGE_MS = 30 * 86400000;
13
+ const configDirectory = () => process.env.MILO_CONFIG_DIR || join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
14
+ export function mistralVibePaths(directory = configDirectory()) {
15
+ const home = resolve(directory, 'mistral-vibe');
16
+ return { home, binary: join(home, 'bin', process.platform === 'win32' ? 'vibe.exe' : 'vibe'), python: join(home, 'tools', 'mistral-vibe', process.platform === 'win32' ? 'Scripts/python.exe' : 'bin/python'), work: join(home, 'work'), receipt: join(home, 'free-plan.json') };
17
+ }
18
+ // Native authentication remains CLI-owned. A shell's general Mistral API key
19
+ // must never silently replace this private Free Vibe login.
20
+ export function mistralVibeEnvironment(directory = configDirectory()) {
21
+ const env = { ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^vibe_/i.test(key) && !/^mistral_api_key$/i.test(key))), VIBE_HOME: mistralVibePaths(directory).home, VIBE_TEST_DISABLE_KEYRING: '1', PYTHON_KEYRING_BACKEND: 'keyring.backends.fail.Keyring' };
22
+ delete env.MISTRAL_API_KEY;
23
+ return env;
24
+ }
25
+ function validateReceipt(value) {
26
+ const receipt = value;
27
+ const checked = typeof receipt?.checkedAt === 'string' ? Date.parse(receipt.checkedAt) : NaN;
28
+ if (!receipt || receipt.version !== 1 || receipt.plan !== 'Free' || receipt.payAsYouGo !== false || receipt.paymentMethodPresent !== false || receipt.purchasedCredits !== 0
29
+ || !Number.isFinite(checked) || checked > Date.now() + 60000 || Date.now() - checked > MISTRAL_VIBE_RECEIPT_MAX_AGE_MS) {
30
+ throw new SourceError('logged_out', 'Mistral Vibe Free plan verification is missing or expired; rerun usegrunt setup');
31
+ }
32
+ return receipt;
33
+ }
34
+ // This receipt records the browser's Free/billing check, not a new entitlement.
35
+ // Recheck it at least every 30 days; never enable overage billing during setup.
36
+ export async function readMistralVibeFreePlanReceipt(directory = configDirectory()) {
37
+ const file = await open(mistralVibePaths(directory).receipt, constants.O_RDONLY | constants.O_NOFOLLOW);
38
+ try {
39
+ const st = await file.stat();
40
+ if (!st.isFile() || st.uid !== process.getuid?.() || (st.mode & 0o777) !== 0o600 || st.size > 4096)
41
+ throw new SourceError('logged_out', 'Unsafe Mistral Vibe plan receipt; rerun usegrunt setup');
42
+ return validateReceipt(JSON.parse(await file.readFile('utf8')));
43
+ }
44
+ finally {
45
+ await file.close();
46
+ }
47
+ }
48
+ export async function writeMistralVibeFreePlanReceipt(directory, receipt) {
49
+ const value = validateReceipt(receipt), paths = mistralVibePaths(directory), temporary = join(paths.home, `.free-plan-${randomUUID()}.tmp`);
50
+ await mkdir(paths.home, { recursive: true, mode: 0o700 });
51
+ try {
52
+ await writeFile(temporary, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
53
+ await rename(temporary, paths.receipt);
54
+ }
55
+ finally {
56
+ await rm(temporary, { force: true });
57
+ }
58
+ }
59
+ // Each invocation has a private process group, so cancellation reaches its
60
+ // Python app server without touching other CLI sessions or browser processes.
61
+ export async function runMistralVibeProcess(binary, args, options) {
62
+ options.signal.throwIfAborted();
63
+ return await new Promise((resolveResult, reject) => {
64
+ const child = spawn(binary, args, { cwd: options.cwd, env: options.env, stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32' });
65
+ let stdout = '', bytes = 0, oversized = false, failed = false;
66
+ let force;
67
+ const kill = (signal) => {
68
+ try {
69
+ if (process.platform !== 'win32' && child.pid)
70
+ process.kill(-child.pid, signal);
71
+ else
72
+ child.kill(signal);
73
+ }
74
+ catch { /* Our process group has already stopped. */ }
75
+ };
76
+ const abort = () => { kill('SIGTERM'); force ??= setTimeout(() => kill('SIGKILL'), 1000); };
77
+ options.signal.addEventListener('abort', abort, { once: true });
78
+ if (options.signal.aborted)
79
+ abort();
80
+ child.stdout.on('data', (chunk) => {
81
+ bytes += chunk.length;
82
+ if (bytes > (options.maxOutputBytes ?? 16 * 1024 * 1024)) {
83
+ oversized = true;
84
+ stdout = '';
85
+ kill('SIGKILL');
86
+ return;
87
+ }
88
+ const text = chunk.toString();
89
+ stdout += text;
90
+ options.onStdout?.(text);
91
+ });
92
+ // Never relay native stderr: authentication URLs and provider error payloads
93
+ // can contain credentials. The structured export gives sanitized outcomes.
94
+ child.stderr.resume();
95
+ child.once('error', () => { failed = true; });
96
+ child.once('close', code => {
97
+ options.signal.removeEventListener('abort', abort);
98
+ if (force)
99
+ clearTimeout(force);
100
+ // A wrapper may exit before its child. Reap only the group we launched.
101
+ if (options.signal.aborted)
102
+ kill('SIGKILL');
103
+ if (options.signal.aborted)
104
+ reject(options.signal.reason);
105
+ else if (failed)
106
+ reject(new SourceError('not_installed', 'Mistral Vibe CLI could not start; rerun usegrunt setup'));
107
+ else if (oversized)
108
+ reject(new SourceError('upstream', 'Mistral Vibe output exceeded the supported size'));
109
+ else
110
+ resolveResult({ stdout, code });
111
+ });
112
+ });
113
+ }
114
+ const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
115
+ function nativeFailure(value) {
116
+ const error = object(value.error), hint = `${typeof error.code === 'string' ? error.code : ''} ${typeof error.message === 'string' ? error.message : ''}`;
117
+ const code = /quota|rate.?limit|budget|credits?.*(?:exhaust|insufficient)|payment.required|429|402/i.test(hint) ? 'quota'
118
+ : /unauthori|authenticat|sign.?in|logged.?out|invalid.?key|401/i.test(hint) ? 'logged_out'
119
+ : value.outcome === 'deadline' ? 'timeout' : value.outcome === 'refusal' ? 'refused' : 'upstream';
120
+ return new SourceError(code, `Mistral Vibe request failed (${code}); check the native Free plan or rerun usegrunt setup`);
121
+ }
122
+ export function parseMistralVibeCompletion(stdout, exported) {
123
+ const run = object(exported), config = object(run.config), models = object(config.models), selected = object(models[MISTRAL_VIBE_MODEL]);
124
+ const providers = Array.isArray(config.providers) ? config.providers.map(object) : [];
125
+ const provider = providers.find(row => row.name === 'mistral');
126
+ if (config.active_model !== MISTRAL_VIBE_MODEL || selected.name !== MISTRAL_VIBE_WIRE_MODEL || selected.provider !== 'mistral'
127
+ || selected.max_context_length !== 262144 || selected.auto_compact_threshold !== 202144
128
+ || object(config.compaction_model).name !== MISTRAL_VIBE_WIRE_MODEL || object(config.compaction_model).provider !== 'mistral'
129
+ || provider?.api_base !== 'https://api.mistral.ai/v1')
130
+ throw new SourceError('upstream', 'Mistral Vibe did not use the vetted Free GLM model');
131
+ if (run.outcome !== 'finished' || run.exit_code !== 0 || run.error)
132
+ throw nativeFailure(run);
133
+ let history;
134
+ try {
135
+ history = JSON.parse(stdout);
136
+ }
137
+ catch {
138
+ throw new SourceError('upstream', 'Mistral Vibe returned invalid completion JSON');
139
+ }
140
+ if (!Array.isArray(history))
141
+ throw new SourceError('upstream', 'Mistral Vibe returned invalid completion history');
142
+ const entries = history.map(object);
143
+ if (entries.some(entry => entry.type === 'effect' || (Array.isArray(entry.content) && entry.content.some(part => /tool_call|tool_use/.test(String(object(part).type)))))) {
144
+ throw new SourceError('refused', 'Mistral Vibe attempted native tools during a text-only completion');
145
+ }
146
+ const answer = [...entries].reverse().find(entry => entry.type === 'message' && entry.role === 'assistant' && entry.generationStatus === 'completed'
147
+ && object(entry.outcome).type !== 'discarded' && Array.isArray(entry.content));
148
+ const text = Array.isArray(answer?.content) ? answer.content.map(object).filter(part => part.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n\n') : '';
149
+ const usage = object(run.usage);
150
+ if (!text.trim() || !Number.isSafeInteger(usage.input_tokens) || Number(usage.input_tokens) < 0 || !Number.isSafeInteger(usage.output_tokens) || Number(usage.output_tokens) < 0) {
151
+ throw new SourceError('upstream', 'Mistral Vibe returned no complete answer or valid native usage');
152
+ }
153
+ return { text, inputTokens: usage.input_tokens, outputTokens: usage.output_tokens };
154
+ }
155
+ export class MistralVibe {
156
+ options;
157
+ id = 'mistral-vibe';
158
+ supportsFunctionTools = true;
159
+ shutdown = new AbortController();
160
+ pending = new Set();
161
+ constructor(options = {}) {
162
+ this.options = options;
163
+ }
164
+ async ready() {
165
+ const paths = mistralVibePaths(this.options.directory);
166
+ try {
167
+ await readMistralVibeFreePlanReceipt(this.options.directory);
168
+ const home = await lstat(paths.home), auth = await lstat(join(paths.home, '.env'));
169
+ if (!home.isDirectory() || home.isSymbolicLink() || home.uid !== process.getuid?.() || (home.mode & 0o077) !== 0
170
+ || !auth.isFile() || auth.isSymbolicLink() || auth.uid !== process.getuid?.() || (auth.mode & 0o777) !== 0o600 || auth.size === 0)
171
+ throw new Error('Unsafe native auth');
172
+ await access(this.options.binary ?? paths.binary, constants.X_OK);
173
+ }
174
+ catch (error) {
175
+ if (error instanceof SourceError)
176
+ throw error;
177
+ throw new SourceError('logged_out', 'Mistral Vibe Free login is unavailable; rerun usegrunt setup');
178
+ }
179
+ return paths;
180
+ }
181
+ async available() { try {
182
+ await this.ready();
183
+ return !this.shutdown.signal.aborted;
184
+ }
185
+ catch {
186
+ return false;
187
+ } }
188
+ async healthCheck() { return this.available(); }
189
+ async complete(request, caller) {
190
+ caller.throwIfAborted();
191
+ if (request.imageInput)
192
+ throw new SourceError('refused', 'Mistral Vibe does not support image inputs through this route');
193
+ const task = this.completeBridged(request, caller);
194
+ this.pending.add(task);
195
+ try {
196
+ return await task;
197
+ }
198
+ catch (error) {
199
+ caller.throwIfAborted();
200
+ if (this.shutdown.signal.aborted)
201
+ throw new SourceError('cancelled', 'Mistral Vibe request cancelled during shutdown');
202
+ if (error instanceof SourceError)
203
+ throw error;
204
+ if (error instanceof Error && error.name === 'TimeoutError')
205
+ throw new SourceError('timeout', 'Mistral Vibe request timed out');
206
+ throw new SourceError('upstream', 'Mistral Vibe request failed');
207
+ }
208
+ finally {
209
+ this.pending.delete(task);
210
+ }
211
+ }
212
+ async completeBridged(request, caller) {
213
+ const needsBridge = request.tools.length > 0 || request.messages.some(message => message.role === 'tool' || message.tool_calls?.length);
214
+ if (!needsBridge)
215
+ return await this.completeText(request, caller);
216
+ let bridge;
217
+ try {
218
+ bridge = new FreebuffTools(request);
219
+ }
220
+ catch {
221
+ throw new SourceError('refused', 'Mistral Vibe rejected unsupported tool definitions or an invalid tool conversation');
222
+ }
223
+ const signal = AbortSignal.any([caller, this.shutdown.signal, AbortSignal.timeout(this.options.timeout ?? 180000)]);
224
+ let inputTokens = 0, outputTokens = 0;
225
+ for (let attempt = 0; attempt < 2; attempt++) {
226
+ const handoffPrompt = bridge.prompt(attempt > 0).replace('native Freebuff tools', 'native Mistral Vibe tools');
227
+ const result = await this.completeText({ ...request, handoffPrompt }, signal);
228
+ inputTokens += result.inputTokens ?? 0;
229
+ outputTokens += result.outputTokens ?? 0;
230
+ try {
231
+ return { ...bridge.parse(result.text), inputTokens, outputTokens };
232
+ }
233
+ catch {
234
+ if (attempt === 1)
235
+ throw new SourceError('upstream', 'Mistral Vibe tool response failed validation after one repair attempt');
236
+ }
237
+ }
238
+ throw new SourceError('upstream', 'Mistral Vibe tool protocol failed');
239
+ }
240
+ async completeText(request, caller) {
241
+ const signal = AbortSignal.any([caller, this.shutdown.signal, AbortSignal.timeout(this.options.timeout ?? 180000)]);
242
+ let temporary;
243
+ try {
244
+ signal.throwIfAborted();
245
+ const paths = await this.ready();
246
+ signal.throwIfAborted();
247
+ await mkdir(paths.work, { recursive: true, mode: 0o700 });
248
+ temporary = await mkdtemp(join(paths.home, '.request-'));
249
+ await chmod(temporary, 0o700);
250
+ const prompt = request.handoffPrompt ?? (request.messages.length === 1 && request.messages[0]?.role === 'user' ? request.messages[0].content
251
+ : `Continue this conversation and answer the latest user request. The following JSON is the complete conversation, including its system and developer instructions:\n${JSON.stringify(request.messages)}`);
252
+ if (!prompt.trim())
253
+ throw new SourceError('upstream', 'No text in the Mistral Vibe request');
254
+ const promptFile = join(temporary, 'prompt.txt'), output = join(temporary, 'export');
255
+ await writeFile(promptFile, prompt, { mode: 0o600, flag: 'wx' });
256
+ const cap = Math.min(4096, Math.max(1, Number.isFinite(request.maxTokens) ? Math.floor(request.maxTokens) : 4096));
257
+ const env = { ...mistralVibeEnvironment(this.options.directory),
258
+ VIBE_ACTIVE_MODEL: MISTRAL_VIBE_MODEL, VIBE_ALLOWED_MODELS: JSON.stringify([MISTRAL_VIBE_WIRE_MODEL]),
259
+ // These are the authenticated native Free preset's actual limits. Pin
260
+ // the wire ID before inference; Vibe's non-admin allowlist fails open.
261
+ VIBE_MODELS: JSON.stringify([{ name: MISTRAL_VIBE_WIRE_MODEL, alias: MISTRAL_VIBE_MODEL, provider: 'mistral', max_context_length: 262144, auto_compact_threshold: 202144, thinking: 'high', thinking_levels: ['low', 'high', 'max'] }]),
262
+ VIBE_COMPACTION_MODEL: JSON.stringify({ name: MISTRAL_VIBE_WIRE_MODEL, alias: MISTRAL_VIBE_MODEL, provider: 'mistral', max_context_length: 262144, auto_compact_threshold: 202144, thinking: 'high', thinking_levels: ['low', 'high', 'max'] }),
263
+ VIBE_UTILITY_MODELS: '{"title":"active","smart_approve":"active"}',
264
+ VIBE_PROVIDERS: JSON.stringify([{ name: 'mistral', api_base: 'https://api.mistral.ai/v1', api_key_env_var: 'MISTRAL_API_KEY', backend: 'mistral', api_style: 'openai' }]),
265
+ VIBE_AGENT_MAX_OUTPUT_TOKENS: String(cap), VIBE_OUTPUT_LIMIT_RETRIES: '0', VIBE_ENABLE_UPDATE_CHECKS: 'false',
266
+ VIBE_ENABLE_MCP: 'false', VIBE_ENABLE_CONNECTORS: 'false', VIBE_ENABLE_SUBAGENTS: 'false', VIBE_DISABLED_TOOLS: '["*"]',
267
+ VIBE_SESSION_LOGGING: '{"enabled":false,"generate_titles":false}' };
268
+ const result = await runMistralVibeProcess(this.options.binary ?? paths.binary, ['--model', MISTRAL_VIBE_MODEL, '--disabled-tools', '*', '--prompt-file', promptFile,
269
+ '--output', 'json', '--output-dir', output, '--max-turns', '1', '--time-limit', String(Math.max(1, Math.ceil((this.options.timeout ?? 180000) / 1000)))], { cwd: paths.work, env, signal });
270
+ signal.throwIfAborted();
271
+ let exported;
272
+ try {
273
+ const file = await open(join(output, 'export.json'), constants.O_RDONLY | constants.O_NOFOLLOW);
274
+ try {
275
+ if ((await file.stat()).size > 1024 * 1024)
276
+ throw new Error('Oversized export');
277
+ exported = JSON.parse(await file.readFile('utf8'));
278
+ }
279
+ finally {
280
+ await file.close();
281
+ }
282
+ }
283
+ catch {
284
+ throw new SourceError('upstream', 'Mistral Vibe produced no readable completion export');
285
+ }
286
+ if (result.code !== 0)
287
+ throw nativeFailure(object(exported));
288
+ return parseMistralVibeCompletion(result.stdout, exported);
289
+ }
290
+ catch (error) {
291
+ caller.throwIfAborted();
292
+ if (this.shutdown.signal.aborted)
293
+ throw new SourceError('cancelled', 'Mistral Vibe request cancelled during shutdown');
294
+ if (signal.aborted)
295
+ throw new SourceError('timeout', 'Mistral Vibe request timed out');
296
+ if (error instanceof SourceError)
297
+ throw error;
298
+ throw new SourceError('upstream', 'Mistral Vibe request failed; rerun usegrunt setup');
299
+ }
300
+ finally {
301
+ if (temporary)
302
+ await rm(temporary, { recursive: true, force: true });
303
+ }
304
+ }
305
+ async close() { this.shutdown.abort(); await Promise.allSettled([...this.pending]); }
306
+ }
@@ -0,0 +1,49 @@
1
+ import { constants } from 'node:fs';
2
+ import { mkdir, open, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ export const providerGrantDirectory = () => process.env.MILO_CONFIG_DIR || join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
7
+ function name(provider) {
8
+ if (provider !== 'runcrate' && provider !== 'apinex')
9
+ throw new Error('Invalid private provider');
10
+ return provider;
11
+ }
12
+ export function validateProviderGrant(value) {
13
+ const grant = value;
14
+ if (!grant || typeof grant.base_url !== 'string' || typeof grant.token !== 'string' || !grant.token.trim())
15
+ throw new Error('Invalid private provider grant');
16
+ let url;
17
+ try {
18
+ url = new URL(grant.base_url);
19
+ }
20
+ catch {
21
+ throw new Error('Invalid private provider endpoint');
22
+ }
23
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash)
24
+ throw new Error('Invalid private provider endpoint');
25
+ return { base_url: grant.base_url.replace(/\/$/, ''), token: grant.token };
26
+ }
27
+ export async function readPrivateProviderGrant(provider, location) {
28
+ const file = await open(join(location, `${name(provider)}.json`), constants.O_RDONLY | constants.O_NOFOLLOW);
29
+ try {
30
+ const stat = await file.stat();
31
+ if (!stat.isFile() || (stat.mode & 0o777) !== 0o600 || stat.uid !== process.getuid?.())
32
+ throw new Error('Unsafe private provider grant file');
33
+ return JSON.parse(await file.readFile('utf8'));
34
+ }
35
+ finally {
36
+ await file.close();
37
+ }
38
+ }
39
+ export async function writePrivateProviderGrant(provider, value, location) {
40
+ const temporary = join(location, `${name(provider)}.${randomUUID()}.tmp`);
41
+ await mkdir(location, { recursive: true, mode: 0o700 });
42
+ try {
43
+ await writeFile(temporary, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
44
+ await rename(temporary, join(location, `${provider}.json`));
45
+ }
46
+ finally {
47
+ await rm(temporary, { force: true });
48
+ }
49
+ }
@@ -94,10 +94,21 @@ export class RegistrySync {
94
94
  await this.load();
95
95
  if (this.controller.signal.aborted)
96
96
  return;
97
- this.timer = setInterval(() => { void this.sync(); }, REGISTRY_INTERVAL);
98
- this.timer.unref();
97
+ // Daily free quotas/check-ins reset at UTC midnight. Recheck then rather
98
+ // than leaving an expired APInex receipt idle until the install-time hour.
99
+ const schedule = () => {
100
+ if (this.controller.signal.aborted)
101
+ return;
102
+ const now = Date.now();
103
+ const midnight = Math.floor(now / REGISTRY_INTERVAL) * REGISTRY_INTERVAL + REGISTRY_INTERVAL;
104
+ this.timer = setTimeout(() => {
105
+ void this.sync().catch(() => this.options.notify?.('Background setup incomplete; run usegrunt setup to resume')).finally(schedule);
106
+ }, midnight - now);
107
+ this.timer.unref();
108
+ };
109
+ schedule();
99
110
  await this.sync();
100
111
  }
101
112
  async close() { if (this.timer)
102
- clearInterval(this.timer); this.controller.abort(); await this.pending; }
113
+ clearTimeout(this.timer); this.controller.abort(); await this.pending; }
103
114
  }
@@ -0,0 +1,64 @@
1
+ import { FreeApi } from './free-api.js';
2
+ import { verifiedDeepSeekFetch } from './deepseek-response.js';
3
+ import { readDataSharingConsent } from './data-sharing.js';
4
+ import { providerGrantDirectory, readPrivateProviderGrant, validateProviderGrant, writePrivateProviderGrant } from './provider-grant.js';
5
+ import { SourceError } from './source.js';
6
+ export const RUNCRATE_DEEPSEEK = 'deepseek-ai/DeepSeek-V4.1-Flash';
7
+ function validate(value) {
8
+ const grant = value;
9
+ const access = validateProviderGrant(value);
10
+ if (grant?.free_account_verified !== true || grant.key_topups_disabled !== true || typeof grant.verified_at !== 'string'
11
+ || !Number.isFinite(Date.parse(grant.verified_at)))
12
+ throw new Error('Runcrate free account verification is missing');
13
+ return { ...access, free_account_verified: true, key_topups_disabled: true, verified_at: grant.verified_at };
14
+ }
15
+ export async function readRuncrateGrant(location = providerGrantDirectory()) {
16
+ return validate(await readPrivateProviderGrant('runcrate', location));
17
+ }
18
+ // Setup calls this only after confirming free access and disabling key top-ups.
19
+ // Like Zro's setup receipt, this does not freeze future account changes at Runcrate.
20
+ export async function writeRuncrateGrant(grant, location = providerGrantDirectory()) {
21
+ const value = validate({ ...grant, free_account_verified: true, key_topups_disabled: true, verified_at: new Date().toISOString() });
22
+ await writePrivateProviderGrant('runcrate', value, location);
23
+ }
24
+ export class Runcrate {
25
+ options;
26
+ id = 'runcrate';
27
+ supportsFunctionTools = true;
28
+ source;
29
+ location;
30
+ constructor(options = {}) {
31
+ this.options = options;
32
+ this.location = options.directory ?? providerGrantDirectory();
33
+ this.source = new FreeApi('runcrate', { ...options, fetcher: verifiedDeepSeekFetch(options.fetcher), loadGrant: () => this.grant() });
34
+ }
35
+ approved = async () => (await readDataSharingConsent(this.location, [this.id])).includes(this.id);
36
+ grant() { return (this.options.loadGrant?.() ?? readRuncrateGrant(this.location)).then(validate); }
37
+ async available() {
38
+ if (!await this.approved())
39
+ return false;
40
+ try {
41
+ const grant = await this.grant();
42
+ const response = await (this.options.fetcher ?? fetch)(`${grant.base_url}/v1/models`, {
43
+ headers: { Authorization: `Bearer ${grant.token}` }, redirect: 'error', signal: AbortSignal.timeout(5000)
44
+ });
45
+ if (!response.ok) {
46
+ await response.body?.cancel();
47
+ return false;
48
+ }
49
+ const result = await response.json();
50
+ return result.data?.some(model => model.id === RUNCRATE_DEEPSEEK) ?? false;
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
56
+ async healthCheck() { return this.available(); }
57
+ async complete(request, signal) {
58
+ signal.throwIfAborted();
59
+ if (!await this.approved())
60
+ throw new SourceError('refused', 'Runcrate data sharing is not approved; rerun usegrunt setup');
61
+ return this.source.complete({ ...request, model: this.id }, signal);
62
+ }
63
+ async close() { await this.source.close(); }
64
+ }
@@ -18,10 +18,18 @@ import { withTerminal } from './terminal.js';
18
18
  import { Nvidia, writeNvidiaGrant } from './nvidia.js';
19
19
  import { Zro, writeZroGrant } from './zro.js';
20
20
  import { TokenHarbor, writeTokenHarborGrant } from './tokenharbor.js';
21
+ import { Runcrate, writeRuncrateGrant } from './runcrate.js';
22
+ import { Apinex, writeApinexGrant } from './apinex.js';
23
+ import { setupMistralVibe } from './mistral-vibe-setup.js';
24
+ import { setupLiveKit } from './livekit-setup.js';
21
25
  import { DATA_SHARING_POLICIES, dataSharingPolicies, readDataSharingConsent } from './data-sharing.js';
22
26
  const exec = promisify(execFile);
23
27
  export const FREELLMAPI_IMAGE = 'ghcr.io/tashfeenahmed/freellmapi@sha256:845a4b568a20fffd5112e1b9c0258e7782d9eabbba2430612d2f7c811eee267e';
24
- export const PROVIDERS = { groq: 'https://console.groq.com/keys', cerebras: 'https://cloud.cerebras.ai/platform/api-keys', kilo: 'https://app.kilo.ai/profile', nvidia: 'https://build.nvidia.com/settings/api-keys', zro: 'https://zro.moonmath.ai/overview', tokenharbor: 'https://tokenharbor.ai/dashboard' };
28
+ export const PROVIDERS = { groq: 'https://console.groq.com/keys', cerebras: 'https://cloud.cerebras.ai/platform/api-keys', kilo: 'https://app.kilo.ai/profile', nvidia: 'https://build.nvidia.com/settings/api-keys', zro: 'https://zro.moonmath.ai/overview', tokenharbor: 'https://tokenharbor.ai/dashboard', runcrate: 'https://www.runcrate.ai/auth/signup', apinex: 'https://apinex.bond/register', 'mistral-vibe': 'https://console.mistral.ai', livekit: 'https://cloud.livekit.io' };
29
+ const freeProviderInstructions = {
30
+ runcrate: ' Verify that the GitHub account is at least 30 days old. Use the normal Get your free tokens link at https://www.runcrate.ai/dashboard/api-keys#free-card to activate its recurring weekly allowance; verify the free tier is active via GitHub and not paused. Leave optional marketing unchecked. Verify no paid subscription, no purchased balance, no payment method and automatic top-ups disabled. If any of these checks fails, stop and report it; do not change billing settings or create another account. Use only deepseek-ai/DeepSeek-V4.1-Flash at api.runcrate.ai. Capture the API key with api_hosts ["api.runcrate.ai"] and auth_shape "bearer", service runcrate, label grunt. Reuse an existing vaulted key where possible; never reset or rotate it.',
31
+ apinex: ' Verify the Free plan and complete today\'s ordinary DAILY CHECK-IN to activate recurring free quota. Use the personal @gmail.com Google identity already connected to Squire; do not choose a workspace identity or switch accounts. Use only free/deepseek-v4.1-flash at api.apinex.bond, never a wallet-funded model or paid sibling. Verify the check-in for the current UTC date is actually claimed and free quota is active; absence of a check-in modal alone is insufficient. Do not use or change any existing paid wallet balance. Dismiss any paid upsell after check-in. Do not add billing, top up a wallet, buy credits, or use any paid balance. If check-in or free access cannot be confirmed, stop and report it. Capture the API key with api_hosts ["api.apinex.bond"] and auth_shape "bearer", service apinex, label grunt. Reuse an existing vaulted key; never reset or rotate it.'
32
+ };
25
33
  export const KILO_NEMOTRON = 'nvidia/nemotron-3-ultra-550b-a55b:free';
26
34
  export { NVIDIA_DEEPSEEK } from './nvidia.js';
27
35
  const savedProviders = ['kilo'];
@@ -311,7 +319,7 @@ export class BrowserSquire {
311
319
  }
312
320
  async driveOnce(provider, url, goal) {
313
321
  const customGoal = goal === undefined ? undefined : `${goal}${this.options.dataSharingApproved?.includes(provider) ? ' The user approved data sharing for this provider during grouped setup consent. You may accept its required free-route data-sharing disclosure to enable free access.' : ' Do not opt in to optional prompt/response retention, staff review or model training; report any required consent for grouped setup approval.'}`;
314
- const instruction = customGoal ?? `Use the user's existing ${provider} account or sign up for the free plan. Prefer Google OAuth using the user's Squire-connected identity. Reuse an existing key in this user's vault, or create one API key for grunt and store it in this user's Squire vault with service ${provider}. Use operate_extract to capture the key directly into the vault; never put its value in your answer.${provider === 'kilo' ? ' Reuse the existing profile API key without resetting it. Capture with api_hosts ["api.kilo.ai", "ai-gateway.kilo.ai"] in that order and auth_shape "bearer"; grunt uses /api/gateway beneath the grant.' : ''}${provider === 'nvidia' ? ' Complete free NVIDIA Build developer onboarding and enable its free inference endpoint. Capture the API key with api_hosts ["integrate.api.nvidia.com"] and auth_shape "bearer". Never reset or rotate an existing key. The requested free model is deepseek-ai/deepseek-v4.1-flash.' : ''}${provider === 'zro' ? ' Verify that this account is on the Free plan, has no paid subscription, no purchased usage-pack balance and no saved payment method before creating or reusing its key. If any paid balance, plan or payment method exists, stop and report it; do not cancel, downgrade, remove a payment method or create another account. Enable only its daily free DeepSeek V4.1 Flash access. Capture the API key with api_hosts ["zro.moonmath.ai"] and auth_shape "bearer". Store service zro, label grunt. Never reset or rotate an existing key. The requested model is deepseek-v4.1-flash.' : ''}${provider === 'tokenharbor' ? ' Enable the free model deepseek-v4.1-flash:free under the approved data-sharing policy; never select its paid sibling. Capture with api_hosts ["tokenharbor.ai"] and auth_shape "bearer", service tokenharbor, label grunt. Do not create a second key if an existing vaulted key is usable, and never reset or rotate an existing key.' : ''}${this.options.dataSharingApproved?.includes(provider) ? ' The user approved data sharing for this provider during grouped setup consent. You may accept its required free-route prompt/response retention, staff review and provider training disclosure to enable free access.' : ' Do not opt in to optional prompt/response retention, staff review or model training; if free access requires that consent, report it for the grouped setup approval.'} No paid plan, payment method, extra account or account switching. If captcha, passkey or email confirmation needs a human, stop and report the required step so grunt can share this browser. Do not bypass verification. Stop on provider refusal.`;
322
+ const instruction = customGoal ?? `Use the user's existing ${provider} account or sign up for the free plan. ${provider === 'runcrate' ? 'Use GitHub OAuth for the free path; do not use Google OAuth because that path requires billing.' : provider === 'apinex' ? 'Use Google OAuth with the personal @gmail.com identity already connected to Squire.' : "Prefer Google OAuth using the user's Squire-connected identity."} Reuse an existing key in this user's vault, or create one API key for grunt and store it in this user's Squire vault with service ${provider}. Use operate_extract to capture the key directly into the vault; never put its value in your answer.${provider === 'kilo' ? ' Reuse the existing profile API key without resetting it. Capture with api_hosts ["api.kilo.ai", "ai-gateway.kilo.ai"] in that order and auth_shape "bearer"; grunt uses /api/gateway beneath the grant.' : ''}${provider === 'nvidia' ? ' Complete free NVIDIA Build developer onboarding and enable its free inference endpoint. Capture the API key with api_hosts ["integrate.api.nvidia.com"] and auth_shape "bearer". Never reset or rotate an existing key. The requested free model is deepseek-ai/deepseek-v4.1-flash.' : ''}${provider === 'zro' ? ' Verify that this account is on the Free plan, has no paid subscription, no purchased usage-pack balance and no saved payment method before creating or reusing its key. If any paid balance, plan or payment method exists, stop and report it; do not cancel, downgrade, remove a payment method or create another account. Enable only its daily free DeepSeek V4.1 Flash access. Capture the API key with api_hosts ["zro.moonmath.ai"] and auth_shape "bearer". Store service zro, label grunt. Never reset or rotate an existing key. The requested model is deepseek-v4.1-flash.' : ''}${provider === 'tokenharbor' ? ' Enable the free model deepseek-v4.1-flash:free under the approved data-sharing policy; never select its paid sibling. Capture with api_hosts ["tokenharbor.ai"] and auth_shape "bearer", service tokenharbor, label grunt. Do not create a second key if an existing vaulted key is usable, and never reset or rotate an existing key.' : ''}${freeProviderInstructions[provider] ?? ''}${this.options.dataSharingApproved?.includes(provider) ? ' The user approved data sharing for this provider during grouped setup consent. You may accept its required free-route prompt/response retention, staff review and provider training disclosure to enable free access.' : ' Do not opt in to optional prompt/response retention, staff review or model training; if free access requires that consent, report it for the grouped setup approval.'} No paid plan, payment method, extra account or account switching. If captcha, passkey or email confirmation needs a human, stop and report the required step so grunt can share this browser. Do not bypass verification. Stop on provider refusal.`;
315
323
  let answer;
316
324
  while (true) {
317
325
  this.signal.throwIfAborted();
@@ -701,6 +709,46 @@ export async function setup(notify = console.log, providers = ['groq'], options
701
709
  try {
702
710
  await owned?.connect();
703
711
  options.signal?.throwIfAborted();
712
+ if (providers.includes('livekit')) {
713
+ const browser = squire;
714
+ if (typeof browser.signup !== 'function')
715
+ throw new Error('LiveKit native signup requires a browser-capable Squire client');
716
+ await setupLiveKit({ directory: location, squire: browser, notify, ...(options.signal ? { signal: options.signal } : {}) });
717
+ providers = providers.filter(provider => provider !== 'livekit');
718
+ }
719
+ if (providers.includes('mistral-vibe')) {
720
+ const browser = squire;
721
+ if (typeof browser.signup !== 'function')
722
+ throw new Error('Mistral Vibe native signup requires a browser-capable Squire client');
723
+ await setupMistralVibe({ directory: location, squire: browser, notify, ...(options.signal ? { signal: options.signal } : {}) });
724
+ providers = providers.filter(provider => provider !== 'mistral-vibe');
725
+ }
726
+ for (const provider of ['runcrate', 'apinex']) {
727
+ if (!providers.includes(provider))
728
+ continue;
729
+ const source = provider === 'runcrate' ? new Runcrate({ directory: location }) : new Apinex({ directory: location });
730
+ const writeGrant = provider === 'runcrate' ? writeRuncrateGrant : writeApinexGrant;
731
+ try {
732
+ const result = await setupProviders(squire, {
733
+ hasKey: async (id) => id === provider && await source.available(),
734
+ addGrant: async (id, grant) => {
735
+ if (id !== provider)
736
+ throw new Error(`Unexpected ${provider} credential`);
737
+ await writeGrant(grant, location);
738
+ if (!await source.available())
739
+ throw new Error(`${provider}: verified free access is unavailable`);
740
+ }
741
+ }, { providers: [provider], notify, reuseSaved: false, verifySaved: [provider] });
742
+ if (result.dropped.length)
743
+ throw new Error(`${provider} setup incomplete; rerun usegrunt setup`);
744
+ }
745
+ finally {
746
+ await source.close();
747
+ }
748
+ providers = providers.filter(id => id !== provider);
749
+ }
750
+ if (!providers.length)
751
+ return {};
704
752
  if (providers.includes('zro')) {
705
753
  const source = new Zro({ directory: location });
706
754
  try {
@@ -339,7 +339,8 @@ const PREAMBLE = [
339
339
  ].join('\n');
340
340
  const SQUIRE_NOTICE = [
341
341
  'Some free services only work with an account. Trusty Squire is a local',
342
- 'browser helper that signs up for them for you using Google sign-in (OAuth).',
342
+ 'browser helper that signs up for them using their supported sign-in.',
343
+ 'Most use Google; Runcrate’s card-free access needs GitHub sign-in.',
343
344
  '',
344
345
  'Next, a browser may open and ask you to sign in to Google once. If Trusty',
345
346
  'Squire is already connected on this machine, setup reuses it. A captcha or',
@@ -411,7 +412,7 @@ export async function wizard(add, actions = wizardActions) {
411
412
  const previous = (await actions.installedSources?.())?.split(',') ?? [];
412
413
  if (add) {
413
414
  const defaults = bundledRegistry.adapters.filter(adapter => knownAdapters.has(adapter.id)).map(adapter => adapter.id);
414
- const sources = ['kilo', 'nvidia', 'zro', 'tokenharbor'].includes(add)
415
+ const sources = ['kilo', 'nvidia', 'zro', 'tokenharbor', 'runcrate', 'apinex', 'mistral-vibe', 'livekit'].includes(add)
415
416
  ? [...new Set([...(previous.length ? previous : defaults), add])]
416
417
  : [...new Set(['freellmapi', ...previous, ...defaults])];
417
418
  const consent = await (actions.approveDataSharing ?? approveDataSharing)({ directory: configDir(), providers: sources });
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 1,
3
- "published": "2026-11-14T22:10:00Z",
3
+ "published": "2026-11-15T06:09:28Z",
4
4
  "adapters": [
5
5
  {
6
6
  "id": "freebuff",
@@ -56,13 +56,61 @@
56
56
  "id": "tokenharbor",
57
57
  "kind": "model",
58
58
  "tier": "experimental",
59
- "weight": 0.2,
59
+ "weight": 0.04,
60
60
  "modalities": [
61
61
  "text"
62
62
  ],
63
63
  "install": "builtin:tokenharbor",
64
64
  "signup": "https://tokenharbor.ai/dashboard",
65
65
  "model": "deepseek-v4.1-flash:free"
66
+ },
67
+ {
68
+ "id": "runcrate",
69
+ "kind": "model",
70
+ "tier": "experimental",
71
+ "weight": 0.04,
72
+ "modalities": [
73
+ "text"
74
+ ],
75
+ "install": "builtin:runcrate",
76
+ "signup": "https://www.runcrate.ai/inference/free",
77
+ "model": "deepseek-ai/DeepSeek-V4.1-Flash"
78
+ },
79
+ {
80
+ "id": "apinex",
81
+ "kind": "model",
82
+ "tier": "experimental",
83
+ "weight": 0.04,
84
+ "modalities": [
85
+ "text"
86
+ ],
87
+ "install": "builtin:apinex",
88
+ "signup": "https://apinex.bond/register",
89
+ "model": "free/deepseek-v4.1-flash"
90
+ },
91
+ {
92
+ "id": "mistral-vibe",
93
+ "kind": "agent",
94
+ "tier": "experimental",
95
+ "weight": 0.04,
96
+ "modalities": [
97
+ "text"
98
+ ],
99
+ "install": "builtin:mistral-vibe",
100
+ "signup": "https://console.mistral.ai/",
101
+ "model": "zai-glm-5-3-flash-vibe-free"
102
+ },
103
+ {
104
+ "id": "livekit",
105
+ "kind": "model",
106
+ "tier": "experimental",
107
+ "weight": 0.04,
108
+ "modalities": [
109
+ "text"
110
+ ],
111
+ "install": "builtin:livekit",
112
+ "signup": "https://cloud.livekit.io/",
113
+ "model": "deepseek-ai/deepseek-v4.1-flash"
66
114
  }
67
115
  ]
68
116
  }