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.
@@ -15,16 +15,24 @@ import { freeConfig, loopback } from './freellmapi.js';
15
15
  import { proxyApproval } from './approval-proxy.js';
16
16
  import { VerificationQueue } from './verification-queue.js';
17
17
  import { withTerminal } from './terminal.js';
18
+ import { BROWSER_CONCURRENCY } from './parallel.js';
18
19
  import { Nvidia, writeNvidiaGrant } from './nvidia.js';
19
20
  import { Zro, writeZroGrant } from './zro.js';
20
21
  import { TokenHarbor, writeTokenHarborGrant } from './tokenharbor.js';
21
22
  import { Runcrate, writeRuncrateGrant } from './runcrate.js';
22
23
  import { Apinex, writeApinexGrant } from './apinex.js';
23
24
  import { setupMistralVibe } from './mistral-vibe-setup.js';
25
+ import { setupLiveKit } from './livekit-setup.js';
26
+ import { setupPollinations } from './pollinations-setup.js';
27
+ import { setupBeatAPI } from './beatapi-setup.js';
28
+ import { setupClixad } from './clixad-setup.js';
29
+ import { setupPerch } from './perch-setup.js';
30
+ import { disabledAdapters } from '../registry.js';
31
+ import { KILO_PARTICLE, verifyKiloAccess } from './kilo.js';
24
32
  import { DATA_SHARING_POLICIES, dataSharingPolicies, readDataSharingConsent } from './data-sharing.js';
25
33
  const exec = promisify(execFile);
26
34
  export const FREELLMAPI_IMAGE = 'ghcr.io/tashfeenahmed/freellmapi@sha256:845a4b568a20fffd5112e1b9c0258e7782d9eabbba2430612d2f7c811eee267e';
