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.
@@ -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,17 @@ 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';
33
+ import { readSetupSession } from './setup-session.js';
26
34
  const exec = promisify(execFile);
27
35
  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' };
36
+ 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
37
  const freeProviderInstructions = {
30
38
  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
39
  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 +41,7 @@ const freeProviderInstructions = {
33
41
  export const KILO_NEMOTRON = 'nvidia/nemotron-3-ultra-550b-a55b:free';
34
42
  export { NVIDIA_DEEPSEEK } from './nvidia.js';
35
43
  const savedProviders = ['kilo'];
36
- const providerModels = { kilo: [KILO_NEMOTRON, 'kilo-auto/free'] };
44
+ const providerModels = { kilo: [KILO_PARTICLE] };
37
45
  const sameService = (credential, service) => credential.service?.trim().toLowerCase() === service.trim().toLowerCase();
38
46
  function apiKeyField(credential, provider) {
39
47
  return credential.field_names.find(field => {
@@ -160,6 +168,13 @@ export class BrowserSquire {
160
168
  approveDataSharing(providers) { this.options.dataSharingApproved = [...new Set(providers)]; }
161
169
  client = new Client({ name: 'grunt setup', version: '0.1.0' });
162
170
  sessions = new Map();
171
+ services = new Map();
172
+ callSignals = new WeakMap();
173
+ queueSignals = new WeakMap();
174
+ browserActive = 0;
175
+ browserQueue = [];
176
+ initialDriveSignal = new AbortController().signal;
177
+ finishing = new Map();
163
178
  recoveryChoices = new Map();
164
179
  pending = new Set();
165
180
  closed = false;
@@ -170,15 +185,133 @@ export class BrowserSquire {
170
185
  metadata;
171
186
  grants = new Map();
172
187
  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
188
  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();
189
+ for (;;) {
190
+ this.signal.throwIfAborted();
191
+ const active = items.filter(item => !this.serviceSignal(item.service).aborted);
192
+ if (!active.length)
193
+ return;
194
+ const prompt = new AbortController();
195
+ const signals = active.map(item => this.serviceSignal(item.service));
196
+ const changed = () => prompt.abort();
197
+ for (const signal of signals)
198
+ signal.addEventListener('abort', changed, { once: true });
199
+ try {
200
+ for (const item of active) {
201
+ console.log(`Complete ${item.service} verification in this browser: ${item.url}`);
202
+ if (item.goal)
203
+ console.log(`${item.service} requested goal; verify every condition before confirming:\n${item.goal}`);
204
+ }
205
+ const attest = active.some(item => item.goal !== undefined);
206
+ const message = attest
207
+ ? `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?`
208
+ : `Finished verification for ${active.map(item => item.service).join(', ')}? Resume setup.`;
209
+ const done = await this.scoped(confirm({ message, initialValue: !attest, signal: prompt.signal }), prompt.signal);
210
+ this.signal.throwIfAborted();
211
+ if (signals.some(signal => signal.aborted))
212
+ continue;
213
+ if (isCancel(done) || !done)
214
+ throw new Error('Provider verification cancelled');
215
+ return;
216
+ }
217
+ catch (error) {
218
+ this.signal.throwIfAborted();
219
+ if (!signals.some(signal => signal.aborted))
220
+ throw error;
221
+ }
222
+ finally {
223
+ for (const signal of signals)
224
+ signal.removeEventListener('abort', changed);
225
+ }
226
+ }
181
227
  }));
228
+ serviceSignal(provider) {
229
+ let controller = this.services.get(provider);
230
+ if (!controller) {
231
+ controller = new AbortController();
232
+ this.services.set(provider, controller);
233
+ }
234
+ return AbortSignal.any([this.signal, controller.signal]);
235
+ }
236
+ async scoped(promise, signal) {
237
+ let abort;
238
+ try {
239
+ return await Promise.race([promise, new Promise((_resolve, reject) => {
240
+ abort = () => reject(new Error('Provider signup cancelled'));
241
+ signal.addEventListener('abort', abort, { once: true });
242
+ if (signal.aborted)
243
+ abort();
244
+ })]);
245
+ }
246
+ finally {
247
+ if (abort)
248
+ signal.removeEventListener('abort', abort);
249
+ }
250
+ }
251
+ async serviceCall(provider, name, args) {
252
+ this.serviceSignal(provider).throwIfAborted();
253
+ // Cancelling MCP before a first response discards its new session ID.
254
+ // Let that one bounded create/drive finish, then close any late session.
255
+ // Known-session calls can be aborted immediately and cleaned up by ID.
256
+ const initial = name === 'operate_drive' && !args.session_id;
257
+ this.callSignals.set(args, initial ? this.initialDriveSignal : this.serviceSignal(provider));
258
+ // Waiting work must remain cancellable even when its eventual first RPC
259
+ // needs to retain a late response containing the owned browser session ID.
260
+ this.queueSignals.set(args, this.serviceSignal(provider));
261
+ try {
262
+ return await this.call(name, args);
263
+ }
264
+ finally {
265
+ this.callSignals.delete(args);
266
+ this.queueSignals.delete(args);
267
+ }
268
+ }
269
+ async browserSlot(signal) {
270
+ signal.throwIfAborted();
271
+ const release = () => {
272
+ let released = false;
273
+ return () => {
274
+ if (released)
275
+ return;
276
+ released = true;
277
+ this.browserActive--;
278
+ this.browserQueue.shift()?.grant();
279
+ };
280
+ };
281
+ if (this.browserActive < BROWSER_CONCURRENCY) {
282
+ this.browserActive++;
283
+ return release();
284
+ }
285
+ return new Promise((resolve, reject) => {
286
+ const entry = { grant: () => {
287
+ signal.removeEventListener('abort', cancelled);
288
+ this.browserActive++;
289
+ resolve(release());
290
+ } };
291
+ const cancelled = () => {
292
+ const index = this.browserQueue.indexOf(entry);
293
+ if (index !== -1)
294
+ this.browserQueue.splice(index, 1);
295
+ signal.removeEventListener('abort', cancelled);
296
+ reject(new Error('Provider signup cancelled'));
297
+ };
298
+ this.browserQueue.push(entry);
299
+ signal.addEventListener('abort', cancelled, { once: true });
300
+ if (signal.aborted)
301
+ cancelled();
302
+ });
303
+ }
304
+ async cancelSignup(provider) {
305
+ let controller = this.services.get(provider);
306
+ if (!controller) {
307
+ controller = new AbortController();
308
+ this.services.set(provider, controller);
309
+ }
310
+ controller.abort(new Error('Provider signup cancelled'));
311
+ for (const handoff of this.handoffs.filter(item => item.provider === provider))
312
+ handoff.close();
313
+ await this.finishSession(provider);
314
+ }
182
315
  connect() {
183
316
  return this.connection ??= this.connectOnce().catch(error => { this.connection = undefined; throw error; });
184
317
  }
@@ -223,27 +356,39 @@ export class BrowserSquire {
223
356
  }
224
357
  }
225
358
  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));
359
+ const provider = typeof args.service === 'string' ? args.service
360
+ : [...this.sessions].find(([, id]) => id === args.session_id)?.[0];
361
+ const queueSignal = this.queueSignals.get(args) ?? (provider ? this.serviceSignal(provider) : this.signal);
362
+ const release = name === 'operate_drive' || name === 'operate_start' ? await this.browserSlot(queueSignal) : undefined;
363
+ try {
364
+ // A slot can be granted just before cancellation. Recheck before dispatch.
365
+ if (release)
366
+ queueSignal.throwIfAborted();
367
+ 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 => {
368
+ if (connectionCheck)
369
+ throw error;
370
+ throw new Error(`Squire ${name} is unavailable; resume setup after reconnecting Squire`);
371
+ });
372
+ if (result.isError) {
373
+ const reason = connectionCheck ? result.content
374
+ .filter(part => part.type === 'text').map(part => part.text ?? '').join(' ') : '';
375
+ throw new Error(reason || `Squire ${name} failed; inspect Squire for the required action`);
376
+ }
377
+ if (result.structuredContent)
378
+ return object(result.structuredContent);
379
+ for (const part of result.content) {
380
+ if (part.type === 'text' && part.text) {
381
+ try {
382
+ return object(JSON.parse(part.text));
383
+ }
384
+ catch { /* Do not echo upstream output. */ }
242
385
  }
243
- catch { /* Do not echo upstream output. */ }
244
386
  }
387
+ throw new Error(`Squire ${name} returned an unsupported result`);
388
+ }
389
+ finally {
390
+ release?.();
245
391
  }
