usegrunt 0.6.5 → 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,6 +15,7 @@ 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';
@@ -22,10 +23,16 @@ import { Runcrate, writeRuncrateGrant } from './runcrate.js';
22
23
  import { Apinex, writeApinexGrant } from './apinex.js';
23
24
  import { setupMistralVibe } from './mistral-vibe-setup.js';
24
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';
25
32
  import { DATA_SHARING_POLICIES, dataSharingPolicies, readDataSharingConsent } from './data-sharing.js';
26
33
  const exec = promisify(execFile);
27
34
  export const FREELLMAPI_IMAGE = 'ghcr.io/tashfeenahmed/freellmapi@sha256:845a4b568a20fffd5112e1b9c0258e7782d9eabbba2430612d2f7c811eee267e';
28
- export const PROVIDERS = { groq: 'https://console.groq.com/keys', cerebras: 'https://cloud.cerebras.ai/platform/api-keys', kilo: 'https://app.kilo.ai/profile', nvidia: 'https://build.nvidia.com/settings/api-keys', zro: 'https://zro.moonmath.ai/overview', tokenharbor: 'https://tokenharbor.ai/dashboard', runcrate: 'https://www.runcrate.ai/auth/signup', apinex: 'https://apinex.bond/register', 'mistral-vibe': 'https://console.mistral.ai', livekit: 'https://cloud.livekit.io' };
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' };
29
36
  const freeProviderInstructions = {
30
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.',
31
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.'
@@ -33,7 +40,7 @@ const freeProviderInstructions = {
33
40
  export const KILO_NEMOTRON = 'nvidia/nemotron-3-ultra-550b-a55b:free';
34
41
  export { NVIDIA_DEEPSEEK } from './nvidia.js';
35
42
  const savedProviders = ['kilo'];
36
- const providerModels = { kilo: [KILO_NEMOTRON, 'kilo-auto/free'] };
43
+ const providerModels = { kilo: [KILO_PARTICLE] };
37
44
  const sameService = (credential, service) => credential.service?.trim().toLowerCase() === service.trim().toLowerCase();
38
45
  function apiKeyField(credential, provider) {
39
46
  return credential.field_names.find(field => {
@@ -160,6 +167,13 @@ export class BrowserSquire {
160
167
  approveDataSharing(providers) { this.options.dataSharingApproved = [...new Set(providers)]; }
161
168
  client = new Client({ name: 'grunt setup', version: '0.1.0' });
162
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();
163
177
  recoveryChoices = new Map();
164
178
  pending = new Set();
165
179
  closed = false;
@@ -170,15 +184,133 @@ export class BrowserSquire {
170
184
  metadata;
171
185
  grants = new Map();
172
186
  verification = new VerificationQueue(items => withTerminal(async () => {
173
- this.signal.throwIfAborted();
174
- for (const item of items)
175
- console.log(`Complete ${item.service} verification in this browser: ${item.url}`);
176
187
  const { confirm, isCancel } = await import('@clack/prompts');
177
- const done = await confirm({ message: `Finished verification for ${items.map(item => item.service).join(', ')}? Resume setup.`, initialValue: true, signal: this.signal });
178
- if (isCancel(done) || !done)
179
- throw new Error('Provider verification cancelled');
180
- 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
+ }
181
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
+ }
182
314
  connect() {
183
315
  return this.connection ??= this.connectOnce().catch(error => { this.connection = undefined; throw error; });
184
316
  }
@@ -223,27 +355,39 @@ export class BrowserSquire {
223
355
  }
224
356
  }
225
357
  async call(name, args, connectionCheck = false) {
226
- const result = await this.client.callTool({ name, arguments: args }, undefined, { timeout: name === 'operate_finish' ? 10000 : 60000, ...(name === 'operate_finish' ? {} : { signal: this.signal }) }).catch(error => {
227
- if (connectionCheck)
228
- throw error;
229
- throw new Error(`Squire ${name} is unavailable; resume setup after reconnecting Squire`);
230
- });
231
- if (result.isError) {
232
- const reason = connectionCheck ? result.content
233
- .filter(part => part.type === 'text').map(part => part.text ?? '').join(' ') : '';
234
- throw new Error(reason || `Squire ${name} failed; inspect Squire for the required action`);
235
- }
236
- if (result.structuredContent)
237
- return object(result.structuredContent);
238
- for (const part of result.content) {
239
- if (part.type === 'text' && part.text) {
240
- try {
241
- 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. */ }
242
384
  }
243
- catch { /* Do not echo upstream output. */ }
244
385
  }
386
+ throw new Error(`Squire ${name} returned an unsupported result`);
387
+ }
388
+ finally {
389
+ release?.();
245
390
  }
246
- throw new Error(`Squire ${name} returned an unsupported result`);
247
391
  }
248
392
  credentials = {
249
393
  list: async () => {
@@ -275,20 +419,34 @@ export class BrowserSquire {
275
419
  const id = this.sessions.get(provider);
276
420
  if (!id)
277
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);
278
438
  try {
279
- await this.call('operate_finish', { session_id: id, outcome: completed ? 'result' : 'none',
280
- ...(completed ? { summary: 'grunt provider key stored in user vault' } : {}) });
281
- if (this.sessions.get(provider) === id)
282
- this.sessions.delete(provider);
283
- this.recoveryChoices.delete(provider);
439
+ await pending;
440
+ }
441
+ finally {
442
+ this.finishing.delete(id);
284
443
  }
285
- catch { /* Preserve the original error; close retries a failed cleanup. */ }
286
444
  }
287
445
  async signup(service, url, goal) {
288
446
  const deadline = Date.now() + 600000;
289
447
  try {
290
448
  while (Date.now() < deadline) {
291
- this.signal.throwIfAborted();
449
+ this.serviceSignal(service).throwIfAborted();
292
450
  const result = await this.drive(service, url, goal);
293
451
  if (result.run.state === 'completed')
294
452
  return;
@@ -304,33 +462,32 @@ export class BrowserSquire {
304
462
  async drive(provider, url = PROVIDERS[provider], goal) {
305
463
  if (this.closed)
306
464
  throw new Error('Squire setup is closed');
307
- const pending = this.driveOnce(provider, url, goal);
465
+ const pending = this.driveOnce(provider, url, goal).catch(async (error) => { await this.finishSession(provider); throw error; });
308
466
  this.pending.add(pending);
467
+ void pending.then(() => this.pending.delete(pending), () => this.pending.delete(pending));
309
468
  try {
310
- return await pending;
469
+ return await this.scoped(pending, this.serviceSignal(provider));
311
470
  }
312
471
  catch (error) {
313
472
  await this.finishSession(provider);
314
473
  throw error;
315
474
  }
316
- finally {
317
- this.pending.delete(pending);
318
- }
319
475
  }
320
476
  async driveOnce(provider, url, goal) {
321
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.'}`;
322
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.`;
323
479
  let answer;
324
480
  while (true) {
325
- this.signal.throwIfAborted();
481
+ this.serviceSignal(provider).throwIfAborted();
326
482
  const session = this.sessions.get(provider);
327
- const result = await this.call('operate_drive', {
483
+ const result = await this.serviceCall(provider, 'operate_drive', {
328
484
  ...(session ? { session_id: session } : { url }), goal: instruction,
329
485
  facts: { plan: 'free', project_name: 'grunt' }, max_seconds: 45, max_steps: 60,
330
486
  ...(answer ? { answer } : {})
331
487
  });
332
488
  if (typeof result.session_id === 'string')
333
489
  this.sessions.set(provider, result.session_id);
490
+ this.serviceSignal(provider).throwIfAborted();
334
491
  // The driver's remaining field can repeat our own goal, including refusal
335
492
  // and human-verification instructions. That is not evidence from the site.
336
493
  const normalize = (value) => value.replace(/\s+/g, ' ').trim().toLowerCase();
@@ -339,15 +496,22 @@ export class BrowserSquire {
339
496
  && !normalize(result.remaining).includes(normalize(instruction)) ? result.remaining : undefined;
340
497
  const reason = setupReason(result.reason, remaining);
341
498
  const classification = [result.reason, remaining].filter(value => typeof value === 'string').join(' ').replace(/[_-]/g, ' ');
342
- 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 ?? ''}`);
343
503
  if (refusal)
344
504
  throw setupStopped(`Provider refused ${provider} signup; setup stopped`, reason);
345
505
  if (result.status === 'complete') {
346
506
  this.metadata = undefined; // A browser capture may have added a credential.
347
507
  await this.finishSession(provider, true);
508
+ this.serviceSignal(provider).throwIfAborted();
348
509
  return { run: { id: provider, state: 'completed' }, decision: 'silent' };
349
510
  }
350
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');
351
515
  if (uncertain && this.sessions.has(provider)) {
352
516
  const used = this.recoveryChoices.get(provider) ?? new Set();
353
517
  this.recoveryChoices.set(provider, used);
@@ -362,7 +526,12 @@ export class BrowserSquire {
362
526
  continue;
363
527
  }
364
528
  }
365
- 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';
366
535
  if (!humanStep && (result.status === 'budget' || result.status === 'evaluate_timeout'))
367
536
  return { run: { id: provider, state: 'running' }, decision: 'silent' };
368
537
  // A driver that cannot choose the next action still owns a resumable tab.
@@ -371,13 +540,17 @@ export class BrowserSquire {
371
540
  if (handoff && process.env.MILO_SETUP_NO_HUMAN === '1')
372
541
  throw new Error('Provider signup needs human verification; stopped before handoff');
373
542
  if (handoff && this.sessions.has(provider)) {
374
- const url = await this.humanHandoff(this.sessions.get(provider));
375
- if (this.options.background) {
376
- console.log(`Complete ${provider} verification in this browser: ${url}`);
377
- await delay(5000, undefined, { signal: this.signal });
378
- 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;
379
553
  }
380
- await this.verification.wait({ service: provider, url });
381
554
  return { run: { id: provider, state: 'running' }, decision: 'silent' };
382
555
  }
383
556
  await this.finishSession(provider);
@@ -385,11 +558,18 @@ export class BrowserSquire {
385
558
  }
386
559
  }
387
560
  async humanHandoff(session) {
388
- 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();
389
565
  if (typeof share.url !== 'string')
390
566
  throw new Error('Squire returned no browser handoff link');
391
567
  const proxy = await proxyApproval(share.url);
392
- 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 } : {}) });
393
573
  return proxy.url;
394
574
  }
395
575
  runs = {
@@ -450,12 +630,58 @@ export class FreeLLMAdmin {
450
630
  await this.call(`/keys/${key.id}`, undefined, 'DELETE');
451
631
  }
452
632
  }
453
- 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);
454
679
  const keys = await this.call('/keys', undefined, 'GET');
455
680
  for (const provider of freeConfig().customProviders) {
456
- 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))
457
684
  await this.call('/keys/custom', provider);
458
- }
459
685
  }
460
686
  }
461
687
  async configureChain(excluded = [], dataSharingApproved) {
@@ -465,11 +691,14 @@ export class FreeLLMAdmin {
465
691
  const provider = [...Object.keys(PROVIDERS), ...savedProviders].find(provider => row.keyLabel === `Milo ${provider} (Squire)`);
466
692
  const owned = managedSharingProvider(row);
467
693
  const fallback = !provider && owned !== undefined;
468
- const sharingAllowed = !owned || approved.includes(owned);
694
+ const retired = retiredManagedAdapter(row);
695
+ const sharingAllowed = !retired && (!owned || approved.includes(owned));
469
696
  const vetted = !provider || !providerModels[provider] || providerModels[provider].includes(row.modelId);
697
+ const disabledParticle = owned === 'kilo' && row.modelId === KILO_PARTICLE && row.enabled === false;
470
698
  return { modelDbId: row.modelDbId,
471
- enabled: sharingAllowed && (fallback || (provider ? row.platform === 'custom' && vetted && !excluded.includes(provider) : row.enabled === true)),
472
- 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 };
473
702
  });
474
703
  await this.call('/fallback', rows, 'PUT');
475
704
  await this.call('/fallback/routing', { strategy: 'priority' }, 'PUT');
@@ -591,28 +820,37 @@ async function saveLocalAdmin(admin) {
591
820
  function managedSharingProvider(row) {
592
821
  if (row.platform !== 'custom')
593
822
  return;
594
- 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')
595
824
  return 'kilo';
596
825
  if (row.keyLabel === 'Freebuff' && row.modelId === 'freebuff')
597
826
  return 'freebuff';
827
+ for (const provider of disabledAdapters)
828
+ if (row.keyLabel === `Milo ${provider} (Squire)`)
829
+ return provider;
598
830
  return;
599
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
+ };
600
838
  // Reconcile only Grunt-owned sharing rows before a legacy backend request. This
601
839
  // never provisions a router, changes custom rows, or enables a disabled row.
602
840
  export async function guardRouterSharing(url, directory) {
603
- const approved = await readDataSharingConsent(directory, ['kilo', 'freebuff']);
604
- if (approved.includes('kilo') && approved.includes('freebuff'))
605
- return;
841
+ const approved = await readDataSharingConsent(directory, ['kilo']);
606
842
  const admin = await readLocalAdmin(join(directory, 'router-admin.json'));
607
843
  if (!admin)
608
844
  throw new Error('Local router admin state is required to enforce data-sharing choices; rerun usegrunt setup');
609
845
  const router = new FreeLLMAdmin(url);
610
846
  await router.login(admin.password);
611
847
  const chain = await router.call('/fallback', undefined, 'GET');
612
- 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; })
613
849
  .map(row => ({ modelDbId: row.modelDbId, enabled: false, priority: row.priority }));
614
850
  if (updates.length)
615
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);
616
854
  }
617
855
  // Read the login already created by setup; never provision or change router state.
618
856
  export async function loadRouterKey(url) {
@@ -697,6 +935,9 @@ function readyRouter(signal) {
697
935
  return starting;
698
936
  }
699
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`);
700
941
  const location = options.directory ?? process.env.MILO_CONFIG_DIR ?? join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
701
942
  const approved = [...new Set([...(options.dataSharingApproved ?? []), ...await readDataSharingConsent(location, DATA_SHARING_POLICIES.map(policy => policy.provider))])];
702
943
  const unapproved = dataSharingPolicies(providers).filter(policy => !approved.includes(policy.provider));
@@ -707,8 +948,37 @@ export async function setup(notify = console.log, providers = ['groq'], options
707
948
  options.squire.approveDataSharing(approved);
708
949
  const squire = options.squire ?? owned;
709
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 {};
710
970
  await owned?.connect();
711
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
+ }
712
982
  if (providers.includes('livekit')) {
713
983
  const browser = squire;
714
984
  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);