27
- export const PROVIDERS = { groq: 'https://console.groq.com/keys', cerebras: 'https://cloud.cerebras.ai/platform/api-keys', kilo: 'https://app.kilo.ai/profile', nvidia: 'https://build.nvidia.com/settings/api-keys', zro: 'https://zro.moonmath.ai/overview', tokenharbor: 'https://tokenharbor.ai/dashboard', runcrate: 'https://www.runcrate.ai/auth/signup', apinex: 'https://apinex.bond/register', 'mistral-vibe': 'https://console.mistral.ai' };
35
+ export const PROVIDERS = { groq: 'https://console.groq.com/keys', cerebras: 'https://cloud.cerebras.ai/platform/api-keys', kilo: 'https://app.kilo.ai/profile', nvidia: 'https://build.nvidia.com/settings/api-keys', zro: 'https://zro.moonmath.ai/overview', tokenharbor: 'https://tokenharbor.ai/dashboard', runcrate: 'https://www.runcrate.ai/auth/signup', apinex: 'https://apinex.bond/register', 'mistral-vibe': 'https://console.mistral.ai', livekit: 'https://cloud.livekit.io', pollinations: 'https://enter.pollinations.ai', beatapi: 'https://beatapi.io', clixad: 'https://app.clixad.io', perch: 'https://www.perchai.app' };
28
36
  const freeProviderInstructions = {
29
37
  runcrate: ' Verify that the GitHub account is at least 30 days old. Use the normal Get your free tokens link at https://www.runcrate.ai/dashboard/api-keys#free-card to activate its recurring weekly allowance; verify the free tier is active via GitHub and not paused. Leave optional marketing unchecked. Verify no paid subscription, no purchased balance, no payment method and automatic top-ups disabled. If any of these checks fails, stop and report it; do not change billing settings or create another account. Use only deepseek-ai/DeepSeek-V4.1-Flash at api.runcrate.ai. Capture the API key with api_hosts ["api.runcrate.ai"] and auth_shape "bearer", service runcrate, label grunt. Reuse an existing vaulted key where possible; never reset or rotate it.',
30
38
  apinex: ' Verify the Free plan and complete today\'s ordinary DAILY CHECK-IN to activate recurring free quota. Use the personal @gmail.com Google identity already connected to Squire; do not choose a workspace identity or switch accounts. Use only free/deepseek-v4.1-flash at api.apinex.bond, never a wallet-funded model or paid sibling. Verify the check-in for the current UTC date is actually claimed and free quota is active; absence of a check-in modal alone is insufficient. Do not use or change any existing paid wallet balance. Dismiss any paid upsell after check-in. Do not add billing, top up a wallet, buy credits, or use any paid balance. If check-in or free access cannot be confirmed, stop and report it. Capture the API key with api_hosts ["api.apinex.bond"] and auth_shape "bearer", service apinex, label grunt. Reuse an existing vaulted key; never reset or rotate it.'
@@ -32,7 +40,7 @@ const freeProviderInstructions = {
32
40
  export const KILO_NEMOTRON = 'nvidia/nemotron-3-ultra-550b-a55b:free';
33
41
  export { NVIDIA_DEEPSEEK } from './nvidia.js';
34
42
  const savedProviders = ['kilo'];
35
- const providerModels = { kilo: [KILO_NEMOTRON, 'kilo-auto/free'] };
43
+ const providerModels = { kilo: [KILO_PARTICLE] };
36
44
  const sameService = (credential, service) => credential.service?.trim().toLowerCase() === service.trim().toLowerCase();
37
45
  function apiKeyField(credential, provider) {
38
46
  return credential.field_names.find(field => {
@@ -159,6 +167,13 @@ export class BrowserSquire {
159
167
  approveDataSharing(providers) { this.options.dataSharingApproved = [...new Set(providers)]; }
160
168
  client = new Client({ name: 'grunt setup', version: '0.1.0' });
161
169
  sessions = new Map();
170
+ services = new Map();
171
+ callSignals = new WeakMap();
172
+ queueSignals = new WeakMap();
173
+ browserActive = 0;
174
+ browserQueue = [];
175
+ initialDriveSignal = new AbortController().signal;
176
+ finishing = new Map();
162
177
  recoveryChoices = new Map();
163
178
  pending = new Set();
164
179
  closed = false;
@@ -169,15 +184,133 @@ export class BrowserSquire {
169
184
  metadata;
170
185
  grants = new Map();
171
186
  verification = new VerificationQueue(items => withTerminal(async () => {
172
- this.signal.throwIfAborted();
173
- for (const item of items)
174
- console.log(`Complete ${item.service} verification in this browser: ${item.url}`);
175
187
  const { confirm, isCancel } = await import('@clack/prompts');
176
- const done = await confirm({ message: `Finished verification for ${items.map(item => item.service).join(', ')}? Resume setup.`, initialValue: true, signal: this.signal });
177
- if (isCancel(done) || !done)
178
- throw new Error('Provider verification cancelled');
179
- this.signal.throwIfAborted();
188
+ for (;;) {
189
+ this.signal.throwIfAborted();
190
+ const active = items.filter(item => !this.serviceSignal(item.service).aborted);
191
+ if (!active.length)
192
+ return;
193
+ const prompt = new AbortController();
194
+ const signals = active.map(item => this.serviceSignal(item.service));
195
+ const changed = () => prompt.abort();
196
+ for (const signal of signals)
197
+ signal.addEventListener('abort', changed, { once: true });
198
+ try {
199
+ for (const item of active) {
200
+ console.log(`Complete ${item.service} verification in this browser: ${item.url}`);
201
+ if (item.goal)
202
+ console.log(`${item.service} requested goal; verify every condition before confirming:\n${item.goal}`);
203
+ }
204
+ const attest = active.some(item => item.goal !== undefined);
205
+ const message = attest
206
+ ? `I personally verified ALL conditions in each full requested goal displayed above (${active.filter(item => item.goal !== undefined).map(item => item.service).join(', ')}), and completed any other listed verification. Confirm these goals are complete?`
207
+ : `Finished verification for ${active.map(item => item.service).join(', ')}? Resume setup.`;
208
+ const done = await this.scoped(confirm({ message, initialValue: !attest, signal: prompt.signal }), prompt.signal);
209
+ this.signal.throwIfAborted();
210
+ if (signals.some(signal => signal.aborted))
211
+ continue;
212
+ if (isCancel(done) || !done)
213
+ throw new Error('Provider verification cancelled');
214
+ return;
215
+ }
216
+ catch (error) {
217
+ this.signal.throwIfAborted();
218
+ if (!signals.some(signal => signal.aborted))
219
+ throw error;
220
+ }
221
+ finally {
222
+ for (const signal of signals)
223
+ signal.removeEventListener('abort', changed);
224
+ }
225
+ }
180
226
  }));
227
+ serviceSignal(provider) {
228
+ let controller = this.services.get(provider);
229
+ if (!controller) {
230
+ controller = new AbortController();
231
+ this.services.set(provider, controller);
232
+ }
233
+ return AbortSignal.any([this.signal, controller.signal]);
234
+ }
235
+ async scoped(promise, signal) {
236
+ let abort;
237
+ try {
238
+ return await Promise.race([promise, new Promise((_resolve, reject) => {
239
+ abort = () => reject(new Error('Provider signup cancelled'));
240
+ signal.addEventListener('abort', abort, { once: true });
241
+ if (signal.aborted)
242
+ abort();
243
+ })]);
244
+ }
245
+ finally {
246
+ if (abort)
247
+ signal.removeEventListener('abort', abort);
248
+ }
249
+ }
250
+ async serviceCall(provider, name, args) {
251
+ this.serviceSignal(provider).throwIfAborted();
252
+ // Cancelling MCP before a first response discards its new session ID.
253
+ // Let that one bounded create/drive finish, then close any late session.
254
+ // Known-session calls can be aborted immediately and cleaned up by ID.
255
+ const initial = name === 'operate_drive' && !args.session_id;
256
+ this.callSignals.set(args, initial ? this.initialDriveSignal : this.serviceSignal(provider));
257
+ // Waiting work must remain cancellable even when its eventual first RPC
258
+ // needs to retain a late response containing the owned browser session ID.
259
+ this.queueSignals.set(args, this.serviceSignal(provider));
260
+ try {
261
+ return await this.call(name, args);
262
+ }
263
+ finally {
264
+ this.callSignals.delete(args);
265
+ this.queueSignals.delete(args);
266
+ }
267
+ }
268
+ async browserSlot(signal) {
269
+ signal.throwIfAborted();
270
+ const release = () => {
271
+ let released = false;
272
+ return () => {
273
+ if (released)
274
+ return;
275
+ released = true;
276
+ this.browserActive--;
277
+ this.browserQueue.shift()?.grant();
278
+ };
279
+ };
280
+ if (this.browserActive < BROWSER_CONCURRENCY) {
281
+ this.browserActive++;
282
+ return release();
283
+ }
284
+ return new Promise((resolve, reject) => {
285
+ const entry = { grant: () => {
286
+ signal.removeEventListener('abort', cancelled);
287
+ this.browserActive++;
288
+ resolve(release());
289
+ } };
290
+ const cancelled = () => {
291
+ const index = this.browserQueue.indexOf(entry);
292
+ if (index !== -1)
293
+ this.browserQueue.splice(index, 1);
294
+ signal.removeEventListener('abort', cancelled);
295
+ reject(new Error('Provider signup cancelled'));
296
+ };
297
+ this.browserQueue.push(entry);
298
+ signal.addEventListener('abort', cancelled, { once: true });
299
+ if (signal.aborted)
300
+ cancelled();
301
+ });
302
+ }
303
+ async cancelSignup(provider) {
304
+ let controller = this.services.get(provider);
305
+ if (!controller) {
306
+ controller = new AbortController();
307
+ this.services.set(provider, controller);
308
+ }
309
+ controller.abort(new Error('Provider signup cancelled'));
310
+ for (const handoff of this.handoffs.filter(item => item.provider === provider))
311
+ handoff.close();
312
+ await this.finishSession(provider);
313
+ }
181
314
  connect() {
182
315
  return this.connection ??= this.connectOnce().catch(error => { this.connection = undefined; throw error; });
183
316
  }
@@ -222,27 +355,39 @@ export class BrowserSquire {
222
355
  }
223
356
  }
224
357
  async call(name, args, connectionCheck = false) {
225
- const result = await this.client.callTool({ name, arguments: args }, undefined, { timeout: name === 'operate_finish' ? 10000 : 60000, ...(name === 'operate_finish' ? {} : { signal: this.signal }) }).catch(error => {
226
- if (connectionCheck)
227
- throw error;
228
- throw new Error(`Squire ${name} is unavailable; resume setup after reconnecting Squire`);
229
- });
230
- if (result.isError) {
231
- const reason = connectionCheck ? result.content
232
- .filter(part => part.type === 'text').map(part => part.text ?? '').join(' ') : '';
233
- throw new Error(reason || `Squire ${name} failed; inspect Squire for the required action`);
234
- }
235
- if (result.structuredContent)
236
- return object(result.structuredContent);
237
- for (const part of result.content) {
238
- if (part.type === 'text' && part.text) {
239
- try {
240
- return object(JSON.parse(part.text));
358
+ const provider = typeof args.service === 'string' ? args.service
359
+ : [...this.sessions].find(([, id]) => id === args.session_id)?.[0];
360
+ const queueSignal = this.queueSignals.get(args) ?? (provider ? this.serviceSignal(provider) : this.signal);
361
+ const release = name === 'operate_drive' || name === 'operate_start' ? await this.browserSlot(queueSignal) : undefined;
362
+ try {
363
+ // A slot can be granted just before cancellation. Recheck before dispatch.
364
+ if (release)
365
+ queueSignal.throwIfAborted();
366
+ const result = await this.client.callTool({ name, arguments: args }, undefined, { timeout: name === 'operate_finish' ? 10000 : 60000, ...(name === 'operate_finish' ? {} : { signal: this.callSignals.get(args) ?? queueSignal }) }).catch(error => {
367
+ if (connectionCheck)
368
+ throw error;
369
+ throw new Error(`Squire ${name} is unavailable; resume setup after reconnecting Squire`);
370
+ });
371
+ if (result.isError) {
372
+ const reason = connectionCheck ? result.content
373
+ .filter(part => part.type === 'text').map(part => part.text ?? '').join(' ') : '';
374
+ throw new Error(reason || `Squire ${name} failed; inspect Squire for the required action`);
375
+ }
376
+ if (result.structuredContent)
377
+ return object(result.structuredContent);
378
+ for (const part of result.content) {
379
+ if (part.type === 'text' && part.text) {
380
+ try {
381
+ return object(JSON.parse(part.text));
382
+ }
383
+ catch { /* Do not echo upstream output. */ }
241
384
  }
242
- catch { /* Do not echo upstream output. */ }
243
385
  }
386
+ throw new Error(`Squire ${name} returned an unsupported result`);
387
+ }
388
+ finally {
389
+ release?.();
244
390
  }
245
- throw new Error(`Squire ${name} returned an unsupported result`);
246
391
  }
247
392
  credentials = {
248
393
  list: async () => {
@@ -274,20 +419,34 @@ export class BrowserSquire {
274
419
  const id = this.sessions.get(provider);
275
420
  if (!id)
276
421
  return;
422
+ const existing = this.finishing.get(id);
423
+ if (existing)
424
+ return existing;
425
+ const pending = (async () => {
426
+ try {
427
+ await this.call('operate_finish', { session_id: id, outcome: completed ? 'result' : 'none',
428
+ ...(completed ? { summary: 'grunt provider key stored in user vault' } : {}) });
429
+ if (this.sessions.get(provider) === id)
430
+ this.sessions.delete(provider);
431
+ this.recoveryChoices.delete(provider);
432
+ for (const handoff of this.handoffs.filter(item => item.provider === provider))
433
+ handoff.close();
434
+ }
435
+ catch { /* Preserve the original error; close retries a failed cleanup. */ }
436
+ })();
437
+ this.finishing.set(id, pending);
277
438
  try {
278
- await this.call('operate_finish', { session_id: id, outcome: completed ? 'result' : 'none',
279
- ...(completed ? { summary: 'grunt provider key stored in user vault' } : {}) });
280
- if (this.sessions.get(provider) === id)
281
- this.sessions.delete(provider);
282
- this.recoveryChoices.delete(provider);
439
+ await pending;
440
+ }
441
+ finally {
442
+ this.finishing.delete(id);
283
443
  }
284
- catch { /* Preserve the original error; close retries a failed cleanup. */ }
285
444
  }
286
445
  async signup(service, url, goal) {
287
446
  const deadline = Date.now() + 600000;
288
447
  try {
289
448
  while (Date.now() < deadline) {
290
- this.signal.throwIfAborted();
449
+ this.serviceSignal(service).throwIfAborted();
291
450
  const result = await this.drive(service, url, goal);
292
451
  if (result.run.state === 'completed')
293
452
  return;
@@ -303,33 +462,32 @@ export class BrowserSquire {
303
462
  async drive(provider, url = PROVIDERS[provider], goal) {
304
463
  if (this.closed)
305
464
  throw new Error('Squire setup is closed');
306
- const pending = this.driveOnce(provider, url, goal);
465
+ const pending = this.driveOnce(provider, url, goal).catch(async (error) => { await this.finishSession(provider); throw error; });
307
466
  this.pending.add(pending);
467
+ void pending.then(() => this.pending.delete(pending), () => this.pending.delete(pending));
308
468
  try {
309
- return await pending;
469
+ return await this.scoped(pending, this.serviceSignal(provider));
310
470
  }
311
471
  catch (error) {
312
472
  await this.finishSession(provider);
313
473
  throw error;
314
474
  }
315
- finally {
316
- this.pending.delete(pending);
317
- }
318
475
  }
319
476
  async driveOnce(provider, url, goal) {
320
477
  const customGoal = goal === undefined ? undefined : `${goal}${this.options.dataSharingApproved?.includes(provider) ? ' The user approved data sharing for this provider during grouped setup consent. You may accept its required free-route data-sharing disclosure to enable free access.' : ' Do not opt in to optional prompt/response retention, staff review or model training; report any required consent for grouped setup approval.'}`;
321
478
  const instruction = customGoal ?? `Use the user's existing ${provider} account or sign up for the free plan. ${provider === 'runcrate' ? 'Use GitHub OAuth for the free path; do not use Google OAuth because that path requires billing.' : provider === 'apinex' ? 'Use Google OAuth with the personal @gmail.com identity already connected to Squire.' : "Prefer Google OAuth using the user's Squire-connected identity."} Reuse an existing key in this user's vault, or create one API key for grunt and store it in this user's Squire vault with service ${provider}. Use operate_extract to capture the key directly into the vault; never put its value in your answer.${provider === 'kilo' ? ' Reuse the existing profile API key without resetting it. Capture with api_hosts ["api.kilo.ai", "ai-gateway.kilo.ai"] in that order and auth_shape "bearer"; grunt uses /api/gateway beneath the grant.' : ''}${provider === 'nvidia' ? ' Complete free NVIDIA Build developer onboarding and enable its free inference endpoint. Capture the API key with api_hosts ["integrate.api.nvidia.com"] and auth_shape "bearer". Never reset or rotate an existing key. The requested free model is deepseek-ai/deepseek-v4.1-flash.' : ''}${provider === 'zro' ? ' Verify that this account is on the Free plan, has no paid subscription, no purchased usage-pack balance and no saved payment method before creating or reusing its key. If any paid balance, plan or payment method exists, stop and report it; do not cancel, downgrade, remove a payment method or create another account. Enable only its daily free DeepSeek V4.1 Flash access. Capture the API key with api_hosts ["zro.moonmath.ai"] and auth_shape "bearer". Store service zro, label grunt. Never reset or rotate an existing key. The requested model is deepseek-v4.1-flash.' : ''}${provider === 'tokenharbor' ? ' Enable the free model deepseek-v4.1-flash:free under the approved data-sharing policy; never select its paid sibling. Capture with api_hosts ["tokenharbor.ai"] and auth_shape "bearer", service tokenharbor, label grunt. Do not create a second key if an existing vaulted key is usable, and never reset or rotate an existing key.' : ''}${freeProviderInstructions[provider] ?? ''}${this.options.dataSharingApproved?.includes(provider) ? ' The user approved data sharing for this provider during grouped setup consent. You may accept its required free-route prompt/response retention, staff review and provider training disclosure to enable free access.' : ' Do not opt in to optional prompt/response retention, staff review or model training; if free access requires that consent, report it for the grouped setup approval.'} No paid plan, payment method, extra account or account switching. If captcha, passkey or email confirmation needs a human, stop and report the required step so grunt can share this browser. Do not bypass verification. Stop on provider refusal.`;
322
479
  let answer;
323
480
  while (true) {
324
- this.signal.throwIfAborted();
481
+ this.serviceSignal(provider).throwIfAborted();
325
482
  const session = this.sessions.get(provider);
326
- const result = await this.call('operate_drive', {
483
+ const result = await this.serviceCall(provider, 'operate_drive', {
327
484
  ...(session ? { session_id: session } : { url }), goal: instruction,
328
485
  facts: { plan: 'free', project_name: 'grunt' }, max_seconds: 45, max_steps: 60,
329
486
  ...(answer ? { answer } : {})
330
487
  });
331
488
  if (typeof result.session_id === 'string')
332
489
  this.sessions.set(provider, result.session_id);
490
+ this.serviceSignal(provider).throwIfAborted();
333
491
  // The driver's remaining field can repeat our own goal, including refusal
334
492
  // and human-verification instructions. That is not evidence from the site.
335
493
  const normalize = (value) => value.replace(/\s+/g, ' ').trim().toLowerCase();
@@ -338,15 +496,22 @@ export class BrowserSquire {
338
496
  && !normalize(result.remaining).includes(normalize(instruction)) ? result.remaining : undefined;
339
497
  const reason = setupReason(result.reason, remaining);
340
498
  const classification = [result.reason, remaining].filter(value => typeof value === 'string').join(' ').replace(/[_-]/g, ' ');
341
- const refusal = ['refused', 'rejected', 'denied', 'forbidden'].includes(String(result.status)) || /\b(?:refus(?:al|ed|es|ing)?|denied|prohibit(?:ed|s)?|not allowed|not permitted|forbidden|disallowed)\b/i.test(classification);
499
+ const observedField = typeof result.field === 'string' && result.field.trim()
500
+ && !normalize(instruction).includes(normalize(result.field))
501
+ && !normalize(result.field).includes(normalize(instruction)) ? result.field : undefined;
502
+ const refusal = ['refused', 'rejected', 'denied', 'forbidden'].includes(String(result.status)) || /\b(?:refus(?:al|ed|es|ing)?|denied|prohibit(?:ed|s)?|not allowed|not permitted|forbidden|disallowed)\b/i.test(`${classification} ${observedField ?? ''}`);
342
503
  if (refusal)
343
504
  throw setupStopped(`Provider refused ${provider} signup; setup stopped`, reason);
344
505
  if (result.status === 'complete') {
345
506
  this.metadata = undefined; // A browser capture may have added a credential.
346
507
  await this.finishSession(provider, true);
508
+ this.serviceSignal(provider).throwIfAborted();
347
509
  return { run: { id: provider, state: 'completed' }, decision: 'silent' };
348
510
  }
349
511
  const uncertain = result.status === 'low_confidence' || result.status === 'no_progress';
512
+ const humanStep = /\b(?:sms|phone|captcha|passkey|email|e mail|verification|confirm(?:ation)?|human(?: only| input| assistance)?)\b/i.test(`${String(result.field)} ${classification}`);
513
+ if (this.options.background && (humanStep || uncertain || result.status === 'stuck'))
514
+ throw new Error('Provider signup needs verification; run usegrunt setup in the foreground to resume');
350
515
  if (uncertain && this.sessions.has(provider)) {
351
516
  const used = this.recoveryChoices.get(provider) ?? new Set();
352
517
  this.recoveryChoices.set(provider, used);
@@ -361,7 +526,12 @@ export class BrowserSquire {
361
526
  continue;
362
527
  }
363
528
  }
364
- const humanStep = /\b(?:sms|phone|captcha|passkey|email|e mail|verification|confirm(?:ation)?|human(?: only| input| assistance)?)\b/i.test(`${String(result.field)} ${classification}`);
529
+ // DONE is a driver choice, not evidence that the account meets the goal.
530
+ // Only the human can attest to every condition, and a generic captcha
531
+ // confirmation must never become an attestation of account/plan state.
532
+ const manualCompletion = uncertain && !humanStep
533
+ && !/\b(?:block(?:ed|ing)?|policy|restrict(?:ed|ion|ions)?)\b/i.test(`${classification} ${String(result.field)}`)
534
+ && object(result.options).DONE === 'The goal is complete';
365
535
  if (!humanStep && (result.status === 'budget' || result.status === 'evaluate_timeout'))
366
536
  return { run: { id: provider, state: 'running' }, decision: 'silent' };
367
537
  // A driver that cannot choose the next action still owns a resumable tab.
@@ -370,13 +540,17 @@ export class BrowserSquire {
370
540
  if (handoff && process.env.MILO_SETUP_NO_HUMAN === '1')
371
541
  throw new Error('Provider signup needs human verification; stopped before handoff');
372
542
  if (handoff && this.sessions.has(provider)) {
373
- const url = await this.humanHandoff(this.sessions.get(provider));
374
- if (this.options.background) {
375
- console.log(`Complete ${provider} verification in this browser: ${url}`);
376
- await delay(5000, undefined, { signal: this.signal });
377
- return { run: { id: provider, state: 'running' }, decision: 'silent' };
543
+ const handoffSession = this.sessions.get(provider);
544
+ const url = await this.humanHandoff(handoffSession);
545
+ this.serviceSignal(provider).throwIfAborted();
546
+ await this.scoped(this.verification.wait({ service: provider, url, ...(manualCompletion ? { goal: instruction } : {}) }), this.serviceSignal(provider));
547
+ this.serviceSignal(provider).throwIfAborted();
548
+ if (manualCompletion) {
549
+ if (this.sessions.get(provider) !== handoffSession)
550
+ throw new Error('Provider verification session changed; rerun setup');
551
+ answer = 'DONE';
552
+ continue;
378
553
  }
379
- await this.verification.wait({ service: provider, url });
380
554
  return { run: { id: provider, state: 'running' }, decision: 'silent' };
381
555
  }
382
556
  await this.finishSession(provider);
@@ -384,11 +558,18 @@ export class BrowserSquire {
384
558
  }
385
559
  }
386
560
  async humanHandoff(session) {
387
- const share = await this.call('operate_share', { session_id: session });
561
+ const provider = [...this.sessions].find(([, id]) => id === session)?.[0];
562
+ const share = await (provider ? this.serviceCall(provider, 'operate_share', { session_id: session }) : this.call('operate_share', { session_id: session }));
563
+ if (provider)
564
+ this.serviceSignal(provider).throwIfAborted();
388
565
  if (typeof share.url !== 'string')
389
566
  throw new Error('Squire returned no browser handoff link');
390
567
  const proxy = await proxyApproval(share.url);
391
- this.handoffs.push(proxy);
568
+ if (provider && this.serviceSignal(provider).aborted) {
569
+ proxy.close();
570
+ throw new Error('Provider signup cancelled');
571
+ }
572
+ this.handoffs.push({ ...proxy, ...(provider ? { provider } : {}) });
392
573
  return proxy.url;
393
574
  }
394
575
  runs = {
@@ -449,12 +630,58 @@ export class FreeLLMAdmin {
449
630
  await this.call(`/keys/${key.id}`, undefined, 'DELETE');
450
631
  }
451
632
  }
452
- async ensureFreeFallbacks() {
633
+ async migrateKiloModels(approved, savedChain) {
634
+ const chain = savedChain ?? await this.call('/fallback', undefined, 'GET');
635
+ const updates = chain.filter(row => managedSharingProvider(row) === 'kilo' && row.enabled !== false
636
+ && (obsoleteManagedKilo(row) || !approved.includes('kilo') || row.priority !== 999999))
637
+ .map(row => ({ modelDbId: row.modelDbId, enabled: approved.includes('kilo') && !obsoleteManagedKilo(row),
638
+ priority: obsoleteManagedKilo(row) || !approved.includes('kilo') ? row.priority : 999999 }));
639
+ // Quarantine before any catalog lookup/registration, so partial failures
640
+ // cannot leave a retired managed route enabled for the next request.
641
+ if (updates.length)
642
+ await this.call('/fallback', updates, 'PUT');
643
+ if (!approved.includes('kilo'))
644
+ return;
645
+ const keys = await this.call('/keys', undefined, 'GET');
646
+ const complete = new Set(keys.filter(key => key.platform === 'custom' && key.models?.some(model => model.modelId === KILO_PARTICLE)).map(key => key.baseUrl));
647
+ for (const key of keys) {
648
+ if (key.platform !== 'custom' || !['Kilo Free', 'Milo kilo (Squire)'].includes(key.label) || !Number.isInteger(key.id) || !key.id || key.id < 1
649
+ || !key.baseUrl || complete.has(key.baseUrl) || !Array.isArray(key.models))
650
+ continue;
651
+ const catalog = await this.call('/keys/custom/discover-models', { keyId: key.id });
652
+ if (!catalog.models.some(model => model.id === KILO_PARTICLE))
653
+ continue;
654
+ // The backend reuses this exact credential. Never read or replace it.
655
+ // Omitted capability flags preserve an existing custom row's settings;
656
+ // the backend already defaults newly inserted chat models to tools-on.
657
+ const registered = await this.call('/keys/custom', { keyId: key.id, models: [{ model: KILO_PARTICLE }] });
658
+ if (!Number.isInteger(registered.modelDbId) || !registered.modelDbId || registered.modelDbId < 1 || registered.model !== KILO_PARTICLE)
659
+ throw new Error('Legacy Kilo Particle registration could not be verified');
660
+ const created = registered.models?.find(model => model.modelDbId === registered.modelDbId && model.model === KILO_PARTICLE)?.created;
661
+ // A user may register/disable this model while catalog discovery runs.
662
+ // Upsert preserves existing fallback flags; only default a new row.
663
+ if (created === true || (created === undefined && registered.created === 1)) {
664
+ await this.call('/fallback', [{ modelDbId: registered.modelDbId, enabled: true, priority: 999999 }], 'PUT');
665
+ }
666
+ complete.add(key.baseUrl);
667
+ }
668
+ }
669
+ async ensureFreeFallbacks(dataSharingApproved) {
670
+ const approved = dataSharingApproved ?? await readDataSharingConsent(dirname(localAdminPath()), ['kilo']);
671
+ // Retired Grunt-owned rows stay quarantined even if a saved sharing receipt
672
+ // approved them. Disable before unrelated discovery can fail.
673
+ const chain = await this.call('/fallback', undefined, 'GET');
674
+ const retired = chain.filter(row => retiredManagedAdapter(row) && row.enabled !== false)
675
+ .map(row => ({ modelDbId: row.modelDbId, enabled: false, priority: row.priority }));
676
+ if (retired.length)
677
+ await this.call('/fallback', retired, 'PUT');
678
+ await this.migrateKiloModels(approved);
453
679
  const keys = await this.call('/keys', undefined, 'GET');
454
680
  for (const provider of freeConfig().customProviders) {
455
- if (!keys.some(key => key.platform === 'custom' && key.baseUrl === provider.baseUrl)) {
681
+ if (provider.label === 'Kilo Free' && !approved.includes('kilo'))
682
+ continue;
683
+ if (!keys.some(key => key.platform === 'custom' && key.baseUrl === provider.baseUrl))
456
684
  await this.call('/keys/custom', provider);
457
- }
458
685
  }
459
686
  }
460
687
  async configureChain(excluded = [], dataSharingApproved) {
@@ -464,11 +691,14 @@ export class FreeLLMAdmin {
464
691
  const provider = [...Object.keys(PROVIDERS), ...savedProviders].find(provider => row.keyLabel === `Milo ${provider} (Squire)`);
465
692
  const owned = managedSharingProvider(row);
466
693
  const fallback = !provider && owned !== undefined;
467
- const sharingAllowed = !owned || approved.includes(owned);
694
+ const retired = retiredManagedAdapter(row);
695
+ const sharingAllowed = !retired && (!owned || approved.includes(owned));
468
696
  const vetted = !provider || !providerModels[provider] || providerModels[provider].includes(row.modelId);
697
+ const disabledParticle = owned === 'kilo' && row.modelId === KILO_PARTICLE && row.enabled === false;
469
698
  return { modelDbId: row.modelDbId,
470
- enabled: sharingAllowed && (fallback || (provider ? row.platform === 'custom' && vetted && !excluded.includes(provider) : row.enabled === true)),
471
- priority: provider === 'kilo' ? (row.modelId === KILO_NEMOTRON ? 999996 : 999997) : owned === 'freebuff' ? 1000000 : owned === 'kilo' ? 999999 : row.priority };
699
+ enabled: sharingAllowed && !obsoleteManagedKilo(row) && !disabledParticle
700
+ && (fallback || (provider ? row.platform === 'custom' && vetted && !excluded.includes(provider) : row.enabled === true)),
701
+ priority: disabledParticle || retired ? row.priority : owned === 'kilo' ? 999999 : row.priority };
472
702
  });
473
703
  await this.call('/fallback', rows, 'PUT');
474
704
  await this.call('/fallback/routing', { strategy: 'priority' }, 'PUT');
@@ -590,28 +820,37 @@ async function saveLocalAdmin(admin) {
590
820
  function managedSharingProvider(row) {
591
821
  if (row.platform !== 'custom')
592
822
  return;
593
- if (row.keyLabel === 'Milo kilo (Squire)' || (row.keyLabel === 'Kilo Free' && row.modelId === 'kilo-auto/free'))
823
+ if (row.keyLabel === 'Milo kilo (Squire)' || row.keyLabel === 'Kilo Free')
594
824
  return 'kilo';
595
825
  if (row.keyLabel === 'Freebuff' && row.modelId === 'freebuff')
596
826
  return 'freebuff';
827
+ for (const provider of disabledAdapters)
828
+ if (row.keyLabel === `Milo ${provider} (Squire)`)
829
+ return provider;
597
830
  return;
598
831
  }
832
+ const obsoleteManagedKilo = (row) => managedSharingProvider(row) === 'kilo' && row.modelId !== KILO_PARTICLE;
833
+ // Keep legacy label recognition for retirement; never recreate these rows.
834
+ const retiredManagedAdapter = (row) => {
835
+ const provider = managedSharingProvider(row);
836
+ return provider !== undefined && disabledAdapters.has(provider);
837
+ };
599
838
  // Reconcile only Grunt-owned sharing rows before a legacy backend request. This
600
839
  // never provisions a router, changes custom rows, or enables a disabled row.
601
840
  export async function guardRouterSharing(url, directory) {
602
- const approved = await readDataSharingConsent(directory, ['kilo', 'freebuff']);
603
- if (approved.includes('kilo') && approved.includes('freebuff'))
604
- return;
841
+ const approved = await readDataSharingConsent(directory, ['kilo']);
605
842
  const admin = await readLocalAdmin(join(directory, 'router-admin.json'));
606
843
  if (!admin)
607
844
  throw new Error('Local router admin state is required to enforce data-sharing choices; rerun usegrunt setup');
608
845
  const router = new FreeLLMAdmin(url);
609
846
  await router.login(admin.password);
610
847
  const chain = await router.call('/fallback', undefined, 'GET');
611
- const updates = chain.filter(row => { const provider = managedSharingProvider(row); return provider && !approved.includes(provider) && row.enabled !== false; })
848
+ const updates = chain.filter(row => { const provider = managedSharingProvider(row); return provider && (retiredManagedAdapter(row) || !approved.includes(provider) || obsoleteManagedKilo(row)) && row.enabled !== false; })
612
849
  .map(row => ({ modelDbId: row.modelDbId, enabled: false, priority: row.priority }));
613
850
  if (updates.length)
614
851
  await router.call('/fallback', updates, 'PUT');
852
+ const patched = chain.map(row => ({ ...row, ...updates.find(update => update.modelDbId === row.modelDbId) }));
853
+ await router.migrateKiloModels(approved, patched);
615
854
  }
616
855
  // Read the login already created by setup; never provision or change router state.
617
856
  export async function loadRouterKey(url) {
@@ -696,6 +935,9 @@ function readyRouter(signal) {
696
935
  return starting;
697
936
  }
698
937
  export async function setup(notify = console.log, providers = ['groq'], options = {}) {
938
+ const retired = providers.find(provider => disabledAdapters.has(provider));
939
+ if (retired)
940
+ throw new Error(`${retired} routing is disabled`);
699
941
  const location = options.directory ?? process.env.MILO_CONFIG_DIR ?? join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
700
942
  const approved = [...new Set([...(options.dataSharingApproved ?? []), ...await readDataSharingConsent(location, DATA_SHARING_POLICIES.map(policy => policy.provider))])];
701
943
  const unapproved = dataSharingPolicies(providers).filter(policy => !approved.includes(policy.provider));
@@ -706,8 +948,44 @@ export async function setup(notify = console.log, providers = ['groq'], options
706
948
  options.squire.approveDataSharing(approved);
707
949
  const squire = options.squire ?? owned;
708
950
  try {
951
+ if (providers.includes('kilo')) {
952
+ await verifyKiloAccess({ ...(options.signal ? { signal: options.signal } : {}) });
953
+ notify('Kilo: free Particle-1 access verified; no account or API key required');
954
+ providers = providers.filter(provider => provider !== 'kilo');
955
+ }
956
+ // Idle sync only reuses verified state for these guarded sources. It never
957
+ // deletes their receipts, provisions a browser or changes account settings.
958
+ if (options.background) {
959
+ const browser = squire;
960
+ for (const provider of ['pollinations', 'beatapi', 'clixad', 'perch']) {
961
+ if (!providers.includes(provider))
962
+ continue;
963
+ await (provider === 'pollinations' ? setupPollinations : provider === 'beatapi' ? setupBeatAPI : provider === 'clixad' ? setupClixad : setupPerch)({ directory: location, squire: browser, background: true,
964
+ dataSharingApproved: approved, notify, ...(options.signal ? { signal: options.signal } : {}) });
965
+ providers = providers.filter(id => id !== provider);
966
+ }
967
+ }
968
+ if (!providers.length)
969
+ return {};
709
970
  await owned?.connect();
710
971
  options.signal?.throwIfAborted();
972
+ for (const provider of ['pollinations', 'beatapi', 'clixad', 'perch']) {
973
+ if (!providers.includes(provider))
974
+ continue;
975
+ const browser = squire;
976
+ if (typeof browser.signup !== 'function')
977
+ throw new Error(`${provider} signup requires a browser-capable Squire client`);
978
+ await (provider === 'pollinations' ? setupPollinations : provider === 'beatapi' ? setupBeatAPI : provider === 'clixad' ? setupClixad : setupPerch)({ directory: location, squire: browser,
979
+ dataSharingApproved: approved, notify, ...(options.signal ? { signal: options.signal } : {}) });
980
+ providers = providers.filter(id => id !== provider);
981
+ }
982
+ if (providers.includes('livekit')) {
983
+ const browser = squire;
984
+ if (typeof browser.signup !== 'function')
985
+ throw new Error('LiveKit native signup requires a browser-capable Squire client');
986
+ await setupLiveKit({ directory: location, squire: browser, notify, ...(options.signal ? { signal: options.signal } : {}) });
987
+ providers = providers.filter(provider => provider !== 'livekit');
988
+ }
711
989
  if (providers.includes('mistral-vibe')) {
712
990
  const browser = squire;
713
991
  if (typeof browser.signup !== 'function')
@@ -13,12 +13,14 @@ export class SourceError extends Error {
13
13
  export const answeredBy = new WeakMap();
14
14
  export class Sources {
15
15
  sources;
16
+ disabledModels;
16
17
  router;
17
18
  // Adapters whose background setup has not finished yet.
18
19
  preparing = new Set();
19
- constructor(sources, routing) {
20
+ constructor(sources, routing, disabledModels = new Set()) {
20
21
  this.sources = sources;
21
- if (!sources.length || new Set(sources.map(s => s.id)).size !== sources.length)
22
+ this.disabledModels = disabledModels;
23
+ if ((!sources.length && !disabledModels.size) || new Set(sources.map(s => s.id)).size !== sources.length)
22
24
  throw new Error('Configure distinct grunt sources');
23
25
  if (routing)
24
26
  this.router = new StickyRouter(sources, routing);
@@ -35,6 +37,9 @@ export class Sources {
35
37
  return [...(this.router ? ['grunt'] : []), 'milo', ...available.filter((id) => id !== null)];
36
38
  }
37
39
  async complete(request, signal) {
40
+ signal.throwIfAborted();
41
+ if (this.disabledModels.has(request.model))
42
+ throw new SourceError('refused', `${request.model} routing is disabled`);
38
43
  if (this.router)
39
44
  return this.router.complete(request, signal);
40
45
  const known = this.sources.some(s => s.id === request.model);