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 CHANGED
@@ -16,18 +16,20 @@ usegrunt installs grunt on this machine. It pools free AI quota and serves one l
16
16
 
17
17
  https://grunt.run. `milo` and `milo-local` remain aliases.
18
18
 
19
- Setup connects Trusty Squire, installs and connects the vetted Freebuff, OpenCode, Kilo and Zro pool, plus opt-in Token Harbor (up to three services at once), tests each service, then connects your coding tools. Browser verification is queued when a provider needs you. Pi is optional.
19
+ Setup connects Trusty Squire and offers nine vetted free sources: Freebuff, OpenCode, Kilo, Zro, Token Harbor, Runcrate, APInex, Mistral Vibe Free and LiveKit. It connects up to three services at once, tests each, then connects your coding tools. Browser verification is queued when a provider needs you. Pi is optional.
20
20
 
21
21
  [Reference](https://github.com/bananaman614305/milo/blob/main/docs/reference.md).
22
22
 
23
- New installs offer Zro's daily free DeepSeek V4.1 Flash and, after one grouped data-sharing approval, Freebuff, OpenCode, Kilo Auto and Token Harbor's weekly free route. `usegrunt add groq`, `usegrunt add cerebras`, `usegrunt add kilo`, `usegrunt add zro` and `usegrunt add tokenharbor` remain available. NVIDIA stays optional while its account verification is unvetted. Existing `freellmapi` routes keep their Nemotron-first Kilo chain; the default `kilo` source selects `kilo-auto/free`. Repeat setup preserves previously connected API sources.
23
+ One grouped data-sharing approval covers the providers that require it, including Runcrate, APInex and Mistral Vibe Free. `usegrunt add <provider>` remains available for supported providers. Runcrate needs a GitHub account at least 30 days old; APInex needs a personal Gmail Google login and daily free check-in. Mistral uses its native Vibe Free coding allowance, not ordinary API credit. NVIDIA stays optional while account verification is unvetted; Cloudflare Qwen is excluded by choice. Existing `freellmapi` routes keep their Nemotron-first Kilo chain; the default `kilo` source selects `kilo-auto/free`. Repeat setup preserves previously connected API sources.
24
+
25
+ LiveKit adds DeepSeek V4.1 Flash through its free Build plan, using one free project and the official CLI's browser login. The documented included inference allowance is $2.50 per calendar month with a hard stop and no card. Keep the account on Build. LiveKit documents [zero data retention and no training for inference](https://docs.livekit.io/agents/models/inference/), so it adds no sharing approval; the existing seven policies remain unchanged. The route passed short-prompt, tool-call and 210,077-token context checks through Grunt.
24
26
 
25
27
  Within OpenCode, new conversations rotate across DeepSeek V4.1 Flash Free,
26
28
  GLM 5.3 Flash Free and Big Pickle. Follow-ups keep their model, and quota errors
27
29
  try another free model. These models may share provider limits; the pool does
28
30
  not create extra credit balances or purchase credits.
29
31
 
30
- Zro setup confirms the Free plan, no purchased usage balance and no payment method before connecting it. Keep that account free: Zro uses the same model ID on its paid plans, so changing the account outside grunt can change billing. Token Harbor uses its explicit `:free` model ID and requires approval for retained prompts, staff review and upstream-provider training. Setup asks once for Freebuff, OpenCode (including Big Pickle), Kilo and Token Harbor together, showing each provider's disclosure. It remembers the approved policy versions in a private local receipt. Declining or cancelling skips those providers and continues with Zro. Changed or newly added policies require another grouped approval. Background setup never prompts, and both signup and routing require the current receipt.
32
+ Zro setup confirms the Free plan, no purchased usage balance and no payment method before connecting it. Keep that account free: Zro uses the same model ID on its paid plans, so changing the account outside grunt can change billing. Token Harbor uses its explicit `:free` model ID. Runcrate requires no paid balance, no card and automatic top-ups off; APInex uses only its `free/` route and never spends wallet funds; Mistral Vibe keeps pay-as-you-go off. Setup shows provider-specific data-sharing disclosures together and remembers approved policy versions in a private receipt. Declining or cancelling skips those providers and continues with Zro and LiveKit, subject to their free-account checks. Changed or newly added policies require another grouped approval. Background setup never prompts, and both signup and routing require the current receipt where required.
31
33
 
32
34
  Kilo free models may log prompts or use them for training; avoid sensitive prompts. Their free limits are unknown. Kilo quota errors fall through FreeLLMAPI's fallback chain. Requests allow a long timeout for Nemotron reasoning.
33
35
 
@@ -0,0 +1,104 @@
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 APINEX_DEEPSEEK = 'free/deepseek-v4.1-flash';
7
+ function validate(value) {
8
+ const grant = value;
9
+ const access = validateProviderGrant(value);
10
+ if (grant?.free_account_verified !== true || typeof grant.daily_checkin_at !== 'string'
11
+ || !Number.isFinite(Date.parse(grant.daily_checkin_at)))
12
+ throw new Error('APInex daily free check-in verification is missing');
13
+ return { ...access, free_account_verified: true, daily_checkin_at: grant.daily_checkin_at };
14
+ }
15
+ export async function readApinexGrant(location = providerGrantDirectory()) {
16
+ return validate(await readPrivateProviderGrant('apinex', location));
17
+ }
18
+ // Called only after Squire has completed today's actual free-account check-in.
19
+ export async function writeApinexGrant(grant, location = providerGrantDirectory()) {
20
+ const value = validate({ ...grant, free_account_verified: true, daily_checkin_at: new Date().toISOString() });
21
+ await writePrivateProviderGrant('apinex', value, location);
22
+ }
23
+ export class Apinex {
24
+ options;
25
+ id = 'apinex';
26
+ supportsFunctionTools = true;
27
+ source;
28
+ location;
29
+ shutdown = new AbortController();
30
+ constructor(options = {}) {
31
+ this.options = options;
32
+ this.location = options.directory ?? providerGrantDirectory();
33
+ this.source = new FreeApi('apinex', { ...options, fetcher: verifiedDeepSeekFetch(options.fetcher), loadGrant: () => this.grant() });
34
+ }
35
+ approved = async () => (await readDataSharingConsent(this.location, [this.id])).includes(this.id);
36
+ async grant() {
37
+ const grant = validate(await (this.options.loadGrant?.() ?? readApinexGrant(this.location)));
38
+ const today = new Date((this.options.now ?? Date.now)()).toISOString().slice(0, 10);
39
+ if (new Date(grant.daily_checkin_at).toISOString().slice(0, 10) !== today)
40
+ throw new Error('APInex daily free check-in is required');
41
+ return grant;
42
+ }
43
+ async access(grant, caller) {
44
+ caller.throwIfAborted();
45
+ const signal = AbortSignal.any([caller, this.shutdown.signal, AbortSignal.timeout(5000)]);
46
+ try {
47
+ const response = await (this.options.fetcher ?? fetch)(`${grant.base_url}/v1/subscription`, {
48
+ headers: { Authorization: `Bearer ${grant.token}` }, redirect: 'error', signal
49
+ });
50
+ if (!response.ok) {
51
+ await response.body?.cancel();
52
+ throw new SourceError(response.status === 401 ? 'logged_out' : response.status === 429 ? 'quota' : 'upstream', `APInex access check returned HTTP ${response.status}`);
53
+ }
54
+ const state = await response.json();
55
+ signal.throwIfAborted();
56
+ const remaining = state?.tokens_remaining;
57
+ if (state?.mode !== 'free')
58
+ throw new SourceError('refused', 'APInex free account access is not active');
59
+ if (state.allowed !== true || typeof remaining !== 'number' || !Number.isFinite(remaining) || remaining <= 0) {
60
+ const reset = typeof state.resets_at_utc === 'string' ? Date.parse(state.resets_at_utc) : NaN;
61
+ const retry = Number.isFinite(reset) ? Math.max(1, Math.ceil((reset - (this.options.now ?? Date.now)()) / 1000)) : undefined;
62
+ throw new SourceError('quota', 'APInex daily free allowance is unavailable; complete its daily check-in', retry);
63
+ }
64
+ }
65
+ catch (error) {
66
+ caller.throwIfAborted();
67
+ if (this.shutdown.signal.aborted)
68
+ throw new SourceError('cancelled', 'APInex access check closed');
69
+ if (signal.aborted)
70
+ throw new SourceError('timeout', 'APInex access check timed out');
71
+ if (error instanceof SourceError)
72
+ throw error;
73
+ throw new SourceError('upstream', 'APInex access check is unavailable');
74
+ }
75
+ }
76
+ async available() {
77
+ if (!await this.approved())
78
+ return false;
79
+ try {
80
+ const grant = await this.grant();
81
+ await this.access(grant, new AbortController().signal);
82
+ return true;
83
+ }
84
+ catch {
85
+ return false;
86
+ }
87
+ }
88
+ async healthCheck() { return this.available(); }
89
+ async complete(request, signal) {
90
+ signal.throwIfAborted();
91
+ if (!await this.approved())
92
+ throw new SourceError('refused', 'APInex data sharing is not approved; rerun usegrunt setup');
93
+ let grant;
94
+ try {
95
+ grant = await this.grant();
96
+ }
97
+ catch {
98
+ throw new SourceError('logged_out', 'APInex daily free check-in is required; rerun usegrunt setup');
99
+ }
100
+ await this.access(grant, signal);
101
+ return this.source.complete({ ...request, model: this.id }, signal);
102
+ }
103
+ async close() { this.shutdown.abort(); await this.source.close(); }
104
+ }
@@ -22,6 +22,18 @@ export const DATA_SHARING_POLICIES = [{
22
22
  provider: 'tokenharbor', name: 'Token Harbor', version: '2026-11-15',
23
23
  disclosure: 'Prompts and responses may be retained, read by staff, and used by upstream providers for training.',
24
24
  url: 'https://team.tokenharbor.ai/faq'
25
+ }, {
26
+ provider: 'runcrate', name: 'Runcrate', version: '2026-11-15',
27
+ disclosure: 'Free inference is served by third-party model providers under their own terms. Runcrate does not save API prompts or responses by default and does not train on saved prompts; upstream retention and training guarantees are not established.',
28
+ url: 'https://www.runcrate.ai/inference/free'
29
+ }, {
30
+ provider: 'apinex', name: 'APInex', version: '2026-11-15',
31
+ disclosure: 'Account and usage metadata are collected. Prompt retention duration and upstream no-training guarantees are not established for the free route.',
32
+ url: 'https://apinex.bond/legal/privacy'
33
+ }, {
34
+ provider: 'mistral-vibe', name: 'Mistral Vibe Free (GLM 5.3 Flash)', version: '2026-11-15',
35
+ disclosure: 'The native coding agent sends task and project context to Mistral-hosted GLM. Free-plan prompt and code data may be used to improve services; no zero-retention guarantee is established for this route.',
36
+ url: 'https://legal.mistral.ai/terms/privacy-policy'
25
37
  }];
26
38
  const fileName = 'data-sharing-consent.json';
27
39
  const emptyReceipt = () => ({ version: 1, approved: {} });
@@ -229,6 +229,58 @@ export async function setupFallbacks(options) {
229
229
  options.notify('Token Harbor setup incomplete or data sharing not approved. Run usegrunt setup to finish; other routes remain available.');
230
230
  }
231
231
  },
