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.
@@ -1,6 +1,7 @@
1
1
  import { promisify } from 'node:util';
2
2
  import { spawn, execFile } from 'node:child_process';
3
- import { mkdir, readFile, writeFile, cp, mkdtemp, rm, access } from 'node:fs/promises';
3
+ import { constants } from 'node:fs';
4
+ import { mkdir, readFile, writeFile, cp, mkdtemp, rm, access, lstat, open } from 'node:fs/promises';
4
5
  import { homedir, tmpdir } from 'node:os';
5
6
  import { dirname, join } from 'node:path';
6
7
  import { fileURLToPath, pathToFileURL } from 'node:url';
@@ -8,19 +9,22 @@ import { setTimeout as delay } from 'node:timers/promises';
8
9
  import { intro, outro, spinner, log, note, multiselect, isCancel } from '@clack/prompts';
9
10
  import chalk from 'chalk';
10
11
  import { setupFallbacks } from './fallback-setup.js';
11
- import { parallelMap } from './parallel.js';
12
+ import { parallelMap, SETUP_CONCURRENCY } from './parallel.js';
12
13
  import { withTerminal } from './terminal.js';
13
14
  import { DOCTOR_TIMEOUT_MS } from './freebuff.js';
14
15
  import { BrowserSquire, PROVIDERS, setup, squireEnvironment } from './setup.js';
15
16
  import { RegistrySync } from './registry.js';
16
- import { bundledRegistry, knownAdapters } from '../registry.js';
17
+ import { bundledRegistry, disabledAdapters, knownAdapters } from '../registry.js';
17
18
  import { banner } from './banner.js';
18
19
  import { approveDataSharing, requiresDataSharing } from './data-sharing.js';
19
- import { HARNESSES, configurePi, connectHarness, detectHarnesses } from './harnesses.js';
20
+ import { configurePi, connectHarness, detectHarnesses } from './harnesses.js';
21
+ import { beginSetupSession } from './setup-session.js';
20
22
  export const configDir = (env = process.env) => env.MILO_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
