usegrunt 0.6.6 → 0.6.8

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,8 @@
1
1
  import { promisify } from 'node:util';
2
+ import { randomUUID } from 'node:crypto';
2
3
  import { spawn, execFile } from 'node:child_process';
3
- import { mkdir, readFile, writeFile, cp, mkdtemp, rm, access } from 'node:fs/promises';
4
+ import { constants } from 'node:fs';
5
+ import { mkdir, readFile, writeFile, cp, mkdtemp, rm, access, lstat, open, rename } from 'node:fs/promises';
4
6
  import { homedir, tmpdir } from 'node:os';
5
7
  import { dirname, join } from 'node:path';
6
8
  import { fileURLToPath, pathToFileURL } from 'node:url';
@@ -9,18 +11,22 @@ import { intro, outro, spinner, log, note, multiselect, isCancel } from '@clack/
9
11
  import chalk from 'chalk';
10
12
  import { setupFallbacks } from './fallback-setup.js';
11
13
  import { parallelMap, SETUP_CONCURRENCY } from './parallel.js';
12
- import { withTerminal } from './terminal.js';
14
+ import { withTerminal, terminalBusy } from './terminal.js';
13
15
  import { DOCTOR_TIMEOUT_MS } from './freebuff.js';
14
16
  import { BrowserSquire, PROVIDERS, setup, squireEnvironment } from './setup.js';
15
17
  import { RegistrySync } from './registry.js';
16
18
  import { bundledRegistry, disabledAdapters, knownAdapters } from '../registry.js';
17
19
  import { banner } from './banner.js';
18
20
  import { approveDataSharing, requiresDataSharing } from './data-sharing.js';