246
- throw new Error(`Squire ${name} returned an unsupported result`);
247
392
  }
248
393
  credentials = {
249
394
  list: async () => {
@@ -275,20 +420,34 @@ export class BrowserSquire {
275
420
  const id = this.sessions.get(provider);
276
421
  if (!id)
277
422
  return;
423
+ const existing = this.finishing.get(id);
424
+ if (existing)
425
+ return existing;
426
+ const pending = (async () => {
427
+ try {
428
+ await this.call('operate_finish', { session_id: id, outcome: completed ? 'result' : 'none',
429
+ ...(completed ? { summary: 'grunt provider key stored in user vault' } : {}) });
430
+ if (this.sessions.get(provider) === id)
431
+ this.sessions.delete(provider);
432
+ this.recoveryChoices.delete(provider);
433
+ for (const handoff of this.handoffs.filter(item => item.provider === provider))
434
+ handoff.close();
435
+ }
436
+ catch { /* Preserve the original error; close retries a failed cleanup. */ }
437
+ })();
438
+ this.finishing.set(id, pending);
278
439
  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);
440
+ await pending;
441
+ }
442
+ finally {
443
+ this.finishing.delete(id);
284
444
  }
285
- catch { /* Preserve the original error; close retries a failed cleanup. */ }
286
445
  }