21
- export async function command(binary, args, interactive = false, signal) {
23
+ export async function command(binary, args, interactive = false, signal, env) {
24
+ signal?.throwIfAborted();
22
25
  const run = () => new Promise((resolve, reject) => {
23
- const child = spawn(binary, args, { stdio: interactive ? 'inherit' : 'ignore', ...(signal ? { signal } : {}) });
26
+ signal?.throwIfAborted();
27
+ const child = spawn(binary, args, { stdio: interactive ? 'inherit' : 'ignore', ...(signal ? { signal } : {}), ...(env ? { env } : {}) });
24
28
  child.once('error', () => reject(new Error(`Could not run ${binary}`)));
25
29
  child.once('exit', code => code === 0 ? resolve() : reject(new Error(`${binary} failed; inspect its service status before retrying`)));
26
30
  });
@@ -70,20 +74,56 @@ export async function squireBrokerExists() {
70
74
  const result = await promisify(execFile)(process.execPath, ['--input-type=module', '-e', program], { env: squireEnvironment(), timeout: 10000 });
71
75
  return result.stdout === 'present';
72
76
  }
73
- export async function connectSquire(options = {}) {
74
- const probe = async () => { const squire = options.squire ?? new BrowserSquire(); try {
75
- await squire.connect();
77
+ async function squireBootstrapEnvironment(signal) {
78
+ signal?.throwIfAborted();
79
+ const directory = configDir();
80
+ await mkdir(directory, { recursive: true, mode: 0o700 });
81
+ signal?.throwIfAborted();
82
+ const parent = await lstat(directory);
83
+ if (!parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid?.() || (parent.mode & 0o777) !== 0o700) {
84
+ throw new Error('Squire setup requires a private grunt configuration directory');
85
+ }
86
+ const path = join(directory, 'squire-opencode.json');
87
+ const file = await open(path, constants.O_RDWR | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
88
+ try {
89
+ const stat = await file.stat();
90
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || stat.size > 262144) {
91
+ throw new Error('Squire setup requires a private grunt-owned client configuration file');
92
+ }
93
+ signal?.throwIfAborted();
94
+ if (!stat.size)
95
+ await file.writeFile('{}\n');
76
96
  }
77
97
  finally {
78
- if (!options.squire)
79
- await squire.close();
80
- } };
98
+ await file.close();
99
+ }
100
+ signal?.throwIfAborted();
101
+ // The supported Squire override applies only to this installer child. It
102
+ // must never rewrite the user's OpenCode config or a provider grant config.
103
+ return { ...process.env, OPENCODE_CONFIG: path };
104
+ }
105
+ export async function connectSquire(options = {}) {
106
+ const probe = async () => {
107
+ options.signal?.throwIfAborted();
108
+ const squire = options.squire ?? new BrowserSquire(options.signal ? { signal: options.signal } : {});
109
+ try {
110
+ await squire.connect();
111
+ options.signal?.throwIfAborted();
112
+ }
113
+ finally {
114
+ if (!options.squire)
115
+ await squire.close();
116
+ }
117
+ };
81
118
  try {
82
119
  await probe();
83
120
  return;
84
121
  }
85
122
  catch (error) {
86
- if (await (options.hasBroker || squireBrokerExists)()) {
123
+ options.signal?.throwIfAborted();
124
+ const exists = await (options.hasBroker || squireBrokerExists)();
125
+ options.signal?.throwIfAborted();
126
+ if (exists) {
87
127
  throw new Error(`Existing trusty-squire-broker failed its connection probe: ${error instanceof Error ? error.message : String(error)}. Repair the broker, then rerun usegrunt setup.`, { cause: error });
88
128
  }
89
129
  }
@@ -91,7 +131,9 @@ export async function connectSquire(options = {}) {
91
131
  throw new Error('Squire login needs human verification; stopped before onboarding');
92
132
  // Only a machine without a broker may enter the installer.
93
133
  const bin = options.installer || join(dirname(fileURLToPath(import.meta.resolve('@trusty-squire/mcp'))), 'bin.js');
94
- await (options.run || command)(process.execPath, [bin, 'connect', '--target=opencode', '--json'], true);
134
+ const env = await squireBootstrapEnvironment(options.signal);
135
+ options.signal?.throwIfAborted();
136
+ await (options.run || command)(process.execPath, [bin, 'connect', '--target=opencode', '--json'], true, options.signal, env);
95
137
  await probe();
96
138
  }
97
139
  export async function preflight(run = command) {
@@ -134,9 +176,9 @@ const xml = (value) => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').re
134
176
  export async function installedSources(directory = configDir()) {
135
177
  try {
136
178
  const sources = JSON.parse(await readFile(join(directory, 'installed-sources.json'), 'utf8'));
137
- if (!Array.isArray(sources) || !sources.length || sources.some(id => typeof id !== 'string' || ![...knownAdapters, 'freellmapi'].includes(id)))
179
+ if (!Array.isArray(sources) || sources.some(id => typeof id !== 'string' || ![...knownAdapters, 'freellmapi'].includes(id)))
138
180
  throw new Error('Invalid saved grunt sources');
139
- return [...new Set(sources)].join(',');
181
+ return [...new Set(sources)].filter(id => !disabledAdapters.has(id)).join(',');
140
182
  }
141
183
  catch (error) {
142
184
  if (error.code !== 'ENOENT')
@@ -148,62 +190,80 @@ export async function installedSources(directory = configDir()) {
148
190
  catch (error) {
149
191
  if (error.code !== 'ENOENT')
150
192
  throw error;
151
- return 'freebuff,opencode,kilo,zro';
193
+ return 'opencode,kilo,zro';
152
194
  }
153
- return 'freellmapi,kilo,freebuff,opencode,zro';
195
+ return 'freellmapi,kilo,opencode,zro';
154
196
  }
155
- export async function installService(adapters) {
197
+ export async function installService(adapters, options = {}) {
198
+ const stage = async (operation) => {
199
+ options.signal?.throwIfAborted();
200
+ const result = await operation();
201
+ options.signal?.throwIfAborted();
202
+ return result;
203
+ };
204
+ options.signal?.throwIfAborted();
156
205
  if (!['linux', 'darwin'].includes(process.platform))
157
206
  throw new Error('grunt background service requires systemd or launchd');
207
+ const selected = [...new Set(adapters ?? (await stage(() => installedSources())).split(','))].filter(id => id && !disabledAdapters.has(id));
208
+ if (selected.some(id => !knownAdapters.has(id) && id !== 'freellmapi'))
209
+ throw new Error('Invalid grunt service selection');
158
210
  const directory = configDir(), runtime = join(directory, 'runtime');
159
211
  // npx cache entries can disappear. Keep a backend runtime outside that cache.
160
212
  const root = fileURLToPath(new URL('../../', import.meta.url));
161
- await mkdir(runtime, { recursive: true, mode: 0o700 });
162
- await cp(join(root, 'dist'), join(runtime, 'dist'), { recursive: true });
163
- const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
164
- await writeFile(join(runtime, 'package.json'), JSON.stringify({ name: 'milo-runtime', private: true, type: 'module', dependencies: pkg.dependencies }), { mode: 0o600 });
165
- await command('npm', ['install', '--prefix', runtime, '--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund']);
213
+ await stage(() => mkdir(runtime, { recursive: true, mode: 0o700 }));
214
+ await stage(() => cp(join(root, 'dist'), join(runtime, 'dist'), { recursive: true }));
215
+ const pkg = JSON.parse(await stage(() => readFile(join(root, 'package.json'), 'utf8')));
216
+ await stage(() => writeFile(join(runtime, 'package.json'), JSON.stringify({ name: 'milo-runtime', private: true, type: 'module', dependencies: pkg.dependencies }), { mode: 0o600 }));
217
+ await stage(() => command('npm', ['install', '--prefix', runtime, '--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund'], false, options.signal));
166
218
  const entry = join(runtime, 'dist', 'local', 'main.js');
167
219
  const port = process.env.MILO_PORT || '8788';
168
220
  if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535)
169
221
  throw new Error('Invalid grunt service port');
170
- const env = { GRUNT_DAEMON: '1', MILO_CONFIG_DIR: directory, MILO_PORT: port, MILO_SOURCES: adapters?.join(',') ?? await installedSources(directory), PATH: process.env.PATH || '/usr/local/bin:/usr/bin:/bin' };
222
+ const env = { GRUNT_DAEMON: '1', MILO_CONFIG_DIR: directory, MILO_PORT: port, MILO_SOURCES: selected.join(','), PATH: process.env.PATH || '/usr/local/bin:/usr/bin:/bin' };
171
223
  if (process.env.MILO_FREELLMAPI_URL)
172
224
  env.MILO_FREELLMAPI_URL = process.env.MILO_FREELLMAPI_URL;
173
225
  const opencodeConfig = join(directory, 'opencode-free.json');
174
226
  try {
175
- await readFile(opencodeConfig);
227
+ await stage(() => readFile(opencodeConfig));
176
228
  env.OPENCODE_CONFIG = opencodeConfig;
177
229
  }
178
230
  catch (error) {
179
231
  if (error.code !== 'ENOENT')
180
232
  throw error;
181
233
  }
182
- await installBackgroundService('milo', entry, env);
183
- await writeFile(join(directory, 'installed-sources.json'), JSON.stringify(env.MILO_SOURCES.split(',')), { mode: 0o600 });
234
+ await stage(() => installBackgroundService('milo', entry, env, options));
235
+ await stage(() => writeFile(join(directory, 'installed-sources.json'), JSON.stringify(selected), { mode: 0o600 }));
184
236
  }
185
- export async function installBackgroundService(name, entry, env) {
237
+ export async function installBackgroundService(name, entry, env, options = {}) {
238
+ const stage = async (operation) => {
239
+ options.signal?.throwIfAborted();
240
+ const result = await operation();
241
+ options.signal?.throwIfAborted();
242
+ return result;
243
+ };
244
+ const run = (binary, args) => stage(() => command(binary, args, false, options.signal));
245
+ options.signal?.throwIfAborted();
186
246
  if (!/^[a-z][a-z0-9-]*$/.test(name))
187
247
  throw new Error('Invalid service name');
188
248
  if (process.platform === 'linux') {
189
249
  const units = join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'systemd', 'user');
190
- await mkdir(units, { recursive: true });
191
- await writeFile(join(units, `${name}.service`), `[Unit]\nDescription=grunt model service\nAfter=network-online.target\n\n[Service]\nExecStart=${systemdQuote(process.execPath)} ${systemdQuote(entry)}\n${Object.entries(env).map(([key, value]) => `Environment=${systemdQuote(`${key}=${value}`)}`).join('\n')}\nRestart=on-failure\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`, { mode: 0o600 });
192
- await command('systemctl', ['--user', 'daemon-reload']);
193
- await command('systemctl', ['--user', 'enable', `${name}.service`]);
194
- await command('systemctl', ['--user', 'restart', `${name}.service`]);
250
+ await stage(() => mkdir(units, { recursive: true }));
251
+ await stage(() => writeFile(join(units, `${name}.service`), `[Unit]\nDescription=grunt model service\nAfter=network-online.target\n\n[Service]\nExecStart=${systemdQuote(process.execPath)} ${systemdQuote(entry)}\n${Object.entries(env).map(([key, value]) => `Environment=${systemdQuote(`${key}=${value}`)}`).join('\n')}\nRestart=on-failure\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`, { mode: 0o600 }));
252
+ await run('systemctl', ['--user', 'daemon-reload']);
253
+ await run('systemctl', ['--user', 'enable', `${name}.service`]);
254
+ await run('systemctl', ['--user', 'restart', `${name}.service`]);
195
255
  }
196
256
  else {
197
257
  const agents = join(homedir(), 'Library', 'LaunchAgents');
198
- await mkdir(agents, { recursive: true });
258
+ await stage(() => mkdir(agents, { recursive: true }));
199
259
  const plist = join(agents, `ai.${name}.service.plist`), domain = `gui/${process.getuid()}`;
200
- await writeFile(plist, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>ai.${name}.service</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(entry)}</string></array><key>EnvironmentVariables</key><dict>${Object.entries(env).map(([key, value]) => `<key>${xml(key)}</key><string>${xml(value)}</string>`).join('')}</dict><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>Umask</key><integer>63</integer></dict></plist>`, { mode: 0o600 });
201
- await command('launchctl', ['bootout', `${domain}/ai.${name}.service`]).catch(() => { });
202
- await command('launchctl', ['bootstrap', domain, plist]);
260
+ await stage(() => writeFile(plist, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>ai.${name}.service</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(entry)}</string></array><key>EnvironmentVariables</key><dict>${Object.entries(env).map(([key, value]) => `<key>${xml(key)}</key><string>${xml(value)}</string>`).join('')}</dict><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>Umask</key><integer>63</integer></dict></plist>`, { mode: 0o600 }));
261
+ await run('launchctl', ['bootout', `${domain}/ai.${name}.service`]).catch(() => { });
262
+ await run('launchctl', ['bootstrap', domain, plist]);
203
263
  }
204
264
  }
205
- // /v1/models asks every source whether it is available, and Freebuff runs `freebuff doctor` to answer.
206
- // Give each probe longer than that check, and stop after totalMs so a hung service still fails.
265
+ // /v1/models asks every source whether it is available. Bound the combined probe
266
+ // so a hung native CLI cannot leave the installer waiting forever.
207
267
  export async function checkService(port = 8788, totalMs = 90000) {
208
268
  const deadline = Date.now() + totalMs;
209
269
  while (Date.now() < deadline) {
@@ -255,10 +315,11 @@ export async function checkServiceSources(unavailable, notify = console.log, ada
255
315
  notify(`${id}: FAIL — ${unit.origin} sets MILO_SOURCES=${unit.sources.join(',')}, which lacks ${id}. Setup does not edit it; add ${id} there or remove that setting.`);
256
316
  }
257
317
  }
258
- export async function checkFallbackServices(unavailable, port = 8788, notify = console.log, adapters = ['freebuff', 'opencode'], wait = { limit: 180000, interval: 2000 }) {
318
+ export async function checkFallbackServices(unavailable, port = 8788, notify = console.log, adapters = ['opencode'], wait = { limit: 180000, interval: 2000 }) {
259
319
  const directory = await mkdtemp(join(tmpdir(), 'milo-free-check-'));
260
320
  try {
261
321
  for (const source of adapters) {
322
+ wait.signal?.throwIfAborted();
262
323
  if (unavailable.includes(source)) {
263
324
  notify(`${source}: FAIL — setup incomplete`);
264
325
  continue;
@@ -266,12 +327,13 @@ export async function checkFallbackServices(unavailable, port = 8788, notify = c
266
327
  const deadline = Date.now() + wait.limit;
267
328
  let failure, waiting = false;
268
329
  for (let attempt = 1;; attempt++) {
330
+ wait.signal?.throwIfAborted();
269
331
  let preparing = false;
270
332
  try {
271
333
  const response = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
272
334
  method: 'POST', headers: { 'Content-Type': 'application/json' },
273
335
  body: JSON.stringify({ model: source, cwd: directory, messages: [{ role: 'user', content: `Reply only: grunt is ready (${source}). Do not use tools or change files. Check ${attempt}.` }], stream: false, max_tokens: 256 }),
274
- signal: AbortSignal.timeout(120000)
336
+ signal: AbortSignal.any([AbortSignal.timeout(120000), ...(wait.signal ? [wait.signal] : [])])
275
337
  });
276
338
  preparing = response.headers.get('x-grunt-preparing')?.split(',').includes(source) ?? false;
277
339
  const answered = response.headers.get('x-grunt-source');
@@ -290,13 +352,13 @@ export async function checkFallbackServices(unavailable, port = 8788, notify = c
290
352
  }
291
353
  // Retry only while grunt still runs this adapter's background setup. Each attempt
292
354
  // is a new prompt, so the router does not keep a fallback source from an earlier try.
293
- if (!failure || !preparing || Date.now() + wait.interval > deadline)
355
+ if (!failure || wait.retryPreparing === false || !preparing || Date.now() + wait.interval > deadline)
294
356
  break;
295
357
  if (!waiting) {
296
358
  waiting = true;
297
359
  notify(`${source}: grunt is still preparing this adapter; waiting`);
298
360
  }
299
- await delay(wait.interval);
361
+ await delay(wait.interval, undefined, wait.signal ? { signal: wait.signal } : {});
300
362
  }
301
363
  if (failure) {
302
364
  unavailable.push(source);
@@ -332,19 +394,19 @@ const PREAMBLE = [
332
394
  'sends each request to a free service that can answer it.',
333
395
  '',
334
396
  'Setup will:',
335
- ' 1. Connect Trusty Squire (one Google sign-in)',
336
- ' 2. Pull the current list of free services from the grunt registry',
337
- ' 3. Sign up for each service, connect it to grunt and test it',
338
- ' 4. Connect grunt to the coding tools installed here'
397
+ ' 1. Pull the free service list and ask for grouped sharing approval',
398
+ ' 2. Start grunt and connect your coding tools when a source answers',
399
+ ' 3. Connect Trusty Squire when an account-based source needs it',
400
+ ' 4. Continue remaining signups and browser confirmations alongside use'
339
401
  ].join('\n');
340
402
  const SQUIRE_NOTICE = [
341
403
  'Some free services only work with an account. Trusty Squire is a local',
342
404
  'browser helper that signs up for them using their supported sign-in.',
343
405
  'Most use Google; Runcrate’s card-free access needs GitHub sign-in.',
344
406
  '',
345
- 'Next, a browser may open and ask you to sign in to Google once. If Trusty',
346
- 'Squire is already connected on this machine, setup reuses it. A captcha or',
347
- 'email check pauses setup until you finish it in the browser.'
407
+ 'Account-based setup may open a browser for Google sign-in. An existing',
408
+ 'Squire connection is reused. Anonymous sources can start first. A captcha',
409
+ 'or email check pauses only its source while other setup jobs continue.'
348
410
  ].join('\n');
349
411
  const mark = (status) => status === 'pass' ? chalk.green('✔') : status === 'fail' ? chalk.red('✘') : chalk.dim('–');
350
412
  const describe = (adapter) => [adapter.kind === 'agent' ? 'coding agent' : 'model API', adapter.model ? `free model ${adapter.model}` : undefined,
@@ -361,12 +423,12 @@ const report = (shown = new Set()) => (line) => {
361
423
  else
362
424
  log.info(line);
363
425
  };
364
- export async function connectHarnesses(port, options = {}) {
426
+ export async function prepareHarnesses(port, options = {}) {
365
427
  log.step('Connect grunt to your coding tools');
366
428
  const found = await detectHarnesses(options.harnesses);
367
429
  if (!found.length) {
368
- log.warn(`No supported coding tool found on PATH (${HARNESSES.map(h => h.binary).join(', ')}). Install one, then rerun usegrunt setup.`);
369
- return [];
430
+ log.info('No supported coding tool is currently installed. Grunt will become usable through its local API.');
431
+ return Object.assign(async () => [], { discoverLater: true });
370
432
  }
371
433
  log.info(`Found: ${found.map(h => h.name).join(', ')}. grunt is added as an extra, named option; your default model and provider stay as they are.`);
372
434
  const interactive = process.stdin.isTTY && process.stdout.isTTY && process.env.MILO_SETUP_NO_HUMAN !== '1';
@@ -377,52 +439,66 @@ export async function connectHarnesses(port, options = {}) {
377
439
  options: list.map(h => ({ value: h.id, label: h.name, hint: h.launch(port) })), initialValues: list.filter(h => h.id === 'pi').map(h => h.id) });
378
440
  return isCancel(picked) ? [] : list.filter(h => picked.includes(h.id));
379
441
  });
380
- const connected = [];
381
- for (const harness of await choose(found)) {
382
- const progress = spinner();
383
- progress.start(`${harness.name}: adding grunt and sending a test request through it`);
384
- try {
385
- const { change } = await connectHarness(harness, port, options.run);
386
- progress.stop(`${harness.name}: PASS — answered through grunt`);
387
- if (change?.backup)
388
- log.info(`${harness.name}: previous config saved as ${change.backup}`);
389
- connected.push(harness);
390
- }
391
- catch (error) {
392
- progress.error(`${harness.name}: FAIL — ${error instanceof Error ? error.message : String(error)}`);
442
+ // Choose once before provider jobs can request browser confirmations. Applying
443
+ // the saved choices later never reads stdin or waits for a Squire prompt.
444
+ const selected = await withTerminal(() => choose(found));
445
+ return async () => {
446
+ const connected = [];
447
+ for (const harness of selected) {
448
+ const progress = spinner();
449
+ progress.start(`${harness.name}: adding grunt and sending a test request through it`);
450
+ try {
451
+ const { change } = await connectHarness(harness, port, options.run);
452
+ progress.stop(`${harness.name}: PASS — answered through grunt`);
453
+ if (change?.backup)
454
+ log.info(`${harness.name}: previous config saved as ${change.backup}`);
455
+ connected.push(harness);
456
+ }
457
+ catch (error) {
458
+ progress.error(`${harness.name}: FAIL — ${error instanceof Error ? error.message : String(error)}`);
459
+ }
393
460
  }
394
- }
395
- if (connected.length)
396
- note(connected.map(h => `${chalk.bold(h.name)}\n ${h.launch(port)}`).join('\n'), 'Start coding with grunt');
397
- return connected;
461
+ if (connected.length)
462
+ note(connected.map(h => `${chalk.bold(h.name)}\n ${h.launch(port)}`).join('\n'), 'Start coding with grunt');
463
+ return connected;
464
+ };
465
+ }
466
+ export async function connectHarnesses(port, options = {}) {
467
+ return (await prepareHarnesses(port, options))();
398
468
  }
399
- const wizardActions = { installedSources, createSquire: () => new BrowserSquire(), banner, preflight, connectSquire, setup, setupFallbacks, installService, configurePi, checkService, checkFallbackServices, loadRegistry, checkServiceSources, connectHarnesses, approveDataSharing };
469
+ const wizardActions = { installedSources, createSquire: () => new BrowserSquire(), banner, preflight, connectSquire, setup, setupFallbacks, installService, configurePi, checkService, checkFallbackServices, loadRegistry, checkServiceSources, connectHarnesses, prepareHarnesses, approveDataSharing };
400
470
  export async function wizard(add, actions = wizardActions) {
471
+ if (add && disabledAdapters.has(add))
472
+ throw new Error(`${add} routing is disabled`);
401
473
  if (add && !Object.hasOwn(PROVIDERS, add))
402
474
  throw new Error(`Choose a supported provider: ${Object.keys(PROVIDERS).join(', ')}`);
403
475
  const squire = actions.createSquire?.();
476
+ let session;
477
+ let connection;
478
+ let closing;
479
+ let abortSetup;
480
+ const closeSquire = () => closing ??= (async () => { await squire?.close(); })();
481
+ const connect = () => connection ??= step('Connecting Trusty Squire', () => actions.connectSquire({ ...(squire ? { squire } : {}), ...(session ? { signal: session.signal } : {}) }));
404
482
  try {
405
483
  await actions.banner?.();
406
484
  intro(chalk.hex('#f4b41a').bold('grunt') + chalk.dim(' — npx usegrunt setup'));
407
485
  note(PREAMBLE, 'What grunt does');
408
486
  await step('Checking prerequisites', () => actions.preflight());
409
487
  note(SQUIRE_NOTICE, 'Google sign-in for Trusty Squire');
410
- await step('Connecting Trusty Squire', () => actions.connectSquire(squire ? { squire } : {}));
411
488
  // Capture legacy API routing before default Kilo setup creates its admin file.
412
- const previous = (await actions.installedSources?.())?.split(',') ?? [];
489
+ const previous = ((await actions.installedSources?.())?.split(',') ?? []).filter(id => id && !disabledAdapters.has(id));
413
490
  if (add) {
414
- const defaults = bundledRegistry.adapters.filter(adapter => knownAdapters.has(adapter.id)).map(adapter => adapter.id);
415
- const sources = ['kilo', 'nvidia', 'zro', 'tokenharbor', 'runcrate', 'apinex', 'mistral-vibe', 'livekit'].includes(add)
491
+ await connect();
492
+ const defaults = bundledRegistry.adapters.filter(adapter => knownAdapters.has(adapter.id) && !disabledAdapters.has(adapter.id)).map(adapter => adapter.id);
493
+ const sources = ['kilo', 'nvidia', 'zro', 'tokenharbor', 'runcrate', 'apinex', 'mistral-vibe', 'livekit', 'pollinations', 'beatapi', 'clixad', 'perch'].includes(add)
416
494
  ? [...new Set([...(previous.length ? previous : defaults), add])]
417
495
  : [...new Set(['freellmapi', ...previous, ...defaults])];
418
496
  const consent = await (actions.approveDataSharing ?? approveDataSharing)({ directory: configDir(), providers: sources });
419
497
  if (consent.skipped.includes(add)) {
420
498
  // A declined addition still needs to replace a previously installed
421
499
  // runtime that predates consent enforcement. Keep only prior choices.
422
- if (previous.length) {
423
- await step('Updating the grunt background service', () => actions.installService(previous));
424
- await step('Waiting for grunt to answer', () => actions.checkService(Number(process.env.MILO_PORT || '8788')));
425
- }
500
+ await step('Updating the grunt background service', () => actions.installService(previous));
501
+ await step('Waiting for grunt to answer', () => actions.checkService(Number(process.env.MILO_PORT || '8788')));
426
502
  outro(`${add} skipped; data sharing was not approved`);
427
503
  return;
428
504
  }
@@ -445,9 +521,9 @@ export async function wizard(add, actions = wizardActions) {
445
521
  log.info(`Registry: ${registry.adapters.length} free services, published ${published}`);
446
522
  else
447
523
  log.warn(`Registry unreachable; using the ${pulled.origin === 'cache' ? 'list saved by an earlier setup' : 'list bundled with this version'} (published ${published})`);
448
- const adapters = registry.adapters.filter(adapter => knownAdapters.has(adapter.id));
524
+ const adapters = registry.adapters.filter(adapter => knownAdapters.has(adapter.id) && !disabledAdapters.has(adapter.id));
449
525
  log.message(registry.adapters.map(adapter => knownAdapters.has(adapter.id)
450
- ? `${chalk.bold(adapter.id.padEnd(10))} ${chalk.dim(describe(adapter))}`
526
+ ? `${chalk.bold(adapter.id.padEnd(10))} ${chalk.dim(disabledAdapters.has(adapter.id) ? 'disabled pending integration review' : describe(adapter))}`
451
527
  : `${chalk.dim(adapter.id.padEnd(10))} ${chalk.dim('skipped: needs a newer usegrunt')}`).join('\n'));
452
528
  const requested = adapters.map(adapter => adapter.id);
453
529
  const consent = await (actions.approveDataSharing ?? approveDataSharing)({ directory: configDir(), providers: requested });
@@ -468,42 +544,140 @@ export async function wizard(add, actions = wizardActions) {
468
544
  outro('No approved free services are available; the background service now enforces your data-sharing choices');
469
545
  return;
470
546
  }
471
- log.step(`Installing and connecting ${ids.length} vetted free services (up to 3 at once)`);
472
- log.info('Trusty Squire reuses existing accounts and grants. Only free access is requested. Provider verification may still need your browser; verification prompts are queued.');
473
- const outcome = await actions.setupFallbacks({ directory: configDir(), run: command, adapters: ids, notify,
474
- ...(consent.approved.length ? { dataSharingApproved: consent.approved } : {}),
475
- ...(squire ? { squire, connect: () => squire.connect() } : {}) });
476
- unavailable.push(...outcome.unavailable);
477
- for (const id of ids)
478
- results.get(id).signup = unavailable.includes(id) ? 'fail' : 'pass';
479
- log.step('Connecting the services to the grunt daemon');
480
- await step('Starting the grunt background service', () => actions.installService([...new Set([...previous.filter(id => id === 'freellmapi'), ...ids])]));
481
547
  const port = Number(process.env.MILO_PORT || '8788');
482
- await step(`Waiting for grunt to answer at http://127.0.0.1:${port}`, () => actions.checkService(port));
483
- const beforeSources = new Set(unavailable);
484
- if (actions.checkServiceSources)
485
- await step('Checking which services the daemon runs', () => actions.checkServiceSources(unavailable, notify, ids));
486
- for (const id of ids)
487
- results.get(id).daemon = beforeSources.has(id) ? 'skip' : unavailable.includes(id) ? 'fail' : 'pass';
488
- log.step('Testing each service with a real request through grunt');
489
- await parallelMap(ids, async (id) => {
490
- const before = unavailable.includes(id);
491
- await actions.checkFallbackServices(unavailable, port, notify, [id]);
492
- results.get(id).check = before ? 'skip' : unavailable.includes(id) ? 'fail' : 'pass';
548
+ const harnessPlan = actions.prepareHarnesses ? await actions.prepareHarnesses(port) : undefined;
549
+ if (harnessPlan?.discoverLater)
550
+ log.info('Setup will check again for coding tools after provider installations finish.');
551
+ const applyHarnesses = harnessPlan ?? (async () => {
552
+ if (actions.connectHarnesses)
553
+ await actions.connectHarnesses(port);
554
+ else if (actions.configurePi)
555
+ await step('Pi provider', () => actions.configurePi(port));
493
556
  });
557
+ session = await beginSetupSession(configDir(), ids);
558
+ abortSetup = () => { void closeSquire().catch(() => { }); };
559
+ session.signal.addEventListener('abort', abortSetup, { once: true });
560
+ session.signal.throwIfAborted();
561
+ await step('Starting the grunt background service', () => actions.installService([...new Set([...previous.filter(id => id === 'freellmapi'), ...ids])], { signal: session.signal }));
562
+ await step(`Waiting for grunt to answer at http://127.0.0.1:${port}`, () => actions.checkService(port));
563
+ // Keep at most three real verification requests in flight without holding a
564
+ // provider-install worker. A queued check receives the released slot directly.
565
+ let activeChecks = 0;
566
+ const queuedChecks = [];
567
+ const check = async (task) => {
568
+ if (activeChecks < 3)
569
+ activeChecks++;
570
+ else
571
+ await new Promise(resolve => queuedChecks.push(resolve));
572
+ try {
573
+ return await task();
574
+ }
575
+ finally {
576
+ const next = queuedChecks.shift();
577
+ if (next)
578
+ next();
579
+ else
580
+ activeChecks--;
581
+ }
582
+ };
583
+ const settled = new Map();
584
+ let firstReady;
585
+ let readyCount = 0;
586
+ const firstAnswer = () => firstReady ??= (async () => {
587
+ log.success(`grunt is ready at http://127.0.0.1:${port}; a free provider answered`);
588
+ log.info('Start using grunt now. Keep this setup terminal open for remaining signups and browser confirmations; working requests do not wait for them.');
589
+ try {
590
+ await applyHarnesses();
591
+ }
592
+ catch {
593
+ log.warn('grunt is ready; coding-tool configuration needs attention. Rerun setup to finish connecting your tool.');
594
+ }
595
+ })();
596
+ const onSettled = (id, available) => {
597
+ if (!ids.includes(id))
598
+ return Promise.reject(new Error('Unexpected provider setup result'));
599
+ const previousResult = settled.get(id);
600
+ if (previousResult)
601
+ return previousResult;
602
+ const task = (async () => {
603
+ const result = results.get(id);
604
+ result.signup = available ? 'pass' : 'fail';
605
+ if (!available) {
606
+ if (!unavailable.includes(id))
607
+ unavailable.push(id);
608
+ result.daemon = result.check = 'skip';
609
+ notify(`${id}: FAIL — setup incomplete`);
610
+ return;
611
+ }
612
+ const passed = await check(async () => {
613
+ try {
614
+ session.signal.throwIfAborted();
615
+ await session.verify(id);
616
+ if (actions.checkServiceSources)
617
+ await actions.checkServiceSources(unavailable, notify, [id]);
618
+ result.daemon = unavailable.includes(id) ? 'fail' : 'pass';
619
+ if (result.daemon === 'fail') {
620
+ result.check = 'skip';
621
+ await session.hold(id);
622
+ return false;
623
+ }
624
+ await actions.checkFallbackServices(unavailable, port, notify, [id], { limit: 180000, interval: 2000, signal: session.signal, retryPreparing: false });
625
+ session.signal.throwIfAborted();
626
+ result.check = unavailable.includes(id) ? 'fail' : 'pass';
627
+ if (result.check === 'pass')
628
+ await session.release(id);
629
+ else
630
+ await session.hold(id);
631
+ session.signal.throwIfAborted();
632
+ return result.check === 'pass';
633
+ }
634
+ catch {
635
+ await session.hold(id).catch(() => { });
636
+ if (!unavailable.includes(id))
637
+ unavailable.push(id);
638
+ result.check = 'fail';
639
+ result.daemon ??= 'fail';
640
+ notify(`${id}: FAIL — verification incomplete; other ready sources continue`);
641
+ return false;
642
+ }
643
+ });
644
+ if (passed) {
645
+ readyCount++;
646
+ await firstAnswer();
647
+ }
648
+ })();
649
+ settled.set(id, task);
650
+ return task;
651
+ };
652
+ log.step(`Installing and connecting ${ids.length} vetted free services (up to ${SETUP_CONCURRENCY} at once)`);
653
+ log.info('Trusty Squire reuses existing accounts and grants. Only free access is requested. Sources become usable independently; verification prompts are queued.');
654
+ const outcome = await actions.setupFallbacks({ directory: configDir(), run: command, adapters: ids, notify, onSettled, connect,
655
+ signal: session.signal, ...(consent.approved.length ? { dataSharingApproved: consent.approved } : {}), ...(squire ? { squire } : {}) });
656
+ // Compatibility for injected setup implementations that return only a final
657
+ // result. Production emits settlement events as soon as each source finishes.
658
+ await parallelMap(ids, id => onSettled(id, !outcome.unavailable.includes(id)));
659
+ await Promise.all(settled.values());
660
+ session.signal.throwIfAborted();
494
661
  note([`${'service'.padEnd(10)} sign-in daemon test`, ...requested.map(id => {
495
662
  const r = results.get(id);
496
663
  return `${id.padEnd(10)} ${mark(r.signup)} ${mark(r.daemon)} ${mark(r.check)}`;
497
664
  })].join('\n'), 'Free services');
498
- if (actions.connectHarnesses)
665
+ if (!readyCount)
666
+ throw new Error('No adapters passed verification. Run usegrunt setup to resume.');
667
+ // OpenCode may have been installed by its provider job. Only rediscover
668
+ // when no tool existed initially, never after the user selected none.
669
+ if (harnessPlan?.discoverLater && actions.connectHarnesses)
499
670
  await actions.connectHarnesses(port);
500
- else if (actions.configurePi)
501
- await step('Pi provider', () => actions.configurePi(port));
502
671
  outro(unavailable.length ? `grunt is ready; incomplete fallbacks: ${unavailable.join(', ')}. Rerun setup to finish them.` : 'grunt is ready');
503
- if (unavailable.length)
504
- throw new Error('Some adapters failed verification. Run usegrunt setup to resume.');
505
672
  }
506
673
  finally {
507
- await squire?.close();
674
+ if (session && abortSetup)
675
+ session.signal.removeEventListener('abort', abortSetup);
676
+ try {
677
+ await closeSquire();
678
+ }
679
+ finally {
680
+ await session?.close();
681
+ }
508
682
  }
509
683
  }