19
- import { HARNESSES, configurePi, connectHarness, detectHarnesses } from './harnesses.js';
21
+ import { configurePi, connectHarness, detectHarnesses } from './harnesses.js';
22
+ import { beginSetupSession } from './setup-session.js';
23
+ import { startSetupDashboard, watchSetupDashboard } from './setup-dashboard.js';
20
24
  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) {
25
+ export async function command(binary, args, interactive = false, signal, env) {
26
+ signal?.throwIfAborted();
22
27
  const run = () => new Promise((resolve, reject) => {
23
- const child = spawn(binary, args, { stdio: interactive ? 'inherit' : 'ignore', ...(signal ? { signal } : {}) });
28
+ signal?.throwIfAborted();
29
+ const child = spawn(binary, args, { stdio: interactive ? 'inherit' : 'ignore', ...(signal ? { signal } : {}), ...(env ? { env } : {}) });
24
30
  child.once('error', () => reject(new Error(`Could not run ${binary}`)));
25
31
  child.once('exit', code => code === 0 ? resolve() : reject(new Error(`${binary} failed; inspect its service status before retrying`)));
26
32
  });
@@ -70,20 +76,56 @@ export async function squireBrokerExists() {
70
76
  const result = await promisify(execFile)(process.execPath, ['--input-type=module', '-e', program], { env: squireEnvironment(), timeout: 10000 });
71
77
  return result.stdout === 'present';
72
78
  }
73
- export async function connectSquire(options = {}) {
74
- const probe = async () => { const squire = options.squire ?? new BrowserSquire(); try {
75
- await squire.connect();
79
+ async function squireBootstrapEnvironment(signal) {
80
+ signal?.throwIfAborted();
81
+ const directory = configDir();
82
+ await mkdir(directory, { recursive: true, mode: 0o700 });
83
+ signal?.throwIfAborted();
84
+ const parent = await lstat(directory);
85
+ if (!parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid?.() || (parent.mode & 0o777) !== 0o700) {
86
+ throw new Error('Squire setup requires a private grunt configuration directory');
87
+ }
88
+ const path = join(directory, 'squire-opencode.json');
89
+ const file = await open(path, constants.O_RDWR | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
90
+ try {
91
+ const stat = await file.stat();
92
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || stat.size > 262144) {
93
+ throw new Error('Squire setup requires a private grunt-owned client configuration file');
94
+ }
95
+ signal?.throwIfAborted();
96
+ if (!stat.size)
97
+ await file.writeFile('{}\n');
76
98
  }
77
99
  finally {
78
- if (!options.squire)
79
- await squire.close();
80
- } };
100
+ await file.close();
101
+ }
102
+ signal?.throwIfAborted();
103
+ // The supported Squire override applies only to this installer child. It
104
+ // must never rewrite the user's OpenCode config or a provider grant config.
105
+ return { ...process.env, OPENCODE_CONFIG: path };
106
+ }
107
+ export async function connectSquire(options = {}) {
108
+ const probe = async () => {
109
+ options.signal?.throwIfAborted();
110
+ const squire = options.squire ?? new BrowserSquire(options.signal ? { signal: options.signal } : {});
111
+ try {
112
+ await squire.connect();
113
+ options.signal?.throwIfAborted();
114
+ }
115
+ finally {
116
+ if (!options.squire)
117
+ await squire.close();
118
+ }
119
+ };
81
120
  try {
82
121
  await probe();
83
122
  return;
84
123
  }
85
124
  catch (error) {
86
- if (await (options.hasBroker || squireBrokerExists)()) {
125
+ options.signal?.throwIfAborted();
126
+ const exists = await (options.hasBroker || squireBrokerExists)();
127
+ options.signal?.throwIfAborted();
128
+ if (exists) {
87
129
  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
130
  }
89
131
  }
@@ -91,7 +133,9 @@ export async function connectSquire(options = {}) {
91
133
  throw new Error('Squire login needs human verification; stopped before onboarding');
92
134
  // Only a machine without a broker may enter the installer.
93
135
  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);
136
+ const env = await squireBootstrapEnvironment(options.signal);
137
+ options.signal?.throwIfAborted();
138
+ await (options.run || command)(process.execPath, [bin, 'connect', '--target=opencode', '--json'], true, options.signal, env);
95
139
  await probe();
96
140
  }
97
141
  export async function preflight(run = command) {
@@ -152,20 +196,27 @@ export async function installedSources(directory = configDir()) {
152
196
  }
153
197
  return 'freellmapi,kilo,opencode,zro';
154
198
  }
155
- export async function installService(adapters) {
199
+ export async function installService(adapters, options = {}) {
200
+ const stage = async (operation) => {
201
+ options.signal?.throwIfAborted();
202
+ const result = await operation();
203
+ options.signal?.throwIfAborted();
204
+ return result;
205
+ };
206
+ options.signal?.throwIfAborted();
156
207
  if (!['linux', 'darwin'].includes(process.platform))
157
208
  throw new Error('grunt background service requires systemd or launchd');
158
- const selected = [...new Set(adapters ?? (await installedSources()).split(','))].filter(id => id && !disabledAdapters.has(id));
209
+ const selected = [...new Set(adapters ?? (await stage(() => installedSources())).split(','))].filter(id => id && !disabledAdapters.has(id));
159
210
  if (selected.some(id => !knownAdapters.has(id) && id !== 'freellmapi'))
160
211
  throw new Error('Invalid grunt service selection');
161
212
  const directory = configDir(), runtime = join(directory, 'runtime');
162
213
  // npx cache entries can disappear. Keep a backend runtime outside that cache.
163
214
  const root = fileURLToPath(new URL('../../', import.meta.url));
164
- await mkdir(runtime, { recursive: true, mode: 0o700 });
165
- await cp(join(root, 'dist'), join(runtime, 'dist'), { recursive: true });
166
- const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
167
- await writeFile(join(runtime, 'package.json'), JSON.stringify({ name: 'milo-runtime', private: true, type: 'module', dependencies: pkg.dependencies }), { mode: 0o600 });
168
- await command('npm', ['install', '--prefix', runtime, '--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund']);
215
+ await stage(() => mkdir(runtime, { recursive: true, mode: 0o700 }));
216
+ await stage(() => cp(join(root, 'dist'), join(runtime, 'dist'), { recursive: true }));
217
+ const pkg = JSON.parse(await stage(() => readFile(join(root, 'package.json'), 'utf8')));
218
+ await stage(() => writeFile(join(runtime, 'package.json'), JSON.stringify({ name: 'milo-runtime', private: true, type: 'module', dependencies: pkg.dependencies }), { mode: 0o600 }));
219
+ await stage(() => command('npm', ['install', '--prefix', runtime, '--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund'], false, options.signal));
169
220
  const entry = join(runtime, 'dist', 'local', 'main.js');
170
221
  const port = process.env.MILO_PORT || '8788';
171
222
  if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535)
@@ -175,34 +226,50 @@ export async function installService(adapters) {
175
226
  env.MILO_FREELLMAPI_URL = process.env.MILO_FREELLMAPI_URL;
176
227
  const opencodeConfig = join(directory, 'opencode-free.json');
177
228
  try {
178
- await readFile(opencodeConfig);
229
+ await stage(() => readFile(opencodeConfig));
179
230
  env.OPENCODE_CONFIG = opencodeConfig;
180
231
  }
181
232
  catch (error) {
182
233
  if (error.code !== 'ENOENT')
183
234
  throw error;
184
235
  }
185
- await installBackgroundService('milo', entry, env);
186
- await writeFile(join(directory, 'installed-sources.json'), JSON.stringify(selected), { mode: 0o600 });
236
+ await stage(() => installBackgroundService('milo', entry, env, options));
237
+ await stage(() => writeFile(join(directory, 'installed-sources.json'), JSON.stringify(selected), { mode: 0o600 }));
238
+ const portStage = join(directory, `.installed-port-${randomUUID()}`);
239
+ try {
240
+ await stage(() => writeFile(portStage, JSON.stringify(Number(port)), { flag: 'wx', mode: 0o600 }));
241
+ await stage(() => rename(portStage, join(directory, 'installed-port.json')));
242
+ }
243
+ finally {
244
+ await rm(portStage, { force: true });
245
+ }
187
246
  }
188
- export async function installBackgroundService(name, entry, env) {
247
+ export async function installBackgroundService(name, entry, env, options = {}) {
248
+ const stage = async (operation) => {
249
+ options.signal?.throwIfAborted();
250
+ const result = await operation();
251
+ options.signal?.throwIfAborted();
252
+ return result;
253
+ };
254
+ const run = (binary, args) => stage(() => command(binary, args, false, options.signal));
255
+ options.signal?.throwIfAborted();
189
256
  if (!/^[a-z][a-z0-9-]*$/.test(name))
190
257
  throw new Error('Invalid service name');
191
258
  if (process.platform === 'linux') {
192
259
  const units = join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'systemd', 'user');
193
- await mkdir(units, { recursive: true });
194
- 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 });
195
- await command('systemctl', ['--user', 'daemon-reload']);
196
- await command('systemctl', ['--user', 'enable', `${name}.service`]);
197
- await command('systemctl', ['--user', 'restart', `${name}.service`]);
260
+ await stage(() => mkdir(units, { recursive: true }));
261
+ 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 }));
262
+ await run('systemctl', ['--user', 'daemon-reload']);
263
+ await run('systemctl', ['--user', 'enable', `${name}.service`]);
264
+ await run('systemctl', ['--user', 'restart', `${name}.service`]);
198
265
  }
199
266
  else {
200
267
  const agents = join(homedir(), 'Library', 'LaunchAgents');
201
- await mkdir(agents, { recursive: true });
268
+ await stage(() => mkdir(agents, { recursive: true }));
202
269
  const plist = join(agents, `ai.${name}.service.plist`), domain = `gui/${process.getuid()}`;
203
- 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 });
204
- await command('launchctl', ['bootout', `${domain}/ai.${name}.service`]).catch(() => { });
205
- await command('launchctl', ['bootstrap', domain, plist]);
270
+ 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 }));
271
+ await run('launchctl', ['bootout', `${domain}/ai.${name}.service`]).catch(() => { });
272
+ await run('launchctl', ['bootstrap', domain, plist]);
206
273
  }
