usegrunt 0.6.5 → 0.6.7

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,398 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { constants } from 'node:fs';
3
+ import { chmod, lstat, mkdir, mkdtemp, open, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { StringDecoder } from 'node:string_decoder';
9
+ import { Ajv } from 'ajv';
10
+ import { readDataSharingConsent } from './data-sharing.js';
11
+ import { providerGrantDirectory } from './provider-grant.js';
12
+ import { FreebuffTools } from './freebuff-tools.js';
13
+ import { SourceError } from './source.js';
14
+ export const CLIXAD_VERSION = '0.0.1-beta.51';
15
+ export const CLIXAD_MODEL = 'glm-5.3-flash';
16
+ export const CLIXAD_GATEWAY = 'https://clixad.onrender.com';
17
+ export const CLIXAD_DASHBOARD = 'https://app.clixad.io';
18
+ export const CLIXAD_INTEGRITY = 'sha512-dZMQxSglUJe/8ZKfw4BXvsD05CbhuTNlTb2IN9eQrZU58K4qdzijrGfTO0SY37MJcr9Yb3XBWb7xBdD1wVVgNQ==';
19
+ export const CLIXAD_TARBALL = `https://registry.npmjs.org/clixad/-/clixad-${CLIXAD_VERSION}.tgz`;
20
+ export const CLIXAD_CORE_SHA256 = {
21
+ 'clixad.mjs': '68ceee5bd62f7afd2f2850e5e38462b985d0798d6a5ce70c917be77506dc4929',
22
+ 'chunk-OPJ5LW6R.mjs': '8f80ef76188e72c2bb8400ed4897045eb6c68e81c49fc7376acdde84f061b401',
23
+ 'tui-NCLZGRMH.mjs': '92b69b5f79a73203b29a57c936ab1d6e257e5433e90b19fff6ce2fb0fa981c41'
24
+ };
25
+ export const CLIXAD_TIMEOUT_MS = 175000;
26
+ export function clixadPaths(directory = providerGrantDirectory()) {
27
+ const home = resolve(directory, 'clixad'), runtime = join(home, 'runtime'), pkg = join(runtime, 'node_modules', 'clixad');
28
+ return { home, runtime, package: pkg, entry: join(pkg, 'dist', 'clixad.mjs'), work: join(home, 'work'), installation: join(home, 'installation.json') };
29
+ }
30
+ const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
31
+ const missing = () => new SourceError('not_installed', 'Clixad private pinned CLI installation is missing or unsafe; rerun usegrunt setup');
32
+ async function privateDirectory(path, create = false) {
33
+ if (create)
34
+ await mkdir(path, { recursive: true, mode: 0o700 });
35
+ const stat = await lstat(path);
36
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
37
+ throw missing();
38
+ }
39
+ export async function prepareClixadDirectories(directory = providerGrantDirectory()) {
40
+ const paths = clixadPaths(directory);
41
+ for (const path of [paths.home, paths.runtime, paths.work])
42
+ await privateDirectory(path, true);
43
+ return paths;
44
+ }
45
+ function installation(value) {
46
+ const receipt = object(value);
47
+ if (receipt.version !== 1 || receipt.cliVersion !== CLIXAD_VERSION || receipt.integrity !== CLIXAD_INTEGRITY
48
+ || JSON.stringify(receipt.coreSha256) !== JSON.stringify(CLIXAD_CORE_SHA256))
49
+ throw missing();
50
+ return { version: 1, cliVersion: CLIXAD_VERSION, integrity: CLIXAD_INTEGRITY, coreSha256: CLIXAD_CORE_SHA256 };
51
+ }
52
+ export async function writeClixadInstallReceipt(directory = providerGrantDirectory()) {
53
+ const paths = await prepareClixadDirectories(directory), temporary = join(paths.home, `.installation-${randomUUID()}`);
54
+ try {
55
+ await writeFile(temporary, JSON.stringify(installation({ version: 1, cliVersion: CLIXAD_VERSION, integrity: CLIXAD_INTEGRITY, coreSha256: CLIXAD_CORE_SHA256 })), { flag: 'wx', mode: 0o600 });
56
+ await rename(temporary, paths.installation);
57
+ }
58
+ finally {
59
+ await rm(temporary, { force: true });
60
+ }
61
+ }
62
+ export async function readClixadInstallReceipt(directory = providerGrantDirectory()) {
63
+ let file;
64
+ try {
65
+ file = await open(clixadPaths(directory).installation, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
66
+ const stat = await file.stat();
67
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || stat.size > 4096)
68
+ throw missing();
69
+ return installation(JSON.parse(await file.readFile('utf8')));
70
+ }
71
+ catch {
72
+ throw missing();
73
+ }
74
+ finally {
75
+ await file?.close();
76
+ }
77
+ }
78
+ async function ready(directory) {
79
+ const paths = clixadPaths(directory);
80
+ for (const path of [paths.home, paths.runtime, paths.work])
81
+ await privateDirectory(path);
82
+ for (const path of [join(paths.runtime, 'node_modules'), paths.package, dirname(paths.entry)]) {
83
+ const stat = await lstat(path);
84
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o022))
85
+ throw missing();
86
+ }
87
+ await readClixadInstallReceipt(directory);
88
+ for (const [name, digest] of Object.entries(CLIXAD_CORE_SHA256)) {
89
+ let file;
90
+ try {
91
+ file = await open(join(dirname(paths.entry), name), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
92
+ const stat = await file.stat();
93
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o022) || stat.size > 1024 * 1024)
94
+ throw missing();
95
+ if (createHash('sha256').update(await file.readFile()).digest('hex') !== digest)
96
+ throw missing();
97
+ }
98
+ catch {
99
+ throw missing();
100
+ }
101
+ finally {
102
+ await file?.close();
103
+ }
104
+ }
105
+ // Native auth remains CLI-owned: only metadata is inspected by Grunt.
106
+ const native = join(homedir(), '.clixad');
107
+ try {
108
+ await privateDirectory(native);
109
+ const stat = await lstat(join(native, 'config.json'));
110
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || stat.size < 1 || stat.size > 65536)
111
+ throw new Error();
112
+ }
113
+ catch {
114
+ throw new SourceError('logged_out', 'Clixad native login is missing or unsafe; rerun usegrunt setup');
115
+ }
116
+ return paths;
117
+ }
118
+ export function clixadEnvironment() {
119
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(?:node_|node$|clixad_|grunt_clixad_|agent_cli_|cursor_|grok_)/i.test(key)
120
+ && !/(?:^|_)(?:api_key|auth_token|access_token|refresh_token|secret|secret_key|token)$/i.test(key)));
121
+ // Do not inject a gateway override: the native CLI then preserves its stored
122
+ // token-origin binding. The child preload rejects nonofficial destinations
123
+ // before fetch, rather than redirecting another profile's credentials.
124
+ return { ...env, CLIXAD_SPONSOR: '0', NO_COLOR: '1', FORCE_COLOR: '0' };
125
+ }
126
+ export const runClixadProcess = async (entry, mode, options) => {
127
+ options.signal.throwIfAborted();
128
+ if (!['linux', 'darwin'].includes(process.platform) || !isAbsolute(entry))
129
+ throw missing();
130
+ const nonce = randomBytes(16).toString('hex'), preload = fileURLToPath(new URL('./clixad-preload.js', import.meta.url));
131
+ return new Promise((resolveResult, reject) => {
132
+ const child = spawn(process.execPath, ['--import', preload, entry, mode], { cwd: options.cwd,
133
+ env: { ...options.env, GRUNT_CLIXAD_NONCE: nonce }, detached: true, stdio: ['pipe', 'pipe', 'pipe', 'ipc'] });
134
+ let stdout = '', bytes = 0, failure;
135
+ const events = [], decoder = new StringDecoder('utf8');
136
+ const stop = () => { if (child.pid) {
137
+ try {
138
+ process.kill(-child.pid, 'SIGKILL');
139
+ }
140
+ catch { /* Our owned process group only. */ }
141
+ } };
142
+ const fail = (error) => { failure ??= error; stop(); };
143
+ const deadline = setTimeout(() => fail(new SourceError('timeout', 'Clixad native command timed out')), CLIXAD_TIMEOUT_MS);
144
+ child.on('message', value => {
145
+ const item = object(value);
146
+ if (item.type !== 'grunt-clixad' || item.version !== 1 || item.nonce !== nonce || !['guard', 'http', 'wallet', 'dispatch', 'completion'].includes(String(item.event))
147
+ || JSON.stringify(item).length > 32768 || events.length >= 32) {
148
+ fail(new SourceError('refused', 'Clixad returned invalid native metadata'));
149
+ return;
150
+ }
151
+ const { type: _type, version: _version, nonce: _nonce, ...metadata } = item;
152
+ events.push(metadata);
153
+ if (item.event === 'guard')
154
+ fail(new SourceError('refused', 'Clixad attempted an unsupported native action or response'));
155
+ });
156
+ const consume = (chunk, capture) => {
157
+ bytes += chunk.length;
158
+ if (bytes > 2 * 1024 * 1024) {
159
+ fail(new SourceError('upstream', 'Clixad native output exceeded the supported size'));
160
+ return;
161
+ }
162
+ if (capture)
163
+ stdout += decoder.write(chunk);
164
+ };
165
+ child.stdout.on('data', (chunk) => consume(chunk, mode !== 'wallet'));
166
+ child.stderr.on('data', (chunk) => consume(chunk, false));
167
+ const abort = () => stop();
168
+ options.signal.addEventListener('abort', abort, { once: true });
169
+ if (options.signal.aborted)
170
+ stop();
171
+ child.stdin.on('error', () => { });
172
+ child.stdin.end(mode === 'ask' ? options.input : undefined);
173
+ child.once('error', () => fail(missing()));
174
+ child.once('close', code => {
175
+ clearTimeout(deadline);
176
+ options.signal.removeEventListener('abort', abort);
177
+ stop();
178
+ stdout += decoder.end();
179
+ if (options.signal.aborted)
180
+ reject(options.signal.reason);
181
+ else if (failure)
182
+ reject(failure);
183
+ else
184
+ resolveResult({ code, stdout, events });
185
+ });
186
+ });
187
+ };
188
+ async function abortable(task, signal) {
189
+ signal.throwIfAborted();
190
+ let abort;
191
+ try {
192
+ return await Promise.race([task, new Promise((_resolve, reject) => { abort = () => reject(signal.reason); signal.addEventListener('abort', abort, { once: true }); if (signal.aborted)
193
+ abort(); })]);
194
+ }
195
+ finally {
196
+ if (abort)
197
+ signal.removeEventListener('abort', abort);
198
+ }
199
+ }
200
+ async function boundedJSON(response, signal) {
201
+ if (!response.body || Number(response.headers.get('content-length')) > 1048576) {
202
+ void response.body?.cancel().catch(() => { });
203
+ throw new Error();
204
+ }
205
+ const reader = response.body.getReader(), chunks = [];
206
+ let bytes = 0;
207
+ try {
208
+ for (;;) {
209
+ const part = await abortable(reader.read(), signal);
210
+ signal.throwIfAborted();
211
+ if (part.done)
212
+ break;
213
+ bytes += part.value.byteLength;
214
+ if (bytes > 1048576)
215
+ throw new Error();
216
+ chunks.push(part.value);
217
+ }
218
+ return object(JSON.parse(Buffer.concat(chunks).toString('utf8')));
219
+ }
220
+ finally {
221
+ void reader.cancel().catch(() => { });
222
+ }
223
+ }
224
+ export async function verifyClixadPublicModel(options = {}) {
225
+ const signal = AbortSignal.any([...(options.signal ? [options.signal] : []), AbortSignal.timeout(5000)]);
226
+ try {
227
+ signal.throwIfAborted();
228
+ const response = await abortable((options.fetcher ?? fetch)(`${CLIXAD_GATEWAY}/v1/models`, { redirect: 'error', signal }), signal);
229
+ if (!response.ok) {
230
+ void response.body?.cancel().catch(() => { });
231
+ throw new Error();
232
+ }
233
+ const body = await boundedJSON(response, signal), rows = Array.isArray(body.data) ? body.data.filter(row => object(row).id === CLIXAD_MODEL) : [];
234
+ const model = object(rows.length === 1 ? rows[0] : undefined);
235
+ if (model.free !== true || model.auto_mode !== false || !Number.isSafeInteger(model.context_window) || Number(model.context_window) < 200000)
236
+ throw new SourceError('refused', 'Clixad GLM 5.3 Flash is not currently a fixed free model with at least 200K context');
237
+ }
238
+ catch (error) {
239
+ if (options.signal?.aborted)
240
+ throw options.signal.reason;
241
+ if (signal.aborted)
242
+ throw new SourceError('timeout', 'Clixad public catalog timed out');
243
+ if (error instanceof SourceError)
244
+ throw error;
245
+ throw new SourceError('upstream', 'Clixad public model metadata is unavailable');
246
+ }
247
+ }
248
+ function nativeErrors(result) {
249
+ if (result.events.some(event => event.event === 'guard'))
250
+ throw new SourceError('refused', 'Clixad attempted an unsupported native action or response');
251
+ const failed = result.events.find(event => event.event === 'http' && (typeof event.status !== 'number' || event.status < 200 || event.status >= 300));
252
+ if (failed)
253
+ throw new SourceError(failed.status === 401 ? 'logged_out' : [402, 429].includes(Number(failed.status)) ? 'quota' : failed.status === 403 ? 'refused' : 'upstream', 'Clixad native access is unavailable', failed.status === 429 ? 60 : undefined);
254
+ if (result.code !== 0)
255
+ throw new SourceError('upstream', 'Clixad native command did not complete');
256
+ }
257
+ function wallet(result, allowExhausted = false) {
258
+ nativeErrors(result);
259
+ const rows = result.events.filter(event => event.event === 'wallet'), state = object(rows.length === 1 ? rows[0] : undefined);
260
+ if (result.events.filter(event => event.event === 'http' && event.operation === 'wallet').length !== 1
261
+ || result.events.some(event => !['wallet', 'http'].includes(event.event) || event.event === 'http' && !['wallet', 'streak'].includes(String(event.operation)))
262
+ || state.balance !== 0 || state.modelEligible !== true || typeof state.dailyCredits !== 'number' || !Number.isFinite(state.dailyCredits) || state.dailyCredits <= 0
263
+ || typeof state.creditsLeft !== 'number' || !Number.isFinite(state.creditsLeft) || state.creditsLeft < 0)
264
+ throw new SourceError('refused', 'Clixad requires zero account balance and verified free GLM allowance');
265
+ if (!allowExhausted && state.creditsLeft <= 0)
266
+ throw new SourceError('quota', 'Clixad daily free allowance is exhausted');
267
+ }
268
+ async function nativeAccess(paths, runner, signal) {
269
+ const options = { cwd: paths.work, env: clixadEnvironment(), signal };
270
+ const pin = await abortable(runner(paths.entry, 'model', options), signal);
271
+ nativeErrors(pin);
272
+ if (pin.events.length || pin.stdout.trim() !== `current model: ${CLIXAD_MODEL}`)
273
+ throw new SourceError('refused', 'Clixad native model changed; select GLM 5.3 Flash explicitly in setup');
274
+ wallet(await abortable(runner(paths.entry, 'wallet', options), signal));
275
+ }
276
+ /** Called by explicit setup/user requests only: native wallet may claim its ordinary daily streak bonus. */
277
+ export async function verifyClixadAccess(options) {
278
+ const signal = AbortSignal.any([...(options.signal ? [options.signal] : []), AbortSignal.timeout(60000)]);
279
+ signal.throwIfAborted();
280
+ const paths = await ready(options.directory);
281
+ await verifyClixadPublicModel({ ...(options.fetcher ? { fetcher: options.fetcher } : {}), signal });
282
+ await nativeAccess(paths, options.runner ?? runClixadProcess, signal);
283
+ }
284
+ function bridgeFor(request) {
285
+ try {
286
+ const messages = [];
287
+ for (const message of request.messages) {
288
+ const previous = messages.at(-1);
289
+ if (message.role === 'assistant' && !message.content && message.tool_calls?.length && !message.tool_call_id
290
+ && previous?.role === 'assistant' && !previous.content && previous.tool_calls?.length && !previous.tool_call_id)
291
+ previous.tool_calls = [...previous.tool_calls, ...message.tool_calls];
292
+ else
293
+ messages.push({ ...message });
294
+ }
295
+ const ajv = new Ajv({ strict: true, strictTypes: false, strictTuples: false, addUsedSchema: false });
296
+ for (const tool of request.tools)
297
+ ajv.compile(object(tool.function).parameters);
298
+ return new FreebuffTools({ ...request, messages });
299
+ }
300
+ catch {
301
+ throw new SourceError('refused', 'Clixad rejected invalid function tools or an uncorrelated tool conversation');
302
+ }
303
+ }
304
+ export class Clixad {
305
+ options;
306
+ id = 'clixad';
307
+ supportsFunctionTools = true;
308
+ shutdown = new AbortController();
309
+ pending = new Set();
310
+ constructor(options = {}) {
311
+ this.options = options;
312
+ }
313
+ get directory() { return this.options.directory ?? providerGrantDirectory(); }
314
+ get runner() { return this.options.runner ?? runClixadProcess; }
315
+ async approved() { return (await readDataSharingConsent(this.directory, [this.id])).includes(this.id); }
316
+ async track(task) { this.pending.add(task); try {
317
+ return await task;
318
+ }
319
+ finally {
320
+ this.pending.delete(task);
321
+ } }
322
+ async available() {
323
+ return this.track((async () => {
324
+ try {
325
+ if (this.shutdown.signal.aborted || !await this.approved())
326
+ return false;
327
+ await ready(this.directory);
328
+ await verifyClixadPublicModel({ ...(this.options.fetcher ? { fetcher: this.options.fetcher } : {}), signal: this.shutdown.signal });
329
+ return !this.shutdown.signal.aborted;
330
+ }
331
+ catch {
332
+ return false;
333
+ }
334
+ })());
335
+ }
336
+ async healthCheck() { return this.available(); }
337
+ complete(request, caller) { return this.track(this.once(request, caller)); }
338
+ async once(request, caller) {
339
+ const timeout = this.options.timeout, signal = AbortSignal.any([caller, this.shutdown.signal, AbortSignal.timeout(typeof timeout === 'number' && Number.isFinite(timeout) && timeout > 0 ? Math.min(CLIXAD_TIMEOUT_MS, Math.ceil(timeout)) : CLIXAD_TIMEOUT_MS)]);
340
+ let temporary;
341
+ try {
342
+ signal.throwIfAborted();
343
+ if (request.imageInput)
344
+ throw new SourceError('refused', 'Clixad supports text inputs through this route');
345
+ if (request.maxTokens !== undefined && (!Number.isSafeInteger(request.maxTokens) || request.maxTokens < 1))
346
+ throw new SourceError('refused', 'Clixad requires a positive integer output-token budget');
347
+ const limit = Math.min(4096, request.maxTokens ?? 4096), bridge = bridgeFor(request);
348
+ if (!await this.approved())
349
+ throw new SourceError('refused', 'Clixad data sharing is not approved; rerun usegrunt setup');
350
+ // This bounds returned output and observed usage only. The native CLI has
351
+ // no hard upstream generation cap and can consume allowance before rejection.
352
+ const prompt = `Your total output budget, including reasoning and the JSON envelope, is ${limit} tokens. Use no native tools, commands, files, web, MCP or subagents.\n`
353
+ + bridge.prompt() + '\nThis request is transparently routed by Grunt using Clixad ask. Only the external caller executes the advertised functions.';
354
+ if (Buffer.byteLength(prompt) > 2 * 1024 * 1024)
355
+ throw new SourceError('refused', 'Clixad prompt exceeds the supported input size');
356
+ const paths = await ready(this.directory);
357
+ signal.throwIfAborted();
358
+ await verifyClixadPublicModel({ ...(this.options.fetcher ? { fetcher: this.options.fetcher } : {}), signal });
359
+ await nativeAccess(paths, this.runner, signal);
360
+ temporary = await mkdtemp(join(paths.work, 'request-'));
361
+ await chmod(temporary, 0o700);
362
+ const native = await abortable(this.runner(paths.entry, 'ask', { cwd: temporary, env: clixadEnvironment(), signal, input: prompt }), signal);
363
+ nativeErrors(native);
364
+ const dispatch = native.events.filter(event => event.event === 'dispatch'), metadata = native.events.filter(event => event.event === 'completion');
365
+ const observed = object(metadata.length === 1 ? metadata[0] : undefined);
366
+ if (native.events.filter(event => event.event === 'http' && event.operation === 'chat').length !== 1
367
+ || native.events.some(event => !['dispatch', 'http', 'completion'].includes(event.event) || event.event === 'http' && event.operation !== 'chat')
368
+ || dispatch.length !== 1 || dispatch[0].model !== CLIXAD_MODEL || observed.free !== true || observed.creditsCharged !== 0 || observed.balance !== 0
369
+ || !Number.isSafeInteger(observed.inputTokens) || Number(observed.inputTokens) < 1 || !Number.isSafeInteger(observed.outputTokens) || Number(observed.outputTokens) < 1
370
+ || Number(observed.outputTokens) > limit || (observed.returnedModel !== undefined && observed.returnedModel !== CLIXAD_MODEL))
371
+ throw new SourceError('refused', 'Clixad returned missing, nonfree, mismatched or over-budget native metadata');
372
+ wallet(await abortable(this.runner(paths.entry, 'wallet', { cwd: paths.work, env: clixadEnvironment(), signal }), signal), true);
373
+ const match = native.stdout.match(/^assistant ([\s\S]*?)\n\s*\[0 credits · balance 0\]\s*$/);
374
+ if (!match || Buffer.byteLength(match[1]) > 65536)
375
+ throw new SourceError('upstream', 'Clixad returned invalid native answer framing');
376
+ try {
377
+ return { ...bridge.parse(match[1]), inputTokens: observed.inputTokens, outputTokens: observed.outputTokens };
378
+ }
379
+ catch {
380
+ throw new SourceError('upstream', 'Clixad JSON function protocol failed validation');
381
+ }
382
+ }
383
+ catch (error) {
384
+ if (caller.aborted || this.shutdown.signal.aborted)
385
+ throw new SourceError('cancelled', 'Clixad request cancelled');
386
+ if (signal.aborted)
387
+ throw new SourceError('timeout', 'Clixad request timed out');
388
+ if (error instanceof SourceError)
389
+ throw error;
390
+ throw new SourceError('upstream', 'Clixad request failed; rerun setup if native access needs repair');
391
+ }
392
+ finally {
393
+ if (temporary)
394
+ await rm(temporary, { recursive: true, force: true });
395
+ }
396
+ }
397
+ async close() { this.shutdown.abort(); await Promise.allSettled([...this.pending]); }
398
+ }
@@ -15,8 +15,8 @@ export const DATA_SHARING_POLICIES = [{
15
15
  disclosure: 'DeepSeek and GLM free routes have zero-retention and no-training policies. The pool also includes Big Pickle, whose collected data may be used for model improvement.',
16
16
  url: 'https://opencode.ai/docs/console/models/#privacy'
17
17
  }, {
18
- provider: 'kilo', name: 'Kilo Auto Free', version: '2026-11-15',
19
- disclosure: 'Auto Free may select providers that log prompts and outputs and use them to improve their services. Do not submit personal or confidential data.',
18
+ provider: 'kilo', name: 'Kilo Particle-1 Free', version: '2026-11-15-particle',
19
+ disclosure: 'Particle-1 prompts and outputs pass through Kilo and Particle AI. The live catalog permits training on prompts; retention and staff-review guarantees are not established. Do not submit personal or confidential data.',
20
20
  url: 'https://kilo.ai/docs/getting-started/using-kilo-for-free'
21
21
  }, {
22
22
  provider: 'tokenharbor', name: 'Token Harbor', version: '2026-11-15',
@@ -34,6 +34,22 @@ export const DATA_SHARING_POLICIES = [{
34
34
  provider: 'mistral-vibe', name: 'Mistral Vibe Free (GLM 5.3 Flash)', version: '2026-11-15',
35
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
36
  url: 'https://legal.mistral.ai/terms/privacy-policy'
37
+ }, {
38
+ provider: 'pollinations', name: 'Pollinations community GLM 5.3 Flash', version: '2026-11-15',
39
+ disclosure: 'Prompts and project context pass through Pollinations, the OSAII community operator, and Poe/Together upstream processing. Retention, staff review, and training guarantees are not established for these intermediaries.',
40
+ url: 'https://pollinations.ai/privacy'
41
+ }, {
42
+ provider: 'beatapi', name: 'BeatAPI free model pool', version: '2026-11-15',
43
+ disclosure: 'Prompts and project context may be retained for operations and processed by upstream providers. BeatAPI states that private content is not used for training without separate notice and consent where required; upstream retention and training guarantees are not established.',
44
+ url: 'https://beatapi.io/privacy-policy'
45
+ }, {
46
+ provider: 'clixad', name: 'Clixad GLM 5.3 Flash', version: '2026-11-15',
47
+ disclosure: 'Prompts, code and tool results pass through Clixad, OpenRouter and model providers. Clixad records usage metadata and says it stores content only when an answer is rated; it excludes training and public-dataset endpoints but does not require zero retention from upstream providers. Grunt does not submit ratings or offers, and uses the documented noninteractive sponsor opt-out.',
48
+ url: 'https://clixad.io/privacy.html'
49
+ }, {
50
+ provider: 'perch', name: 'Perch Starter DeepSeek', version: '2026-11-15',
51
+ disclosure: 'Prompts, code and tool context are processed by Perch and its inference providers. The optional Starter Data Program must remain off. Setup turns off the account settings Use memory and Learn new memories without deleting saved notes; both must remain off for routing. Operational processing for service delivery, security, debugging and metering remains; retention and review limits and zero-retention coverage have not been independently verified.',
52
+ url: 'https://www.perchai.app/privacy#starter-data-program'
37
53
  }];
38
54
  const fileName = 'data-sharing-consent.json';
39
55
  const emptyReceipt = () => ({ version: 1, approved: {} });
@@ -3,11 +3,13 @@ import { promisify } from 'node:util';
3
3
  import { mkdir, writeFile, access } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { BrowserSquire, setup } from './setup.js';
6
- import { parallelMap } from './parallel.js';
6
+ import { parallelMap, SETUP_CONCURRENCY } from './parallel.js';
7
+ import { disabledAdapters } from '../registry.js';
7
8
  import { OpenCode } from './opencode.js';
8
9
  import { DOCTOR_TIMEOUT_MS } from './freebuff.js';
9
10
  import { SourceError, Sources } from './source.js';
10
11
  import { DATA_SHARING_POLICIES, readDataSharingConsent, requiresDataSharing } from './data-sharing.js';
12
+ import { ClixadNativeLoginRequired } from './clixad-setup.js';
11
13
  const exec = promisify(execFile);
12
14
  class FreebuffCompatibilityError extends Error {
13
15
  }
@@ -65,8 +67,14 @@ export async function verifyOpenCode(source = new OpenCode(), signal = AbortSign
65
67
  export async function setupFallbacks(options) {
66
68
  const squire = options.squire ?? new BrowserSquire({ dataSharingApproved: options.dataSharingApproved ?? [] });
67
69
  const owned = squire instanceof BrowserSquire && !options.squire;
68
- const unavailable = [];
69
- const adapters = options.adapters ?? ['freebuff', 'opencode'];
70
+ const requested = [...new Set(options.adapters ?? ['opencode'])];
71
+ // A registry may list account-based providers first. Keep their shared
72
+ // browser login from occupying every worker before anonymous routes start.
73
+ const anonymous = ['kilo', 'opencode'];
74
+ const execution = [...anonymous.filter(id => requested.includes(id)), ...requested.filter(id => !anonymous.includes(id))];
75
+ const unavailable = requested.filter(id => disabledAdapters.has(id));
76
+ for (const id of unavailable)
77
+ options.notify(`${id}: routing is disabled; other free services continue`);
70
78
  const approved = [...new Set([...(options.dataSharingApproved ?? []), ...await readDataSharingConsent(options.directory, DATA_SHARING_POLICIES.map(policy => policy.provider))])];
71
79
  if (squire instanceof BrowserSquire)
72
80
  squire.approveDataSharing(approved);
@@ -93,6 +101,16 @@ export async function setupFallbacks(options) {
93
101
  await options.run('npm', ['install', '--global', pkg]);
94
102
  }
95
103
  };
104
+ const settled = new Set(), callbacks = [], callbackFailures = [];
105
+ const onSettled = (id, available) => {
106
+ if (!options.onSettled || settled.has(id))
107
+ return;
108
+ settled.add(id);
109
+ // Observers may verify the daemon or configure coding tools. Start that
110
+ // work immediately without holding a provider worker or rejecting early.
111
+ callbacks.push(Promise.resolve().then(() => options.onSettled(id, available && !options.signal?.aborted))
112
+ .catch(error => { callbackFailures.push(error); }));
113
+ };
96
114
  options.notify('Free routes run their own tools with your filesystem permissions in the working directory. Free model providers may retain prompts.');
97
115
  try {
98
116
  const tasks = {
@@ -191,11 +209,8 @@ export async function setupFallbacks(options) {
191
209
  },
192
210
  kilo: async () => {
193
211
  try {
194
- await connect();
195
- if (!squire.runs)
196
- throw new Error('Provider signup requires Squire');
197
212
  await (options.setupProvider ?? setup)(options.notify, ['kilo'], { squire: squire, directory: options.directory, dataSharingApproved: approved, ...(options.signal ? { signal: options.signal } : {}) });
198
- options.notify('Kilo: free API access connected through Squire');
213
+ options.notify('Kilo: free Particle-1 access verified without signup');
199
214
  }
200
215
  catch {
201
216
  unavailable.push('kilo');
@@ -243,20 +258,6 @@ export async function setupFallbacks(options) {
243
258
  options.notify('Runcrate free setup incomplete. GitHub must be at least 30 days old; rerun usegrunt setup to resume. Other routes remain available.');
244
259
  }
245
260
  },
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
261
  'mistral-vibe': async () => {
261
262
  try {
262
263
  await connect();
@@ -281,6 +282,58 @@ export async function setupFallbacks(options) {
281
282
  options.notify('LiveKit free Build signup or native CLI pairing incomplete. Rerun usegrunt setup; other routes remain available.');
282
283
  }
283
284
  },
285
+ pollinations: async () => {
286
+ try {
287
+ if (!options.background)
288
+ await connect();
289
+ await (options.setupProvider ?? setup)(options.notify, ['pollinations'], { squire: squire, directory: options.directory,
290
+ background: options.background ?? false, dataSharingApproved: approved, ...(options.signal ? { signal: options.signal } : {}) });
291
+ options.notify('Pollinations: community GLM 5.3 Flash access connected through Squire');
292
+ }
293
+ catch {
294
+ unavailable.push('pollinations');
295
+ options.notify('Pollinations free setup incomplete. Rerun usegrunt setup to resume; other routes remain available.');
296
+ }
297
+ },
298
+ beatapi: async () => {
299
+ try {
300
+ if (!options.background)
301
+ await connect();
302
+ await (options.setupProvider ?? setup)(options.notify, ['beatapi'], { squire: squire, directory: options.directory,
303
+ background: options.background ?? false, dataSharingApproved: approved, ...(options.signal ? { signal: options.signal } : {}) });
304
+ options.notify('BeatAPI: free DeepSeek V4.1 Flash access connected through Squire');
305
+ }
306
+ catch {
307
+ unavailable.push('beatapi');
308
+ options.notify('BeatAPI free setup incomplete. Rerun usegrunt setup to resume; other routes remain available.');
309
+ }
310
+ },
311
+ clixad: async () => {
312
+ try {
313
+ if (!options.background)
314
+ await connect();
315
+ await (options.setupProvider ?? setup)(options.notify, ['clixad'], { squire: squire, directory: options.directory,
316
+ background: options.background ?? false, dataSharingApproved: approved, ...(options.signal ? { signal: options.signal } : {}) });
317
+ options.notify('Clixad: free GLM 5.3 Flash access connected');
318
+ }
319
+ catch (error) {
320
+ unavailable.push('clixad');
321
+ options.notify(error instanceof ClixadNativeLoginRequired ? error.message : 'Clixad setup needs attention. Rerun usegrunt setup; other free routes continue.');
322
+ }
323
+ },
324
+ perch: async () => {
325
+ try {
326
+ if (!options.background)
327
+ await connect();
328
+ await (options.setupProvider ?? setup)(options.notify, ['perch'], { squire: squire, directory: options.directory,
329
+ background: options.background ?? false, dataSharingApproved: approved, ...(options.signal ? { signal: options.signal } : {}) });
330
+ options.notify('Perch: Starter DeepSeek access connected with optional data sharing and account memory off');
331
+ }
332
+ catch {
333
+ unavailable.push('perch');
334
+ options.notify('Perch Starter setup needs attention. Rerun usegrunt setup; other free routes continue.');
335
+ }
336
+ },
284
337
  nvidia: async () => {
285
338
  try {
286
339
  await connect();
@@ -295,19 +348,45 @@ export async function setupFallbacks(options) {
295
348
  }
296
349
  }
297
350
  };
298
- await parallelMap(adapters, async (id) => {
299
- if (requiresDataSharing(id) && !approved.includes(id)) {
300
- unavailable.push(id);
301
- options.notify(`${id}: skipped until the grouped data-sharing approval is granted`);
302
- return;
303
- }
304
- const task = tasks[id];
305
- if (!task)
306
- throw new Error('Unsupported vetted adapter');
307
- await task();
308
- }, 3, options.signal);
351
+ let failure;
352
+ try {
353
+ await parallelMap(execution, async (id) => {
354
+ let available = false;
355
+ try {
356
+ if (disabledAdapters.has(id))
357
+ return;
358
+ if (requiresDataSharing(id) && !approved.includes(id)) {
359
+ unavailable.push(id);
360
+ options.notify(`${id}: skipped until the grouped data-sharing approval is granted`);
361
+ return;
362
+ }
363
+ const task = tasks[id];
364
+ if (!task)
365
+ throw new Error('Unsupported vetted adapter');
366
+ await task();
367
+ available = !unavailable.includes(id);
368
+ }
369
+ finally {
370
+ onSettled(id, available);
371
+ }
372
+ }, SETUP_CONCURRENCY, options.signal);
373
+ }
374
+ catch (error) {
375
+ failure = { error };
376
+ }
377
+ finally {
378
+ // Cancellation can leave queued providers unstarted. Settle those as
379
+ // unavailable and keep the shared client alive until observers finish.
380
+ for (const id of requested)
381
+ onSettled(id, false);
382
+ await Promise.all(callbacks);
383
+ }
384
+ if (failure)
385
+ throw failure.error;
309
386
  options.signal?.throwIfAborted();
310
- return { unavailable: adapters.filter(id => unavailable.includes(id)) };
387
+ if (callbackFailures.length)
388
+ throw callbackFailures[0];
389
+ return { unavailable: requested.filter(id => unavailable.includes(id)) };
311
390
  }
312
391
  finally {
313
392
  if (owned && connection)
@@ -22,7 +22,11 @@ function logError(log) {
22
22
  const line = log.split('\n').find(line => /prompt_policy_refused|logged.?out|unauthorized|login required|not signed in|"code"\s*:\s*"quota"|quota[ _-](?:exceeded|exhausted|reached)|free[ _-]?hours.*(?:exhaust|exceed|empty)|(?:out of|no) free hours/i.test(line));
23
23
  if (!line)
24
24
  return;
25
- return new SourceError(/prompt_policy_refused/.test(line) ? 'refused' : /quota|hours/i.test(line) ? 'quota' : 'logged_out', `Freebuff: ${line}`);
25
+ if (/prompt_policy_refused/.test(line))
26
+ return new SourceError('refused', 'Freebuff refused this request under its usage policy');
27
+ if (/quota|hours/i.test(line))
28
+ return new SourceError('quota', 'Freebuff free-hours allowance is exhausted');
29
+ return new SourceError('logged_out', 'Freebuff login is unavailable; rerun setup');
26
30
  }
27
31
  // A request starts a fresh process; slots bound parallel sessions for each canonical cwd.
28
32
  class Pool {