usegrunt 0.6.4 → 0.6.6
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 +15 -6
- package/dist/local/beatapi-setup.js +83 -0
- package/dist/local/beatapi.js +298 -0
- package/dist/local/clixad-preload.js +177 -0
- package/dist/local/clixad-setup.js +345 -0
- package/dist/local/clixad.js +398 -0
- package/dist/local/data-sharing.js +18 -2
- package/dist/local/fallback-setup.js +74 -22
- package/dist/local/free-api.js +2 -1
- package/dist/local/freebuff.js +5 -1
- package/dist/local/freellmapi.js +3 -5
- package/dist/local/kilo.js +209 -0
- package/dist/local/livekit-setup.js +269 -0
- package/dist/local/livekit.js +219 -0
- package/dist/local/main.js +13 -11
- package/dist/local/parallel.js +2 -0
- package/dist/local/perch-process.js +377 -0
- package/dist/local/perch-setup.js +297 -0
- package/dist/local/perch.js +480 -0
- package/dist/local/pollinations-setup.js +109 -0
- package/dist/local/pollinations.js +324 -0
- package/dist/local/registry.js +4 -4
- package/dist/local/setup.js +340 -62
- package/dist/local/source.js +7 -2
- package/dist/local/wizard.js +24 -21
- package/dist/registry/adapters.json +65 -29
- package/dist/registry.js +4 -2
- package/package.json +1 -1
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { Ajv } from 'ajv';
|
|
2
|
+
import { readDataSharingConsent } from './data-sharing.js';
|
|
3
|
+
import { providerGrantDirectory } from './provider-grant.js';
|
|
4
|
+
import { FreebuffTools } from './freebuff-tools.js';
|
|
5
|
+
import { SourceError } from './source.js';
|
|
6
|
+
export const KILO_PARTICLE = 'particle-ai/particle-1:free';
|
|
7
|
+
export const KILO_ORIGIN = 'https://ai-gateway.kilo.ai/api/v1';
|
|
8
|
+
const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
9
|
+
async function abortable(promise, signal) {
|
|
10
|
+
signal.throwIfAborted();
|
|
11
|
+
let abort;
|
|
12
|
+
try {
|
|
13
|
+
return await Promise.race([promise, new Promise((_resolve, reject) => {
|
|
14
|
+
abort = () => reject(signal.reason);
|
|
15
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
16
|
+
if (signal.aborted)
|
|
17
|
+
abort();
|
|
18
|
+
})]);
|
|
19
|
+
}
|
|
20
|
+
finally {
|
|
21
|
+
if (abort)
|
|
22
|
+
signal.removeEventListener('abort', abort);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
async function json(response, signal, limit) {
|
|
26
|
+
if (!response.body || Number(response.headers.get('content-length')) > limit) {
|
|
27
|
+
void response.body?.cancel().catch(() => { });
|
|
28
|
+
throw new SourceError('upstream', 'Kilo response exceeded the supported size');
|
|
29
|
+
}
|
|
30
|
+
const reader = response.body.getReader(), chunks = [];
|
|
31
|
+
let bytes = 0;
|
|
32
|
+
try {
|
|
33
|
+
for (;;) {
|
|
34
|
+
const part = await abortable(reader.read(), signal);
|
|
35
|
+
signal.throwIfAborted();
|
|
36
|
+
if (part.done)
|
|
37
|
+
break;
|
|
38
|
+
bytes += part.value.byteLength;
|
|
39
|
+
if (bytes > limit)
|
|
40
|
+
throw new SourceError('upstream', 'Kilo response exceeded the supported size');
|
|
41
|
+
chunks.push(part.value);
|
|
42
|
+
}
|
|
43
|
+
return object(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
void reader.cancel().catch(() => { });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function status(response) {
|
|
50
|
+
if (response.ok)
|
|
51
|
+
return;
|
|
52
|
+
const raw = response.headers.get('retry-after'), seconds = raw === null ? NaN : /^\d+(?:\.\d+)?$/.test(raw) ? Number(raw) : (Date.parse(raw) - Date.now()) / 1000;
|
|
53
|
+
void response.body?.cancel().catch(() => { });
|
|
54
|
+
throw new SourceError(response.status === 429 ? 'quota' : [401, 402, 403].includes(response.status) ? 'refused' : 'upstream', `Kilo returned HTTP ${response.status}`, response.status === 429 ? Math.max(1, Number.isFinite(seconds) ? Math.ceil(seconds) : 60) : undefined);
|
|
55
|
+
}
|
|
56
|
+
/** Nonbillable public metadata only. No account, API key, or paid fallback is used. */
|
|
57
|
+
export async function verifyKiloAccess(options = {}) {
|
|
58
|
+
const signal = AbortSignal.any([...(options.signal ? [options.signal] : []), AbortSignal.timeout(5000)]);
|
|
59
|
+
try {
|
|
60
|
+
signal.throwIfAborted();
|
|
61
|
+
const response = await abortable((options.fetcher ?? fetch)(`${KILO_ORIGIN}/models`, { redirect: 'error', signal }), signal);
|
|
62
|
+
status(response);
|
|
63
|
+
const body = await json(response, signal, 4 * 1024 * 1024), rows = Array.isArray(body.data) ? body.data.filter(row => object(row).id === KILO_PARTICLE) : [];
|
|
64
|
+
const model = object(rows.length === 1 ? rows[0] : undefined), pricing = object(model.pricing), parameters = model.supported_parameters;
|
|
65
|
+
const zero = (key) => (typeof pricing[key] === 'string' || typeof pricing[key] === 'number') && String(pricing[key]).trim() !== '' && Number(pricing[key]) === 0;
|
|
66
|
+
const costs = ['request', 'image', 'web_search', 'internal_reasoning', 'input_cache_read', 'input_cache_write'];
|
|
67
|
+
if (model.isFree !== true || !zero('prompt') || !zero('completion') || costs.some(key => key in pricing && !zero(key))
|
|
68
|
+
|| !Number.isSafeInteger(model.context_length) || Number(model.context_length) < 200000
|
|
69
|
+
|| !Array.isArray(parameters) || !['tools', 'max_tokens'].every(key => parameters.includes(key))) {
|
|
70
|
+
throw new SourceError('refused', 'Kilo Particle is not currently a verified free model with at least 200K context');
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (options.signal?.aborted)
|
|
75
|
+
throw new SourceError('cancelled', 'Kilo access check cancelled');
|
|
76
|
+
if (signal.aborted)
|
|
77
|
+
throw new SourceError('timeout', 'Kilo access check timed out');
|
|
78
|
+
if (error instanceof SourceError)
|
|
79
|
+
throw error;
|
|
80
|
+
throw new SourceError('upstream', 'Kilo free model metadata is unavailable');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function conversation(request) {
|
|
84
|
+
try {
|
|
85
|
+
const messages = [];
|
|
86
|
+
for (const message of request.messages) {
|
|
87
|
+
const previous = messages.at(-1);
|
|
88
|
+
// Responses expresses parallel calls as separate assistant items.
|
|
89
|
+
if (message.role === 'assistant' && message.content === '' && message.tool_calls?.length && !message.tool_call_id
|
|
90
|
+
&& previous?.role === 'assistant' && previous.content === '' && previous.tool_calls?.length && !previous.tool_call_id) {
|
|
91
|
+
previous.tool_calls = [...previous.tool_calls, ...message.tool_calls];
|
|
92
|
+
}
|
|
93
|
+
else
|
|
94
|
+
messages.push({ ...message });
|
|
95
|
+
}
|
|
96
|
+
new FreebuffTools({ ...request, messages }); // Validate roles and actual correlated results; no JSON bridge or tool execution.
|
|
97
|
+
const validators = new Map(), ajv = new Ajv({ strict: true, strictTypes: false, strictTuples: false, addUsedSchema: false });
|
|
98
|
+
for (const tool of request.tools) {
|
|
99
|
+
const fn = object(tool.function);
|
|
100
|
+
validators.set(fn.name, ajv.compile(fn.parameters));
|
|
101
|
+
}
|
|
102
|
+
return { messages, validators };
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw new SourceError('refused', 'Kilo rejected invalid function tools or an uncorrelated tool conversation');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
export class Kilo {
|
|
109
|
+
options;
|
|
110
|
+
id = 'kilo';
|
|
111
|
+
supportsFunctionTools = true;
|
|
112
|
+
shutdown = new AbortController();
|
|
113
|
+
pending = new Set();
|
|
114
|
+
constructor(options = {}) {
|
|
115
|
+
this.options = options;
|
|
116
|
+
}
|
|
117
|
+
async approved() { return (await readDataSharingConsent(this.options.directory ?? providerGrantDirectory(), [this.id])).includes(this.id); }
|
|
118
|
+
async track(task) { this.pending.add(task); try {
|
|
119
|
+
return await task;
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
this.pending.delete(task);
|
|
123
|
+
} }
|
|
124
|
+
async available() {
|
|
125
|
+
return this.track((async () => {
|
|
126
|
+
try {
|
|
127
|
+
if (this.shutdown.signal.aborted || !await this.approved())
|
|
128
|
+
return false;
|
|
129
|
+
await verifyKiloAccess({ ...(this.options.fetcher ? { fetcher: this.options.fetcher } : {}), signal: this.shutdown.signal });
|
|
130
|
+
return !this.shutdown.signal.aborted;
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
})());
|
|
136
|
+
}
|
|
137
|
+
async healthCheck() { return this.available(); }
|
|
138
|
+
complete(request, caller) { return this.track(this.once(request, caller)); }
|
|
139
|
+
async once(request, caller) {
|
|
140
|
+
const timeout = this.options.timeout, signal = AbortSignal.any([caller, this.shutdown.signal, AbortSignal.timeout(typeof timeout === 'number' && Number.isFinite(timeout) && timeout > 0 ? Math.min(180000, Math.ceil(timeout)) : 180000)]);
|
|
141
|
+
try {
|
|
142
|
+
signal.throwIfAborted();
|
|
143
|
+
if (request.imageInput)
|
|
144
|
+
throw new SourceError('refused', 'Kilo Particle supports text inputs through this route');
|
|
145
|
+
if (request.maxTokens !== undefined && (!Number.isSafeInteger(request.maxTokens) || request.maxTokens < 1))
|
|
146
|
+
throw new SourceError('refused', 'Kilo requires a positive integer output-token budget');
|
|
147
|
+
const limit = Math.min(4096, request.maxTokens ?? 4096), { messages, validators } = conversation(request);
|
|
148
|
+
if (!await this.approved())
|
|
149
|
+
throw new SourceError('refused', 'Kilo data sharing is not approved; rerun usegrunt setup');
|
|
150
|
+
signal.throwIfAborted();
|
|
151
|
+
const body = JSON.stringify({ model: KILO_PARTICLE, messages, ...(request.tools.length ? { tools: request.tools } : {}), stream: false, max_tokens: limit });
|
|
152
|
+
if (Buffer.byteLength(body) > 2 * 1024 * 1024)
|
|
153
|
+
throw new SourceError('refused', 'Kilo prompt exceeds the supported input size');
|
|
154
|
+
await verifyKiloAccess({ ...(this.options.fetcher ? { fetcher: this.options.fetcher } : {}), signal });
|
|
155
|
+
signal.throwIfAborted();
|
|
156
|
+
const response = await abortable((this.options.fetcher ?? fetch)(`${KILO_ORIGIN}/chat/completions`, { method: 'POST', redirect: 'error', signal,
|
|
157
|
+
headers: { 'Content-Type': 'application/json' }, body }), signal);
|
|
158
|
+
status(response);
|
|
159
|
+
const result = await json(response, signal, 2 * 1024 * 1024), usage = object(result.usage), details = object(usage.cost_details);
|
|
160
|
+
if (result.model !== KILO_PARTICLE)
|
|
161
|
+
throw new SourceError('refused', 'Kilo returned an unverified Particle model');
|
|
162
|
+
if (usage.cost !== 0 || ['total_cost', 'credits_charged'].some(key => key in usage && usage[key] !== 0)
|
|
163
|
+
|| ['upstream_inference_cost', 'upstream_inference_prompt_cost', 'upstream_inference_completions_cost'].some(key => details[key] !== 0)
|
|
164
|
+
|| ['cost', 'total_cost', 'credits_charged'].some(key => key in result && result[key] !== 0)
|
|
165
|
+
|| !Number.isSafeInteger(usage.prompt_tokens) || Number(usage.prompt_tokens) < 1 || !Number.isSafeInteger(usage.completion_tokens)
|
|
166
|
+
|| Number(usage.completion_tokens) < 1 || Number(usage.completion_tokens) > limit)
|
|
167
|
+
throw new SourceError('refused', 'Kilo returned unverified free usage or exceeded the output budget');
|
|
168
|
+
const choice = object(Array.isArray(result.choices) && result.choices.length === 1 ? result.choices[0] : undefined), message = object(choice.message);
|
|
169
|
+
if (message.refusal)
|
|
170
|
+
throw new SourceError('refused', 'Kilo refused the request');
|
|
171
|
+
if (!(message.content === undefined || message.content === null || typeof message.content === 'string'))
|
|
172
|
+
throw new SourceError('upstream', 'Kilo returned invalid completion content');
|
|
173
|
+
const calls = [], ids = new Set();
|
|
174
|
+
if (message.tool_calls !== undefined) {
|
|
175
|
+
if (!Array.isArray(message.tool_calls) || message.tool_calls.length > 16)
|
|
176
|
+
throw new SourceError('upstream', 'Kilo returned invalid function calls');
|
|
177
|
+
for (const value of message.tool_calls) {
|
|
178
|
+
const call = object(value), fn = object(call.function);
|
|
179
|
+
let args;
|
|
180
|
+
try {
|
|
181
|
+
args = JSON.parse(String(fn.arguments));
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
throw new SourceError('upstream', 'Kilo returned invalid function arguments');
|
|
185
|
+
}
|
|
186
|
+
if (call.type !== 'function' || typeof call.id !== 'string' || !call.id || call.id.length > 256 || ids.has(call.id)
|
|
187
|
+
|| request.messages.some(m => m.tool_calls?.some(old => old.id === call.id)) || typeof fn.name !== 'string' || typeof fn.arguments !== 'string'
|
|
188
|
+
|| !args || typeof args !== 'object' || Array.isArray(args) || !validators.get(fn.name)?.(args))
|
|
189
|
+
throw new SourceError('upstream', 'Kilo returned invalid function calls');
|
|
190
|
+
ids.add(call.id);
|
|
191
|
+
calls.push({ id: call.id, type: 'function', function: { name: fn.name, arguments: fn.arguments } });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (!message.content && !calls.length)
|
|
195
|
+
throw new SourceError('upstream', 'Kilo returned an empty completion');
|
|
196
|
+
return { text: typeof message.content === 'string' ? message.content : '', ...(calls.length ? { calls } : {}), inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens };
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
if (caller.aborted || this.shutdown.signal.aborted)
|
|
200
|
+
throw new SourceError('cancelled', 'Kilo request cancelled');
|
|
201
|
+
if (signal.aborted)
|
|
202
|
+
throw new SourceError('timeout', 'Kilo request timed out');
|
|
203
|
+
if (error instanceof SourceError)
|
|
204
|
+
throw error;
|
|
205
|
+
throw new SourceError('upstream', 'Kilo request failed');
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
async close() { this.shutdown.abort(); await Promise.allSettled([...this.pending]); }
|
|
209
|
+
}
|
|
@@ -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
|
+
}
|