207
274
  }
208
275
  // /v1/models asks every source whether it is available. Bound the combined probe
@@ -262,6 +329,7 @@ export async function checkFallbackServices(unavailable, port = 8788, notify = c
262
329
  const directory = await mkdtemp(join(tmpdir(), 'milo-free-check-'));
263
330
  try {
264
331
  for (const source of adapters) {
332
+ wait.signal?.throwIfAborted();
265
333
  if (unavailable.includes(source)) {
266
334
  notify(`${source}: FAIL — setup incomplete`);
267
335
  continue;
@@ -269,12 +337,13 @@ export async function checkFallbackServices(unavailable, port = 8788, notify = c
269
337
  const deadline = Date.now() + wait.limit;
270
338
  let failure, waiting = false;
271
339
  for (let attempt = 1;; attempt++) {
340
+ wait.signal?.throwIfAborted();
272
341
  let preparing = false;
273
342
  try {
274
343
  const response = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
275
344
  method: 'POST', headers: { 'Content-Type': 'application/json' },
276
345
  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 }),
277
- signal: AbortSignal.timeout(120000)
346
+ signal: AbortSignal.any([AbortSignal.timeout(120000), ...(wait.signal ? [wait.signal] : [])])
278
347
  });
279
348
  preparing = response.headers.get('x-grunt-preparing')?.split(',').includes(source) ?? false;
280
349
  const answered = response.headers.get('x-grunt-source');
@@ -293,13 +362,13 @@ export async function checkFallbackServices(unavailable, port = 8788, notify = c
293
362
  }
294
363
  // Retry only while grunt still runs this adapter's background setup. Each attempt
295
364
  // is a new prompt, so the router does not keep a fallback source from an earlier try.
296
- if (!failure || !preparing || Date.now() + wait.interval > deadline)
365
+ if (!failure || wait.retryPreparing === false || !preparing || Date.now() + wait.interval > deadline)
297
366
  break;
298
367
  if (!waiting) {
299
368
  waiting = true;
300
369
  notify(`${source}: grunt is still preparing this adapter; waiting`);
301
370
  }
302
- await delay(wait.interval);
371
+ await delay(wait.interval, undefined, wait.signal ? { signal: wait.signal } : {});
303
372
  }
304
373
  if (failure) {
305
374
  unavailable.push(source);
@@ -335,19 +404,19 @@ const PREAMBLE = [
335
404
  'sends each request to a free service that can answer it.',
336
405
  '',
337
406
  'Setup will:',
338
- ' 1. Connect Trusty Squire (one Google sign-in)',
339
- ' 2. Pull the current list of free services from the grunt registry',
340
- ' 3. Sign up for each service, connect it to grunt and test it',
341
- ' 4. Connect grunt to the coding tools installed here'
407
+ ' 1. Pull the free service list and ask for grouped sharing approval',
408
+ ' 2. Start grunt and connect your coding tools when a source answers',
409
+ ' 3. Connect Trusty Squire when an account-based source needs it',
410
+ ' 4. Continue remaining signups and browser confirmations alongside use'
342
411
  ].join('\n');
343
412
  const SQUIRE_NOTICE = [
344
413
  'Some free services only work with an account. Trusty Squire is a local',
345
414
  'browser helper that signs up for them using their supported sign-in.',
346
415
  'Most use Google; Runcrate’s card-free access needs GitHub sign-in.',
347
416
  '',
348
- 'Next, a browser may open and ask you to sign in to Google once. If Trusty',
349
- 'Squire is already connected on this machine, setup reuses it. A captcha or',
350
- 'email check pauses setup until you finish it in the browser.'
417
+ 'Account-based setup may open a browser for Google sign-in. An existing',
418
+ 'Squire connection is reused. Anonymous sources can start first. A captcha',
419
+ 'or email check pauses only its source while other setup jobs continue.'
351
420
  ].join('\n');
352
421
  const mark = (status) => status === 'pass' ? chalk.green('✔') : status === 'fail' ? chalk.red('✘') : chalk.dim('–');
353
422
  const describe = (adapter) => [adapter.kind === 'agent' ? 'coding agent' : 'model API', adapter.model ? `free model ${adapter.model}` : undefined,
@@ -364,14 +433,26 @@ const report = (shown = new Set()) => (line) => {
364
433
  else
365
434
  log.info(line);
366
435
  };
367
- export async function connectHarnesses(port, options = {}) {
368
- log.step('Connect grunt to your coding tools');
436
+ // Only short UI writes enter this queue. Provider probes and coding-tool
437
+ // configuration keep running while a browser confirmation owns stdin.
438
+ const pendingUi = new Set();
439
+ function queueUi(write) {
440
+ const task = withTerminal(async () => { write(); }).catch(() => { });
441
+ pendingUi.add(task);
442
+ void task.then(() => { pendingUi.delete(task); });
443
+ }
444
+ async function drainUi() {
445
+ while (pendingUi.size)
446
+ await Promise.all([...pendingUi]);
447
+ }
448
+ export async function prepareHarnesses(port, options = {}) {
449
+ queueUi(() => log.step('Connect grunt to your coding tools'));
369
450
  const found = await detectHarnesses(options.harnesses);
370
451
  if (!found.length) {
371
- log.warn(`No supported coding tool found on PATH (${HARNESSES.map(h => h.binary).join(', ')}). Install one, then rerun usegrunt setup.`);
372
- return [];
452
+ queueUi(() => log.info('No supported coding tool is currently installed. Grunt will become usable through its local API.'));
453
+ return Object.assign(async () => [], { discoverLater: true });
373
454
  }
374
- 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.`);
455
+ queueUi(() => 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.`));
375
456
  const interactive = process.stdin.isTTY && process.stdout.isTTY && process.env.MILO_SETUP_NO_HUMAN !== '1';
376
457
  const choose = options.choose ?? (async (list) => {
377
458
  if (!interactive)
@@ -380,42 +461,86 @@ export async function connectHarnesses(port, options = {}) {
380
461
  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) });
381
462
  return isCancel(picked) ? [] : list.filter(h => picked.includes(h.id));
382
463
  });
383
- const connected = [];
384
- for (const harness of await choose(found)) {
385
- const progress = spinner();
386
- progress.start(`${harness.name}: adding grunt and sending a test request through it`);
387
- try {
388
- const { change } = await connectHarness(harness, port, options.run);
389
- progress.stop(`${harness.name}: PASS — answered through grunt`);
390
- if (change?.backup)
391
- log.info(`${harness.name}: previous config saved as ${change.backup}`);
392
- connected.push(harness);
393
- }
394
- catch (error) {
395
- progress.error(`${harness.name}: FAIL — ${error instanceof Error ? error.message : String(error)}`);
464
+ // Choose once before provider jobs can request browser confirmations. Applying
465
+ // the saved choices later never reads stdin or waits for a Squire prompt.
466
+ const selected = await withTerminal(() => choose(found));
467
+ return async () => {
468
+ const connected = [];
469
+ for (const harness of selected) {
470
+ queueUi(() => log.step(`${harness.name}: adding grunt and sending a test request through it`));
471
+ try {
472
+ const { change } = await connectHarness(harness, port, options.run);
473
+ queueUi(() => {
474
+ log.success(`${harness.name}: PASS — answered through grunt`);
475
+ if (change?.backup)
476
+ log.info(`${harness.name}: previous config saved as ${change.backup}`);
477
+ });
478
+ connected.push(harness);
479
+ }
480
+ catch (error) {
481
+ queueUi(() => log.error(`${harness.name}: FAIL — ${error instanceof Error ? error.message : String(error)}`));
482
+ }
396
483
  }
397
- }
398
- if (connected.length)
399
- note(connected.map(h => `${chalk.bold(h.name)}\n ${h.launch(port)}`).join('\n'), 'Start coding with grunt');
400
- return connected;
484
+ if (connected.length)
485
+ queueUi(() => note(connected.map(h => `${chalk.bold(h.name)}\n ${h.launch(port)}`).join('\n'), 'Start coding with grunt'));
486
+ return connected;
487
+ };
401
488
  }
402
- const wizardActions = { installedSources, createSquire: () => new BrowserSquire(), banner, preflight, connectSquire, setup, setupFallbacks, installService, configurePi, checkService, checkFallbackServices, loadRegistry, checkServiceSources, connectHarnesses, approveDataSharing };
489
+ export async function connectHarnesses(port, options = {}) {
490
+ return (await prepareHarnesses(port, options))();
491
+ }
492
+ const wizardActions = { installedSources, createSquire: () => new BrowserSquire(), banner, preflight, connectSquire, setup, setupFallbacks, installService, configurePi, checkService, checkFallbackServices, loadRegistry, checkServiceSources, connectHarnesses, prepareHarnesses, approveDataSharing, startDashboard: startSetupDashboard, watchDashboard: watchSetupDashboard };
403
493
  export async function wizard(add, actions = wizardActions) {
404
494
  if (add && disabledAdapters.has(add))
405
495
  throw new Error(`${add} routing is disabled`);
406
496
  if (add && !Object.hasOwn(PROVIDERS, add))
407
497
  throw new Error(`Choose a supported provider: ${Object.keys(PROVIDERS).join(', ')}`);
408
498
  const squire = actions.createSquire?.();
499
+ let session;
500
+ let connection;
501
+ let closing;
502
+ let abortSetup;
503
+ let dashboard;
504
+ let watchPort;
505
+ let stopVerificationStatus;
506
+ let verificationStatus = Promise.resolve();
507
+ const queuedReports = [];
508
+ const showReport = report();
509
+ const notify = (line) => {
510
+ // Redraws and background progress must never overwrite a foreground
511
+ // confirmation. Preserve routine messages for the final normal screen.
512
+ if (dashboard || terminalBusy()) {
513
+ if (queuedReports.length < 512)
514
+ queuedReports.push(line);
515
+ }
516
+ else
517
+ showReport(line);
518
+ };
519
+ const stopDashboard = async () => {
520
+ const display = dashboard;
521
+ dashboard = undefined;
522
+ await display?.stop().catch(() => { });
523
+ const lines = queuedReports.splice(0);
524
+ if (lines.length)
525
+ queueUi(() => { for (const line of lines)
526
+ showReport(line); });
527
+ };
528
+ const closeSquire = () => closing ??= (async () => { await squire?.close(); })();
529
+ const connect = () => connection ??= (async () => {
530
+ // A long-running spinner would compete with the live source dashboard.
531
+ notify('Connecting Trusty Squire');
532
+ await actions.connectSquire({ ...(squire ? { squire } : {}), ...(session ? { signal: session.signal } : {}) });
533
+ })();
409
534
  try {
410
535
  await actions.banner?.();
411
536
  intro(chalk.hex('#f4b41a').bold('grunt') + chalk.dim(' — npx usegrunt setup'));
412
537
  note(PREAMBLE, 'What grunt does');
413
538
  await step('Checking prerequisites', () => actions.preflight());
414
539
  note(SQUIRE_NOTICE, 'Google sign-in for Trusty Squire');
415
- await step('Connecting Trusty Squire', () => actions.connectSquire(squire ? { squire } : {}));
416
540
  // Capture legacy API routing before default Kilo setup creates its admin file.
417
541
  const previous = ((await actions.installedSources?.())?.split(',') ?? []).filter(id => id && !disabledAdapters.has(id));
418
542
  if (add) {
543
+ await connect();
419
544
  const defaults = bundledRegistry.adapters.filter(adapter => knownAdapters.has(adapter.id) && !disabledAdapters.has(adapter.id)).map(adapter => adapter.id);
420
545
  const sources = ['kilo', 'nvidia', 'zro', 'tokenharbor', 'runcrate', 'apinex', 'mistral-vibe', 'livekit', 'pollinations', 'beatapi', 'clixad', 'perch'].includes(add)
421
546
  ? [...new Set([...(previous.length ? previous : defaults), add])]
@@ -458,7 +583,6 @@ export async function wizard(add, actions = wizardActions) {
458
583
  const ids = requested.filter(id => !consent.skipped.includes(id));
459
584
  const results = new Map(requested.map(id => [id, consent.skipped.includes(id) ? { signup: 'skip', daemon: 'skip', check: 'skip' } : {}]));
460
585
  const unavailable = [];
461
- const notify = report();
462
586
  if (consent.skipped.length)
463
587
  log.info(`Skipped data-sharing services: ${consent.skipped.join(', ')}. Other free services continue.`);
464
588
  if (!ids.length) {
@@ -471,42 +595,173 @@ export async function wizard(add, actions = wizardActions) {
471
595
  outro('No approved free services are available; the background service now enforces your data-sharing choices');
472
596
  return;
473
597
  }
474
- log.step(`Installing and connecting ${ids.length} vetted free services (up to ${SETUP_CONCURRENCY} at once)`);
475
- 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.');
476
- const outcome = await actions.setupFallbacks({ directory: configDir(), run: command, adapters: ids, notify,
477
- ...(consent.approved.length ? { dataSharingApproved: consent.approved } : {}),
478
- ...(squire ? { squire, connect: () => squire.connect() } : {}) });
479
- unavailable.push(...outcome.unavailable);
480
- for (const id of ids)
481
- results.get(id).signup = unavailable.includes(id) ? 'fail' : 'pass';
482
- log.step('Connecting the services to the grunt daemon');
483
- await step('Starting the grunt background service', () => actions.installService([...new Set([...previous.filter(id => id === 'freellmapi'), ...ids])]));
484
598
  const port = Number(process.env.MILO_PORT || '8788');
485
- await step(`Waiting for grunt to answer at http://127.0.0.1:${port}`, () => actions.checkService(port));
486
- const beforeSources = new Set(unavailable);
487
- if (actions.checkServiceSources)
488
- await step('Checking which services the daemon runs', () => actions.checkServiceSources(unavailable, notify, ids));
489
- for (const id of ids)
490
- results.get(id).daemon = beforeSources.has(id) ? 'skip' : unavailable.includes(id) ? 'fail' : 'pass';
491
- log.step('Testing each service with a real request through grunt');
492
- await parallelMap(ids, async (id) => {
493
- const before = unavailable.includes(id);
494
- await actions.checkFallbackServices(unavailable, port, notify, [id]);
495
- results.get(id).check = before ? 'skip' : unavailable.includes(id) ? 'fail' : 'pass';
599
+ const harnessPlan = actions.prepareHarnesses ? await actions.prepareHarnesses(port) : undefined;
600
+ if (harnessPlan?.discoverLater)
601
+ log.info('Setup will check again for coding tools after provider installations finish.');
602
+ const applyHarnesses = harnessPlan ?? (async () => {
603
+ if (actions.connectHarnesses)
604
+ await actions.connectHarnesses(port);
605
+ else if (actions.configurePi) {
606
+ queueUi(() => log.step('Pi provider'));
607
+ await actions.configurePi(port);
608
+ queueUi(() => log.success('Pi provider configured'));
609
+ }
610
+ });
611
+ session = await beginSetupSession(configDir(), ids);
612
+ const activeSession = session;
613
+ stopVerificationStatus = squire?.onVerificationChange?.(services => {
614
+ const selected = services.filter(id => ids.includes(id));
615
+ verificationStatus = verificationStatus.then(() => activeSession.setApprovals?.(selected)).catch(() => {
616
+ // Lease writes enforce ownership independently; never echo exception
617
+ // payloads or interfere with the human's confirmation terminal.
618
+ });
496
619
  });
497
- note([`${'service'.padEnd(10)} sign-in daemon test`, ...requested.map(id => {
620
+ abortSetup = () => { void closeSquire().catch(() => { }); };
621
+ session.signal.addEventListener('abort', abortSetup, { once: true });
622
+ session.signal.throwIfAborted();
623
+ await step('Starting the grunt background service', () => actions.installService([...new Set([...previous.filter(id => id === 'freellmapi'), ...ids])], { signal: session.signal }));
624
+ await step(`Waiting for grunt to answer at http://127.0.0.1:${port}`, () => actions.checkService(port));
625
+ // Keep at most three real verification requests in flight without holding a
626
+ // provider-install worker. A queued check receives the released slot directly.
627
+ let activeChecks = 0;
628
+ const queuedChecks = [];
629
+ const check = async (task) => {
630
+ if (activeChecks < 3)
631
+ activeChecks++;
632
+ else
633
+ await new Promise(resolve => queuedChecks.push(resolve));
634
+ try {
635
+ return await task();
636
+ }
637
+ finally {
638
+ const next = queuedChecks.shift();
639
+ if (next)
640
+ next();
641
+ else
642
+ activeChecks--;
643
+ }
644
+ };
645
+ const settled = new Map();
646
+ let firstReady;
647
+ let readyCount = 0;
648
+ const firstAnswer = () => firstReady ??= (async () => {
649
+ queueUi(() => {
650
+ log.success(`grunt is ready at http://127.0.0.1:${port}; a free provider answered`);
651
+ log.info('Start using grunt now. Keep this setup terminal open for remaining signups and browser confirmations; working requests do not wait for them.');
652
+ });
653
+ try {
654
+ await applyHarnesses();
655
+ }
656
+ catch {
657
+ queueUi(() => log.warn('grunt is ready; coding-tool configuration needs attention. Rerun setup to finish connecting your tool.'));
658
+ }
659
+ queueUi(() => log.info(`Source dashboard: npx usegrunt status --watch --port ${port}`));
660
+ try {
661
+ dashboard = actions.startDashboard?.({ port, signal: session.signal, approvals: () => squire?.pendingVerificationServices() ?? [] });
662
+ }
663
+ catch {
664
+ queueUi(() => log.info('Live source view unavailable; setup continues. Reopen it with the status command above.'));
665
+ }
666
+ })();
667
+ const onSettled = (id, available) => {
668
+ if (!ids.includes(id))
669
+ return Promise.reject(new Error('Unexpected provider setup result'));
670
+ const previousResult = settled.get(id);
671
+ if (previousResult)
672
+ return previousResult;
673
+ const task = (async () => {
674
+ const result = results.get(id);
675
+ result.signup = available ? 'pass' : 'fail';
676
+ if (!available) {
677
+ if (!unavailable.includes(id))
678
+ unavailable.push(id);
679
+ result.daemon = result.check = 'skip';
680
+ notify(`${id}: FAIL — setup incomplete`);
681
+ return;
682
+ }
683
+ const passed = await check(async () => {
684
+ try {
685
+ session.signal.throwIfAborted();
686
+ await session.verify(id);
687
+ if (actions.checkServiceSources)
688
+ await actions.checkServiceSources(unavailable, notify, [id]);
689
+ result.daemon = unavailable.includes(id) ? 'fail' : 'pass';
690
+ if (result.daemon === 'fail') {
691
+ result.check = 'skip';
692
+ await session.hold(id);
693
+ return false;
694
+ }
695
+ await actions.checkFallbackServices(unavailable, port, notify, [id], { limit: 180000, interval: 2000, signal: session.signal, retryPreparing: false });
696
+ session.signal.throwIfAborted();
697
+ result.check = unavailable.includes(id) ? 'fail' : 'pass';
698
+ if (result.check === 'pass')
699
+ await session.release(id);
700
+ else
701
+ await session.hold(id);
702
+ session.signal.throwIfAborted();
703
+ return result.check === 'pass';
704
+ }
705
+ catch {
706
+ await session.hold(id).catch(() => { });
707
+ if (!unavailable.includes(id))
708
+ unavailable.push(id);
709
+ result.check = 'fail';
710
+ result.daemon ??= 'fail';
711
+ notify(`${id}: FAIL — verification incomplete; other ready sources continue`);
712
+ return false;
713
+ }
714
+ });
715
+ if (passed) {
716
+ readyCount++;
717
+ await firstAnswer();
718
+ }
719
+ })();
720
+ settled.set(id, task);
721
+ return task;
722
+ };
723
+ log.step(`Installing and connecting ${ids.length} vetted free services (up to ${SETUP_CONCURRENCY} at once)`);
724
+ log.info('Trusty Squire reuses existing accounts and grants. Only free access is requested. Sources become usable independently; verification prompts are queued.');
725
+ const outcome = await actions.setupFallbacks({ directory: configDir(), run: command, adapters: ids, notify, onSettled, connect,
726
+ signal: session.signal, ...(consent.approved.length ? { dataSharingApproved: consent.approved } : {}), ...(squire ? { squire } : {}) });
727
+ // Compatibility for injected setup implementations that return only a final
728
+ // result. Production emits settlement events as soon as each source finishes.
729
+ await parallelMap(ids, id => onSettled(id, !outcome.unavailable.includes(id)));
730
+ await Promise.all(settled.values());
731
+ session.signal.throwIfAborted();
732
+ await stopDashboard();
733
+ await drainUi();
734
+ await withTerminal(async () => note([`${'service'.padEnd(10)} sign-in daemon test`, ...requested.map(id => {
498
735
  const r = results.get(id);
499
736
  return `${id.padEnd(10)} ${mark(r.signup)} ${mark(r.daemon)} ${mark(r.check)}`;
500
- })].join('\n'), 'Free services');
501
- if (actions.connectHarnesses)
737
+ })].join('\n'), 'Free services'));
738
+ if (!readyCount)
739
+ throw new Error('No adapters passed verification. Run usegrunt setup to resume.');
740
+ // OpenCode may have been installed by its provider job. Only rediscover
741
+ // when no tool existed initially, never after the user selected none.
742
+ if (harnessPlan?.discoverLater && actions.connectHarnesses)
502
743
  await actions.connectHarnesses(port);
503
- else if (actions.configurePi)
504
- await step('Pi provider', () => actions.configurePi(port));
505
- outro(unavailable.length ? `grunt is ready; incomplete fallbacks: ${unavailable.join(', ')}. Rerun setup to finish them.` : 'grunt is ready');
506
- if (unavailable.length)
507
- throw new Error('Some adapters failed verification. Run usegrunt setup to resume.');
744
+ await drainUi();
745
+ await withTerminal(async () => outro(unavailable.length ? `grunt is ready; incomplete fallbacks: ${unavailable.join(', ')}. Rerun setup to finish them.` : 'grunt is ready'));
746
+ watchPort = port;
508
747
  }
509
748
  finally {
510
- await squire?.close();
749
+ await stopDashboard();
750
+ stopVerificationStatus?.();
751
+ await verificationStatus;
752
+ if (session && abortSetup)
753
+ session.signal.removeEventListener('abort', abortSetup);
754
+ try {
755
+ await closeSquire();
756
+ }
757
+ finally {
758
+ await session?.close();
759
+ await stopDashboard();
760
+ await drainUi();
761
+ }
511
762
  }
763
+ // Only the standalone view reads keys, after all signups, browser clients,
764
+ // and the setup lease have been released. Noninteractive setup still exits.
765
+ if (watchPort !== undefined)
766
+ await actions.watchDashboard?.(watchPort);
512
767
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "usegrunt",
3
- "version": "0.6.6",
3
+ "version": "0.6.8",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22"