232
+ runcrate: async () => {
233
+ try {
234
+ await connect();
235
+ if (!squire.runs)
236
+ throw new Error('Provider signup requires Squire');
237
+ await (options.setupProvider ?? setup)(options.notify, ['runcrate'], { squire: squire, directory: options.directory,
238
+ dataSharingApproved: approved, ...(options.signal ? { signal: options.signal } : {}) });
239
+ options.notify('Runcrate: GitHub-verified weekly free DeepSeek V4.1 Flash access connected through Squire');
240
+ }
241
+ catch {
242
+ unavailable.push('runcrate');
243
+ options.notify('Runcrate free setup incomplete. GitHub must be at least 30 days old; rerun usegrunt setup to resume. Other routes remain available.');
244
+ }
245
+ },
246
+ apinex: async () => {
247
+ try {
248
+ await connect();
249
+ if (!squire.runs)
250
+ throw new Error('Provider signup requires Squire');
251
+ await (options.setupProvider ?? setup)(options.notify, ['apinex'], { squire: squire, directory: options.directory,
252
+ dataSharingApproved: approved, ...(options.signal ? { signal: options.signal } : {}) });
253
+ options.notify('APInex: daily check-in verified for free DeepSeek V4.1 Flash access through Squire');
254
+ }
255
+ catch {
256
+ unavailable.push('apinex');
257
+ options.notify('APInex free setup or daily check-in incomplete. Rerun usegrunt setup to resume; other routes remain available.');
258
+ }
259
+ },
260
+ 'mistral-vibe': async () => {
261
+ try {
262
+ await connect();
263
+ await (options.setupProvider ?? setup)(options.notify, ['mistral-vibe'], { squire: squire, directory: options.directory,
264
+ dataSharingApproved: approved, ...(options.signal ? { signal: options.signal } : {}) });
265
+ options.notify('Mistral Vibe: native free GLM 5.3 Flash access connected through Squire');
266
+ }
267
+ catch {
268
+ unavailable.push('mistral-vibe');
269
+ options.notify('Mistral Vibe native free setup incomplete. Install uv or Python 3.12+ if missing, then rerun usegrunt setup; other routes remain available.');
270
+ }
271
+ },
272
+ livekit: async () => {
273
+ try {
274
+ await connect();
275
+ await (options.setupProvider ?? setup)(options.notify, ['livekit'], { squire: squire, directory: options.directory,
276
+ ...(options.signal ? { signal: options.signal } : {}) });
277
+ options.notify('LiveKit: native free Build DeepSeek V4.1 Flash access connected through Squire');
278
+ }
279
+ catch {
280
+ unavailable.push('livekit');
281
+ options.notify('LiveKit free Build signup or native CLI pairing incomplete. Rerun usegrunt setup; other routes remain available.');
282
+ }
283
+ },
232
284
  nvidia: async () => {
233
285
  try {
234
286
  await connect();
@@ -3,19 +3,23 @@ import { open } from 'node:fs/promises';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { SourceError } from './source.js';
6
- // Probe-only providers: these are not enabled by the published adapter registry.
6
+ // Low-level pinned clients. Production wrappers add provider-specific access
7
+ // receipts, quota checks and data-sharing consent before enabling a route.
7
8
  export const FREE_API_PROVIDERS = {
8
9
  zro: { model: 'deepseek-v4.1-flash', prefix: '/v1' },
9
10
  amd: { model: 'DeepSeek-V4.1-Flash', prefix: '/radeon/api/v1' },
10
- tokenharbor: { model: 'deepseek-v4.1-flash:free', prefix: '/v1' }
11
+ tokenharbor: { model: 'deepseek-v4.1-flash:free', prefix: '/v1' },
12
+ runcrate: { model: 'deepseek-ai/DeepSeek-V4.1-Flash', prefix: '/v1' },
13
+ apinex: { model: 'free/deepseek-v4.1-flash', prefix: '/v1' },
14
+ livekit: { model: 'deepseek-ai/deepseek-v4.1-flash', prefix: '/v1' }
11
15
  };
12
16
  // Official API metadata maps deepseek-flash to DeepSeek-V4.1-Flash:
13
17
  // https://api-docs.deepseek.com/api/list-models/ . Other aliases below are the
14
18
  // explicit V4.1 IDs used by these providers, not loose family-name matches.
15
19
  const deepSeekV41Aliases = new Set(['deepseek-flash', 'deepseek-v4.1-flash', 'deepseek-v4.1-flash-1017',
16
- 'deepseek-v4.1-flash-free', 'deepseek-v4.1-flash:free']);
20
+ 'deepseek-v4.1-flash-free', 'deepseek-v4.1-flash:free', 'free/deepseek-v4.1-flash']);
17
21
  export function isDeepSeekV41Model(value) {
18
- return typeof value === 'string' && deepSeekV41Aliases.has(value.toLowerCase().replace(/^deepseek\//, ''));
22
+ return typeof value === 'string' && deepSeekV41Aliases.has(value.toLowerCase().replace(/^deepseek(?:-ai)?\//, ''));
19
23
  }
20
24
  const directory = () => process.env.MILO_CONFIG_DIR || join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
21
25
  function providerName(value) {
@@ -0,0 +1,269 @@
1
+ import { spawn, execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { access, chmod, lstat, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
5
+ import { constants } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { LIVEKIT_CLI_VERSION, livekitPaths, livekitEnvironment, parseLiveKitProjects, readLiveKitFreeBuildReceipt, writeLiveKitFreeBuildReceipt } from './livekit.js';
9
+ const exec = promisify(execFile);
10
+ // Official v2.19.4 checksums.txt, pinned with the release rather than fetched as
11
+ // a mutable trust decision during installation.
12
+ const archives = {
13
+ darwin_amd64: '281c8db91cd83ead131e16c4f857db80a6cdbc59996584961ce7b0c6d34b2789',
14
+ darwin_arm64: '0732343947a08c1cb495bf7a5c4a0dab2cc2caecd1f67d9eba3fdf01ae3f2cee',
15
+ linux_amd64: 'cb0f769201faa13956a3999bee078ec63fd5f22b855a79c09d648283e50debae',
16
+ linux_arm64: '368b12e35fff71ff14867800f747da3714ec2a56b61b855d552c3d79ef4a9586'
17
+ };
18
+ const clean = (text) => text.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '').replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replaceAll('\r', '');
19
+ const quote = (text) => "'" + text.replaceAll("'", "'\\''") + "'";
20
+ async function privateDirectory(path) {
21
+ await mkdir(path, { recursive: true, mode: 0o700 });
22
+ const stat = await lstat(path);
23
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o700)
24
+ throw new Error('LiveKit setup requires a private directory owned by this user with mode 0700');
25
+ }
26
+ async function nativeConfig(directory, missing = false) {
27
+ await privateDirectory(directory);
28
+ try {
29
+ const stat = await lstat(join(directory, 'cli-config.yaml'));
30
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || (!missing && stat.size === 0))
31
+ throw new Error('Unsafe LiveKit native CLI config; it must be owned by this user with mode 0600');
32
+ }
33
+ catch (error) {
34
+ if (!missing || error.code !== 'ENOENT')
35
+ throw error;
36
+ }
37
+ }
38
+ async function command(binary, args, cwd, signal) {
39
+ try {
40
+ return (await exec(binary, args, { cwd, env: livekitEnvironment(), signal, timeout: 30000, maxBuffer: 262144 })).stdout;
41
+ }
42
+ catch {
43
+ signal?.throwIfAborted();
44
+ throw new Error('LiveKit native CLI command failed; rerun usegrunt setup');
45
+ }
46
+ }
47
+ export async function installLiveKit(directory, options = {}) {
48
+ const platform = options.platform ?? process.platform;
49
+ const arch = (options.arch ?? process.arch) === 'x64' ? 'amd64' : options.arch ?? process.arch;
50
+ const checksum = archives[`${platform}_${arch}`];
51
+ if (!checksum)
52
+ throw new Error('LiveKit automatic installation supports Linux and macOS on x64 or arm64');
53
+ const paths = livekitPaths(directory);
54
+ await privateDirectory(paths.home);
55
+ const bin = join(paths.home, 'bin');
56
+ await privateDirectory(bin);
57
+ const work = join(paths.home, 'work');
58
+ await privateDirectory(work);
59
+ try {
60
+ const stat = await lstat(paths.binary);
61
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
62
+ throw new Error('unsafe');
63
+ await access(paths.binary, constants.X_OK);
64
+ if (clean(await command(paths.binary, ['--version'], work, options.signal)).trim() === `lk version ${LIVEKIT_CLI_VERSION}`)
65
+ return paths.binary;
66
+ }
67
+ catch {
68
+ options.signal?.throwIfAborted();
69
+ }
70
+ const temporary = await mkdtemp(join(paths.home, '.install-'));
71
+ try {
72
+ const name = `lk_${LIVEKIT_CLI_VERSION}_${platform}_${arch}.tar.gz`;
73
+ const response = await (options.fetcher ?? fetch)(`https://github.com/livekit/livekit-cli/releases/download/v${LIVEKIT_CLI_VERSION}/${name}`, { signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(120000)]) : AbortSignal.timeout(120000), redirect: 'follow' });
74
+ if (!response.ok || Number(response.headers.get('content-length')) > 100 * 1024 * 1024)
75
+ throw new Error('LiveKit release download failed');
76
+ const archive = Buffer.from(await response.arrayBuffer());
77
+ if (archive.length > 100 * 1024 * 1024 || createHash('sha256').update(archive).digest('hex') !== checksum)
78
+ throw new Error('LiveKit release checksum did not match the pinned official release');
79
+ const path = join(temporary, 'release.tar.gz');
80
+ await writeFile(path, archive, { mode: 0o600, flag: 'wx' });
81
+ await command('tar', ['-xzf', path, '-C', temporary, 'lk'], work, options.signal);
82
+ const binary = join(temporary, 'lk');
83
+ const stat = await lstat(binary);
84
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.())
85
+ throw new Error('Invalid LiveKit release binary');
86
+ await chmod(binary, 0o700);
87
+ if (clean(await command(binary, ['--version'], work, options.signal)).trim() !== `lk version ${LIVEKIT_CLI_VERSION}`)
88
+ throw new Error('LiveKit release version did not match');
89
+ await rename(binary, paths.binary);
90
+ return paths.binary;
91
+ }
92
+ finally {
93
+ await rm(temporary, { recursive: true, force: true });
94
+ }
95
+ }
96
+ async function awaitBrowser(promise, signal, message) {
97
+ let aborted;
98
+ try {
99
+ await Promise.race([promise, new Promise((_resolve, reject) => {
100
+ aborted = () => reject(new Error(message));
101
+ signal.addEventListener('abort', aborted, { once: true });
102
+ if (signal.aborted)
103
+ aborted();
104
+ })]);
105
+ }
106
+ catch {
107
+ throw new Error(message);
108
+ }
109
+ finally {
110
+ if (aborted)
111
+ signal.removeEventListener('abort', aborted);
112
+ }
113
+ }
114
+ async function verifyAccount(options) {
115
+ const deadline = new AbortController();
116
+ const timeout = setTimeout(() => deadline.abort(), 600000);
117
+ const signal = options.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signal;
118
+ try {
119
+ await awaitBrowser(Promise.resolve().then(() => options.squire.signup('livekit', 'https://cloud.livekit.io', 'Use the personal Google identity already connected to Squire to sign up for LiveKit Cloud, or reuse its existing account. Verify the Build free plan, $2.50 monthly inference credit with a hard stop, no payment method, purchased credits, paid subscription or automatic top-ups. Reuse the owned empty grunt-free project, or create that one ordinary empty free project if absent. Turn off optional Agent observability on this owned grunt-free project, leaving unrelated projects unchanged. Do not create rooms, deploy agents, enable hosting or billing, buy credits, inspect API secrets, switch accounts or alter other projects. If the account has any paid plan, payment method, paid credits or automatic billing, stop without changing it. Finish only after verifying the free project and its billing state; native CLI pairing follows separately if needed. Required human verification needs browser handoff; stop on refusal.')), signal, 'LiveKit free Build account verification did not complete; rerun usegrunt setup');
120
+ }
121
+ finally {
122
+ clearTimeout(timeout);
123
+ }
124
+ }
125
+ async function verifyProject(binary, selector, work, signal) {
126
+ // This signs locally through the official CLI and performs no inference.
127
+ // The short-lived token remains backend-only and is discarded immediately.
128
+ const token = (await command(binary, ['--project', selector, '--config', join(work, 'livekit.toml'), 'token', 'create', '--inference', '--token-only', '--valid-for', '10m', '--identity', 'agent'], work, signal)).trim();
129
+ if (!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token) || token.length > 16384)
130
+ throw new Error('LiveKit native project authentication is unavailable; rerun usegrunt setup');
131
+ }
132
+ async function authenticate(binary, options, work) {
133
+ // pkg/browser ignores BROWSER and directly executes these platform openers.
134
+ // Suppress only that unmanaged launch; Squire visits the real pairing URL.
135
+ const openers = await mkdtemp(join(livekitPaths(options.directory).home, '.openers-'));
136
+ for (const name of ['open', 'xdg-open', 'x-www-browser', 'www-browser'])
137
+ await writeFile(join(openers, name), '#!/bin/sh\nexit 0\n', { mode: 0o700, flag: 'wx' });
138
+ const shell = `stty rows 40 cols 120 && exec ${quote(binary)} --config ${quote(join(work, 'livekit.toml'))} cloud auth --timeout 600`;
139
+ const args = process.platform === 'darwin' ? ['-q', '/dev/null', '/bin/sh', '-c', shell] : ['-qefc', shell, '/dev/null'];
140
+ const child = spawn('script', args, { cwd: work, env: { ...livekitEnvironment(), PATH: `${openers}:${process.env.PATH ?? '/usr/bin:/bin'}`, TERM: 'xterm-256color', NO_COLOR: '1', LK_NO_SKILLS_PROMPT: '1' }, stdio: ['pipe', 'pipe', 'pipe'], detached: process.platform !== 'win32' });
141
+ let buffer = '', failure, paired = false;
142
+ let pairing;
143
+ const answered = new Set();
144
+ let force;
145
+ const timeoutController = new AbortController();
146
+ const signal = options.signal ? AbortSignal.any([options.signal, timeoutController.signal]) : timeoutController.signal;
147
+ const stop = (hard = false) => { try {
148
+ if (child.pid)
149
+ process.kill(-child.pid, hard ? 'SIGKILL' : 'SIGTERM');
150
+ }
151
+ catch { /* Owned process already exited. */ } };
152
+ const abort = () => { stop(); force ??= setTimeout(() => stop(true), 1000); force.unref(); };
153
+ const deadline = setTimeout(() => { failure = new Error('LiveKit native login timed out; rerun usegrunt setup'); timeoutController.abort(); }, 600000);
154
+ signal.addEventListener('abort', abort, { once: true });
155
+ const read = (chunk) => {
156
+ buffer = (buffer + chunk.toString()).slice(-65536);
157
+ const text = clean(buffer);
158
+ const answer = (key, value) => { if (!answered.has(key)) {
159
+ answered.add(key);
160
+ child.stdin.write(value);
161
+ } };
162
+ if (/install livekit.*skills|install.*coding agent.*skills/i.test(text))
163
+ answer('skills', 'n\n');
164
+ if (/what is the name of this device\?/i.test(text))
165
+ answer('device', '\x15grunt\n');
166
+ if (/make this project default\?/i.test(text))
167
+ answer('default', 'n\n');
168
+ if (/choose a different alias/i.test(text))
169
+ answer('alias', `\x15grunt-free-${randomUUID().slice(0, 8)}\n`);
170
+ const match = text.match(/https:\/\/cloud\.livekit\.io\/cli\/confirm-auth\?[^\s\x1b]+/);
171
+ if (match && !paired) {
172
+ const url = new URL(match[0]);
173
+ if (!url.searchParams.get('t') || url.username || url.password || url.hash) {
174
+ failure = new Error('LiveKit returned an invalid native pairing URL');
175
+ abort();
176
+ return;
177
+ }
178
+ paired = true;
179
+ pairing = awaitBrowser(Promise.resolve().then(() => options.squire.signup('livekit', url.href, 'Approve only the LiveKit native CLI pairing started by Grunt. Select exactly the owned grunt-free project just verified on the Build free plan. Do not select another existing or paid project. Keep the $2.50 monthly inference hard stop and no payment method, paid credits or automatic billing. Never view, copy or reveal an API secret. Do not enable agent hosting, create rooms, buy credits, change another project, or switch accounts. Report any human verification for browser handoff; stop on refusal.')), signal, 'LiveKit browser pairing did not complete; rerun usegrunt setup');
180
+ void pairing.catch(() => { failure = new Error('LiveKit browser pairing did not complete; rerun usegrunt setup'); abort(); });
181
+ }
182
+ };
183
+ child.stdout.on('data', read);
184
+ child.stderr.on('data', read);
185
+ if (signal.aborted)
186
+ abort();
187
+ try {
188
+ const code = await new Promise((resolve, reject) => { child.once('error', () => reject(new Error('LiveKit native login requires the standard script PTY utility'))); child.once('close', resolve); });
189
+ if (signal.aborted)
190
+ throw new Error('LiveKit native login was cancelled or timed out; rerun usegrunt setup');
191
+ if (failure || code !== 0 || !paired)
192
+ throw failure ?? new Error('LiveKit native login did not complete');
193
+ await pairing;
194
+ }
195
+ finally {
196
+ clearTimeout(deadline);
197
+ if (force)
198
+ clearTimeout(force);
199
+ signal.removeEventListener('abort', abort);
200
+ stop(true);
201
+ child.stdin.destroy();
202
+ await rm(openers, { recursive: true, force: true });
203
+ }
204
+ }
205
+ export async function setupLiveKit(options) {
206
+ options.signal?.throwIfAborted();
207
+ const binary = await (options.install ?? installLiveKit)(options.directory, options.signal ? { signal: options.signal } : {});
208
+ const paths = livekitPaths(options.directory);
209
+ const work = await mkdtemp(join(paths.home, '.setup-work-'));
210
+ try {
211
+ await writeFile(join(work, 'livekit.toml'), '', { mode: 0o600, flag: 'wx' });
212
+ const native = options.nativeDirectory ?? join(homedir(), '.livekit');
213
+ await nativeConfig(native, true);
214
+ const before = parseLiveKitProjects(await command(binary, ['--config', join(work, 'livekit.toml'), 'project', 'list'], work, options.signal));
215
+ try {
216
+ const receipt = await readLiveKitFreeBuildReceipt(options.directory);
217
+ if (before.some(project => project.selector === receipt.projectSelector && project.id === receipt.projectId && project.url === receipt.projectURL)) {
218
+ await nativeConfig(native);
219
+ await verifyProject(binary, receipt.projectSelector, work, options.signal);
220
+ return;
221
+ }
222
+ }
223
+ catch {
224
+ options.signal?.throwIfAborted();
225
+ }
226
+ // A fresh browser check replaces any previous billing approval immediately.
227
+ await rm(paths.receipt, { force: true });
228
+ await verifyAccount(options);
229
+ const existing = before.filter(project => /^wss:\/\/grunt-free-[a-z0-9-]+\.livekit\.cloud$/.test(project.url));
230
+ if (existing.length && existing.some(project => project.id !== existing[0].id || project.url !== existing[0].url))
231
+ throw new Error('Multiple LiveKit grunt-free projects need an explicit selection before setup can continue');
232
+ if (existing.length) {
233
+ const project = existing[0];
234
+ let usable = false;
235
+ try {
236
+ await verifyProject(binary, project.selector, work, options.signal);
237
+ usable = true;
238
+ }
239
+ catch {
240
+ options.signal?.throwIfAborted();
241
+ }
242
+ if (usable) {
243
+ await writeLiveKitFreeBuildReceipt(options.directory, { version: 1, plan: 'Build', payAsYouGo: false, paymentMethodPresent: false, purchasedCredits: 0, projectSelector: project.selector, projectId: project.id, projectURL: project.url, checkedAt: new Date().toISOString() });
244
+ options.notify?.('LiveKit: verified free Build project reused with its existing native login');
245
+ return;
246
+ }
247
+ }
248
+ await authenticate(binary, options, work);
249
+ await nativeConfig(native);
250
+ const after = parseLiveKitProjects(await command(binary, ['--config', join(work, 'livekit.toml'), 'project', 'list'], work, options.signal));
251
+ const oldDefault = before.find(project => project.default);
252
+ if (oldDefault && after.find(project => project.default)?.selector !== oldDefault.selector)
253
+ throw new Error('LiveKit CLI changed the previous default project; restore it before rerunning setup');
254
+ if (before.some(old => !after.some(project => project.selector === old.selector && project.id === old.id && project.url === old.url)))
255
+ throw new Error('LiveKit CLI changed an existing project profile; setup stopped');
256
+ const added = after.filter(project => !before.some(old => old.selector === project.selector));
257
+ if (added.length !== 1)
258
+ throw new Error('LiveKit native login did not identify exactly one newly authorized free project');
259
+ const project = added[0];
260
+ if (!/^wss:\/\/grunt-free-[a-z0-9-]+\.livekit\.cloud$/.test(project.url))
261
+ throw new Error('LiveKit authorized a different project than the verified grunt-free project');
262
+ await verifyProject(binary, project.selector, work, options.signal);
263
+ await writeLiveKitFreeBuildReceipt(options.directory, { version: 1, plan: 'Build', payAsYouGo: false, paymentMethodPresent: false, purchasedCredits: 0, projectSelector: project.selector, projectId: project.id, projectURL: project.url, checkedAt: new Date().toISOString() });
264
+ options.notify?.('LiveKit: native free Build project connected for DeepSeek V4.1 Flash');
265
+ }
266
+ finally {
267
+ await rm(work, { recursive: true, force: true });
268
+ }
269
+ }