287
446
  async signup(service, url, goal) {
288
447
  const deadline = Date.now() + 600000;
289
448
  try {
290
449
  while (Date.now() < deadline) {
291
- this.signal.throwIfAborted();
450
+ this.serviceSignal(service).throwIfAborted();
292
451
  const result = await this.drive(service, url, goal);
293
452
  if (result.run.state === 'completed')
294
453
  return;
@@ -304,33 +463,32 @@ export class BrowserSquire {
304
463
  async drive(provider, url = PROVIDERS[provider], goal) {
305
464
  if (this.closed)
306
465
  throw new Error('Squire setup is closed');
307
- const pending = this.driveOnce(provider, url, goal);
466
+ const pending = this.driveOnce(provider, url, goal).catch(async (error) => { await this.finishSession(provider); throw error; });
308
467
  this.pending.add(pending);
468
+ void pending.then(() => this.pending.delete(pending), () => this.pending.delete(pending));
309
469
  try {
310
- return await pending;
470
+ return await this.scoped(pending, this.serviceSignal(provider));
311
471
  }
312
472
  catch (error) {
313
473
  await this.finishSession(provider);
314
474
  throw error;
315
475
  }
316
- finally {
317
- this.pending.delete(pending);
318
- }
319
476
  }
320
477
  async driveOnce(provider, url, goal) {
321
478
  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
479
  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
480
  let answer;
324
481
  while (true) {
325
- this.signal.throwIfAborted();
482
+ this.serviceSignal(provider).throwIfAborted();
326
483
  const session = this.sessions.get(provider);
327
- const result = await this.call('operate_drive', {
484
+ const result = await this.serviceCall(provider, 'operate_drive', {
328
485
  ...(session ? { session_id: session } : { url }), goal: instruction,
329
486
  facts: { plan: 'free', project_name: 'grunt' }, max_seconds: 45, max_steps: 60,
330
487
  ...(answer ? { answer } : {})
331
488
  });
332
489
  if (typeof result.session_id === 'string')
333
490
  this.sessions.set(provider, result.session_id);
491
+ this.serviceSignal(provider).throwIfAborted();
334
492
  // The driver's remaining field can repeat our own goal, including refusal
335
493
  // and human-verification instructions. That is not evidence from the site.
336
494
  const normalize = (value) => value.replace(/\s+/g, ' ').trim().toLowerCase();
@@ -339,15 +497,22 @@ export class BrowserSquire {
339
497
  && !normalize(result.remaining).includes(normalize(instruction)) ? result.remaining : undefined;
340
498
  const reason = setupReason(result.reason, remaining);
341
499
  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);
500
+ const observedField = typeof result.field === 'string' && result.field.trim()
501
+ && !normalize(instruction).includes(normalize(result.field))
502
+ && !normalize(result.field).includes(normalize(instruction)) ? result.field : undefined;
503
+ 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
504
  if (refusal)
344
505
  throw setupStopped(`Provider refused ${provider} signup; setup stopped`, reason);
345
506
  if (result.status === 'complete') {
346
507
  this.metadata = undefined; // A browser capture may have added a credential.
347
508
  await this.finishSession(provider, true);
509
+ this.serviceSignal(provider).throwIfAborted();
348
510
  return { run: { id: provider, state: 'completed' }, decision: 'silent' };
349
511
  }
350
512
  const uncertain = result.status === 'low_confidence' || result.status === 'no_progress';
513
+ const humanStep = /\b(?:sms|phone|captcha|passkey|email|e mail|verification|confirm(?:ation)?|human(?: only| input| assistance)?)\b/i.test(`${String(result.field)} ${classification}`);
514
+ if (this.options.background && (humanStep || uncertain || result.status === 'stuck'))
515
+ throw new Error('Provider signup needs verification; run usegrunt setup in the foreground to resume');
351
516
  if (uncertain && this.sessions.has(provider)) {
352
517
  const used = this.recoveryChoices.get(provider) ?? new Set();
353
518
  this.recoveryChoices.set(provider, used);
@@ -362,7 +527,12 @@ export class BrowserSquire {
362
527
  continue;
363
528
  }
364
529
  }
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}`);
530
+ // DONE is a driver choice, not evidence that the account meets the goal.
531
+ // Only the human can attest to every condition, and a generic captcha
532
+ // confirmation must never become an attestation of account/plan state.
533
+ const manualCompletion = uncertain && !humanStep
534
+ && !/\b(?:block(?:ed|ing)?|policy|restrict(?:ed|ion|ions)?)\b/i.test(`${classification} ${String(result.field)}`)
535
+ && object(result.options).DONE === 'The goal is complete';
366
536
  if (!humanStep && (result.status === 'budget' || result.status === 'evaluate_timeout'))
367
537
  return { run: { id: provider, state: 'running' }, decision: 'silent' };
368
538
  // A driver that cannot choose the next action still owns a resumable tab.
@@ -371,13 +541,17 @@ export class BrowserSquire {
371
541
  if (handoff && process.env.MILO_SETUP_NO_HUMAN === '1')
372
542
  throw new Error('Provider signup needs human verification; stopped before handoff');
373
543
  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' };
544
+ const handoffSession = this.sessions.get(provider);
545
+ const url = await this.humanHandoff(handoffSession);
546
+ this.serviceSignal(provider).throwIfAborted();
547
+ await this.scoped(this.verification.wait({ service: provider, url, ...(manualCompletion ? { goal: instruction } : {}) }), this.serviceSignal(provider));
548
+ this.serviceSignal(provider).throwIfAborted();
549
+ if (manualCompletion) {
550
+ if (this.sessions.get(provider) !== handoffSession)
551
+ throw new Error('Provider verification session changed; rerun setup');
552
+ answer = 'DONE';
553
+ continue;
379
554
  }
380
- await this.verification.wait({ service: provider, url });
381
555
  return { run: { id: provider, state: 'running' }, decision: 'silent' };
382
556
  }
383
557
  await this.finishSession(provider);
@@ -385,11 +559,18 @@ export class BrowserSquire {
385
559
  }
386
560
  }
387
561
  async humanHandoff(session) {
388
- const share = await this.call('operate_share', { session_id: session });
562
+ const provider = [...this.sessions].find(([, id]) => id === session)?.[0];
563
+ const share = await (provider ? this.serviceCall(provider, 'operate_share', { session_id: session }) : this.call('operate_share', { session_id: session }));
564
+ if (provider)
565
+ this.serviceSignal(provider).throwIfAborted();
389
566
  if (typeof share.url !== 'string')
390
567
  throw new Error('Squire returned no browser handoff link');
391
568
  const proxy = await proxyApproval(share.url);
392
- this.handoffs.push(proxy);
569
+ if (provider && this.serviceSignal(provider).aborted) {
570
+ proxy.close();
571
+ throw new Error('Provider signup cancelled');
572
+ }
573
+ this.handoffs.push({ ...proxy, ...(provider ? { provider } : {}) });
393
574
  return proxy.url;
394
575
  }
395
576
  runs = {
@@ -450,12 +631,58 @@ export class FreeLLMAdmin {
450
631
  await this.call(`/keys/${key.id}`, undefined, 'DELETE');
451
632
  }
452
633
  }
453
- async ensureFreeFallbacks() {
634
+ async migrateKiloModels(approved, savedChain) {
635
+ const chain = savedChain ?? await this.call('/fallback', undefined, 'GET');
636
+ const updates = chain.filter(row => managedSharingProvider(row) === 'kilo' && row.enabled !== false
637
+ && (obsoleteManagedKilo(row) || !approved.includes('kilo') || row.priority !== 999999))
638
+ .map(row => ({ modelDbId: row.modelDbId, enabled: approved.includes('kilo') && !obsoleteManagedKilo(row),
639
+ priority: obsoleteManagedKilo(row) || !approved.includes('kilo') ? row.priority : 999999 }));
640
+ // Quarantine before any catalog lookup/registration, so partial failures
641
+ // cannot leave a retired managed route enabled for the next request.
642
+ if (updates.length)
643
+ await this.call('/fallback', updates, 'PUT');
644
+ if (!approved.includes('kilo'))
645
+ return;
646
+ const keys = await this.call('/keys', undefined, 'GET');
647
+ const complete = new Set(keys.filter(key => key.platform === 'custom' && key.models?.some(model => model.modelId === KILO_PARTICLE)).map(key => key.baseUrl));
648
+ for (const key of keys) {
649
+ if (key.platform !== 'custom' || !['Kilo Free', 'Milo kilo (Squire)'].includes(key.label) || !Number.isInteger(key.id) || !key.id || key.id < 1
650
+ || !key.baseUrl || complete.has(key.baseUrl) || !Array.isArray(key.models))
651
+ continue;
652
+ const catalog = await this.call('/keys/custom/discover-models', { keyId: key.id });
653
+ if (!catalog.models.some(model => model.id === KILO_PARTICLE))
654
+ continue;
655
+ // The backend reuses this exact credential. Never read or replace it.
656
+ // Omitted capability flags preserve an existing custom row's settings;
657
+ // the backend already defaults newly inserted chat models to tools-on.
658
+ const registered = await this.call('/keys/custom', { keyId: key.id, models: [{ model: KILO_PARTICLE }] });
659
+ if (!Number.isInteger(registered.modelDbId) || !registered.modelDbId || registered.modelDbId < 1 || registered.model !== KILO_PARTICLE)
660
+ throw new Error('Legacy Kilo Particle registration could not be verified');
661
+ const created = registered.models?.find(model => model.modelDbId === registered.modelDbId && model.model === KILO_PARTICLE)?.created;
662
+ // A user may register/disable this model while catalog discovery runs.
663
+ // Upsert preserves existing fallback flags; only default a new row.
664
+ if (created === true || (created === undefined && registered.created === 1)) {
665
+ await this.call('/fallback', [{ modelDbId: registered.modelDbId, enabled: true, priority: 999999 }], 'PUT');
666
+ }
667
+ complete.add(key.baseUrl);
668
+ }
669
+ }
670
+ async ensureFreeFallbacks(dataSharingApproved) {
671
+ const approved = dataSharingApproved ?? await readDataSharingConsent(dirname(localAdminPath()), ['kilo']);
672
+ // Retired Grunt-owned rows stay quarantined even if a saved sharing receipt
673
+ // approved them. Disable before unrelated discovery can fail.
674
+ const chain = await this.call('/fallback', undefined, 'GET');
675
+ const retired = chain.filter(row => retiredManagedAdapter(row) && row.enabled !== false)
676
+ .map(row => ({ modelDbId: row.modelDbId, enabled: false, priority: row.priority }));
677
+ if (retired.length)
678
+ await this.call('/fallback', retired, 'PUT');
679
+ await this.migrateKiloModels(approved);
454
680
  const keys = await this.call('/keys', undefined, 'GET');
455
681
  for (const provider of freeConfig().customProviders) {
456
- if (!keys.some(key => key.platform === 'custom' && key.baseUrl === provider.baseUrl)) {
682
+ if (provider.label === 'Kilo Free' && !approved.includes('kilo'))
683
+ continue;
684
+ if (!keys.some(key => key.platform === 'custom' && key.baseUrl === provider.baseUrl))
457
685
  await this.call('/keys/custom', provider);
458
- }
459
686
  }
460
687
  }
461
688
  async configureChain(excluded = [], dataSharingApproved) {
@@ -465,11 +692,14 @@ export class FreeLLMAdmin {
465
692
  const provider = [...Object.keys(PROVIDERS), ...savedProviders].find(provider => row.keyLabel === `Milo ${provider} (Squire)`);
466
693
  const owned = managedSharingProvider(row);
467
694
  const fallback = !provider && owned !== undefined;
468
- const sharingAllowed = !owned || approved.includes(owned);
695
+ const retired = retiredManagedAdapter(row);
696
+ const sharingAllowed = !retired && (!owned || approved.includes(owned));
469
697
  const vetted = !provider || !providerModels[provider] || providerModels[provider].includes(row.modelId);
698
+ const disabledParticle = owned === 'kilo' && row.modelId === KILO_PARTICLE && row.enabled === false;
470
699
  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 };
700
+ enabled: sharingAllowed && !obsoleteManagedKilo(row) && !disabledParticle
701
+ && (fallback || (provider ? row.platform === 'custom' && vetted && !excluded.includes(provider) : row.enabled === true)),
702
+ priority: disabledParticle || retired ? row.priority : owned === 'kilo' ? 999999 : row.priority };
473
703
  });
474
704
  await this.call('/fallback', rows, 'PUT');
475
705
  await this.call('/fallback/routing', { strategy: 'priority' }, 'PUT');
@@ -591,28 +821,47 @@ async function saveLocalAdmin(admin) {
591
821
  function managedSharingProvider(row) {
592
822
  if (row.platform !== 'custom')
593
823
  return;
594
- if (row.keyLabel === 'Milo kilo (Squire)' || (row.keyLabel === 'Kilo Free' && row.modelId === 'kilo-auto/free'))
824
+ if (row.keyLabel === 'Milo kilo (Squire)' || row.keyLabel === 'Kilo Free')
595
825
  return 'kilo';
596
826
  if (row.keyLabel === 'Freebuff' && row.modelId === 'freebuff')
597
827
  return 'freebuff';
828
+ for (const provider of disabledAdapters)
829
+ if (row.keyLabel === `Milo ${provider} (Squire)`)
830
+ return provider;
598
831
  return;
599
832
  }
833
+ const obsoleteManagedKilo = (row) => managedSharingProvider(row) === 'kilo' && row.modelId !== KILO_PARTICLE;
834
+ // Keep legacy label recognition for retirement; never recreate these rows.
835
+ const retiredManagedAdapter = (row) => {
836
+ const provider = managedSharingProvider(row);
837
+ return provider !== undefined && disabledAdapters.has(provider);
838
+ };
600
839
  // Reconcile only Grunt-owned sharing rows before a legacy backend request. This
601
840
  // never provisions a router, changes custom rows, or enables a disabled row.
841
+ export class RouterSetupPending extends Error {
842
+ }
602
843
  export async function guardRouterSharing(url, directory) {
603
- const approved = await readDataSharingConsent(directory, ['kilo', 'freebuff']);
604
- if (approved.includes('kilo') && approved.includes('freebuff'))
605
- return;
844
+ const approved = await readDataSharingConsent(directory, ['kilo']);
606
845
  const admin = await readLocalAdmin(join(directory, 'router-admin.json'));
607
846
  if (!admin)
608
847
  throw new Error('Local router admin state is required to enforce data-sharing choices; rerun usegrunt setup');
609
848
  const router = new FreeLLMAdmin(url);
610
849
  await router.login(admin.password);
611
850
  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; })
851
+ const updates = chain.filter(row => { const provider = managedSharingProvider(row); return provider && (retiredManagedAdapter(row) || !approved.includes(provider) || obsoleteManagedKilo(row)) && row.enabled !== false; })
613
852
  .map(row => ({ modelDbId: row.modelDbId, enabled: false, priority: row.priority }));
614
853
  if (updates.length)
615
854
  await router.call('/fallback', updates, 'PUT');
855
+ const patched = chain.map(row => ({ ...row, ...updates.find(update => update.modelDbId === row.modelDbId) }));
856
+ const pending = (await readSetupSession(directory))?.pending;
857
+ if (patched.some(row => {
858
+ const provider = managedSharingProvider(row);
859
+ return provider && row.enabled !== false && pending?.has(provider);
860
+ }))
861
+ throw new RouterSetupPending('A managed provider is still being verified');
862
+ // An old aggregate backend must not create a new owned route before the
863
+ // corresponding direct source has passed its foreground verification.
864
+ await router.migrateKiloModels(approved.filter(provider => !pending?.has(provider)), patched);
616
865
  }
617
866
  // Read the login already created by setup; never provision or change router state.
618
867
  export async function loadRouterKey(url) {
@@ -697,6 +946,9 @@ function readyRouter(signal) {
697
946
  return starting;
698
947
  }
699
948
  export async function setup(notify = console.log, providers = ['groq'], options = {}) {
949
+ const retired = providers.find(provider => disabledAdapters.has(provider));
950
+ if (retired)
951
+ throw new Error(`${retired} routing is disabled`);
700
952
  const location = options.directory ?? process.env.MILO_CONFIG_DIR ?? join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
701
953
  const approved = [...new Set([...(options.dataSharingApproved ?? []), ...await readDataSharingConsent(location, DATA_SHARING_POLICIES.map(policy => policy.provider))])];
702
954
  const unapproved = dataSharingPolicies(providers).filter(policy => !approved.includes(policy.provider));
@@ -707,8 +959,37 @@ export async function setup(notify = console.log, providers = ['groq'], options
707
959
  options.squire.approveDataSharing(approved);
708
960
  const squire = options.squire ?? owned;
709
961
  try {
962
+ if (providers.includes('kilo')) {
963
+ await verifyKiloAccess({ ...(options.signal ? { signal: options.signal } : {}) });
964
+ notify('Kilo: free Particle-1 access verified; no account or API key required');
965
+ providers = providers.filter(provider => provider !== 'kilo');
966
+ }
967
+ // Idle sync only reuses verified state for these guarded sources. It never
968
+ // deletes their receipts, provisions a browser or changes account settings.
969
+ if (options.background) {
970
+ const browser = squire;
971
+ for (const provider of ['pollinations', 'beatapi', 'clixad', 'perch']) {
972
+ if (!providers.includes(provider))
973
+ continue;
974
+ await (provider === 'pollinations' ? setupPollinations : provider === 'beatapi' ? setupBeatAPI : provider === 'clixad' ? setupClixad : setupPerch)({ directory: location, squire: browser, background: true,
975
+ dataSharingApproved: approved, notify, ...(options.signal ? { signal: options.signal } : {}) });
976
+ providers = providers.filter(id => id !== provider);
977
+ }
978
+ }
979
+ if (!providers.length)
980
+ return {};
710
981
  await owned?.connect();
711
982
  options.signal?.throwIfAborted();
983
+ for (const provider of ['pollinations', 'beatapi', 'clixad', 'perch']) {
984
+ if (!providers.includes(provider))
985
+ continue;
986
+ const browser = squire;
987
+ if (typeof browser.signup !== 'function')
988
+ throw new Error(`${provider} signup requires a browser-capable Squire client`);
989
+ await (provider === 'pollinations' ? setupPollinations : provider === 'beatapi' ? setupBeatAPI : provider === 'clixad' ? setupClixad : setupPerch)({ directory: location, squire: browser,
990
+ dataSharingApproved: approved, notify, ...(options.signal ? { signal: options.signal } : {}) });
991
+ providers = providers.filter(id => id !== provider);
992
+ }
712
993
  if (providers.includes('livekit')) {
713
994
  const browser = squire;
714
995
  if (typeof browser.signup !== 'function')