usegrunt 0.6.7 → 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.
package/README.md CHANGED
@@ -25,7 +25,29 @@ The curated pool has eleven sources: OpenCode, Kilo, Zro, Token Harbor, Runcrate
25
25
 
26
26
  In 0.6.7, setup starts the persistent daemon before provider jobs and checks each provider as it finishes. The first verified reply makes grunt ready; setup then applies your coding-tool choices while the remaining jobs continue. Eligible anonymous Kilo and OpenCode routes can work while account-dependent providers wait for Squire sign-in. Up to six provider jobs, three browser operations and three reply checks can run concurrently; readiness does not wait for the whole pool.
27
27
 
28
- The original `npx usegrunt` terminal stays open as the approval console until the remaining jobs finish. Use a connected coding tool in another terminal while it works. Closing the console pauses unfinished signups; verified daemon routes keep running, and rerunning setup resumes the rest. Partial provider failures are reported without failing an installation that has at least one verified route. Perch remains in the default pool, but its human verification does not have to finish before another route becomes usable. Setup duration depends on downloads, prerequisites and verification; no cold-start time is promised.
28
+ The original `npx usegrunt` terminal shows a live source dashboard after the first verified reply, while remaining signups continue. It yields to browser confirmations and resumes afterward. Use a connected coding tool in another terminal while it works. Closing the console pauses unfinished signups; verified daemon routes keep running, and rerunning setup resumes the rest. Partial provider failures are reported without failing an installation that has at least one verified route. Perch remains in the default pool, but its human verification does not have to finish before another route becomes usable. Setup duration depends on downloads, prerequisites and verification; no cold-start time is promised.
29
+
30
+ Reopen the dashboard in a separate terminal:
31
+
32
+ ```bash
33
+ npx usegrunt status --watch
34
+ # One snapshot, suitable for scripts:
35
+ npx usegrunt status --json
36
+ # An older installation on a custom port:
37
+ npx usegrunt status --watch --port 8792
38
+ ```
39
+
40
+ The dashboard uses green for verified replies, cyan for requests in progress,
41
+ blue for setup, yellow for approvals or limits, and red for failures. Arrow keys
42
+ select a source, Enter shows details, `d` toggles disabled sources, and `q` closes
43
+ the view without stopping the daemon. During unfinished setup the view is
44
+ passive so Squire owns the keyboard; those keys become available after setup.
45
+ Status refreshes use cached observations and never send test prompts. Model
46
+ labels describe registry configuration, not an attestation of the latest reply.
47
+ Unobserved sources and unreported credit balances are shown honestly. Narrow
48
+ terminals hide model/timing columns, `NO_COLOR` removes color, and piped output
49
+ prints a single plain snapshot. New setup remembers the installed port;
50
+ `--port` overrides `MILO_PORT`, the saved port, and the default 8788.
29
51
 
30
52
  [Reference](https://github.com/bananaman614305/milo/blob/main/docs/reference.md) · [Vision](https://github.com/bananaman614305/milo/blob/main/VISION.md) · [Changelog](https://github.com/bananaman614305/milo/blob/main/CHANGELOG.md) · [Project instructions](https://github.com/bananaman614305/milo/blob/main/CLAUDE.md).
31
53
 
package/dist/local/api.js CHANGED
@@ -153,6 +153,7 @@ export function createLocalApp(sources, options = {}) {
153
153
  await next();
154
154
  });
155
155
  app.get('/dots/pair', c => pairDots(c.req.raw, options.dotsEnv ?? process.env));
156
+ app.get('/v1/status', c => { c.header('Cache-Control', 'no-store'); return c.json(sources.status()); });
156
157
  app.get('/v1/models', async (c) => c.json({ object: 'list', data: (await sources.models()).map(id => ({ id, object: 'model', created: 0, owned_by: 'milo' })) }));
157
158
  for (const [path, api] of [['chat/completions', 'chat'], ['messages', 'messages'], ['responses', 'responses']]) {
158
159
  app.post(`/v1/${path}`, async (c) => {
@@ -0,0 +1,474 @@
1
+ import { Chalk } from 'chalk';
2
+ import { stripVTControlCharacters } from 'node:util';
3
+ import { constants } from 'node:fs';
4
+ import { open } from 'node:fs/promises';
5
+ import { homedir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ const errorCodes = new Set(['not_installed', 'logged_out', 'quota', 'timeout', 'upstream', 'refused', 'cancelled']);
8
+ const states = new Set(['unknown', 'available', 'ready', 'answering', 'connecting', 'verifying', 'limited', 'error', 'disabled', 'unavailable', 'approval']);
9
+ const labels = {
10
+ unknown: '? Unknown', available: '~ Available', ready: '✓ Ready', answering: '→ Answering',
11
+ connecting: '~ Connecting', verifying: '~ Verifying', limited: '! Limited', error: '× Error',
12
+ disabled: '- Disabled', unavailable: '- Unavailable', approval: '! Approval'
13
+ };
14
+ const names = { opencode: 'OpenCode', kilo: 'Kilo', zro: 'Zro', tokenharbor: 'TokenHarbor', runcrate: 'Runcrate', 'mistral-vibe': 'Mistral Vibe', livekit: 'LiveKit', pollinations: 'Pollinations', beatapi: 'BeatAPI', clixad: 'Clixad', perch: 'Perch', freebuff: 'Freebuff', apinex: 'APInex' };
15
+ // Runtime status is local, but never let provider metadata control the terminal.
16
+ function safe(value) {
17
+ // Strip OSC/DCS strings completely, including terminal-title and hyperlink controls.
18
+ let ordinary = '';
19
+ for (let i = 0; i < value.length; i++) {
20
+ if (value.charCodeAt(i) === 27 && [']', 'P', '^', '_'].includes(value[i + 1] ?? '')) {
21
+ i += 2;
22
+ while (i < value.length && value.charCodeAt(i) !== 7 && !(value.charCodeAt(i) === 27 && value[i + 1] === '\\'))
23
+ i++;
24
+ if (value.charCodeAt(i) === 27)
25
+ i++;
26
+ }
27
+ else
28
+ ordinary += value[i];
29
+ }
30
+ return [...stripVTControlCharacters(ordinary)].filter(c => {
31
+ const cp = c.codePointAt(0);
32
+ return cp >= 32 && !(cp >= 127 && cp <= 159) && !(cp >= 0x202a && cp <= 0x202e) && !(cp >= 0x2066 && cp <= 0x2069);
33
+ }).join('');
34
+ }
35
+ function cellWidth(c) {
36
+ const cp = c.codePointAt(0);
37
+ if (/\p{Mark}/u.test(c) || cp === 0x200d || cp === 0xfe0f)
38
+ return 0;
39
+ return cp >= 0x1100 && (cp <= 0x115f || cp === 0x2329 || cp === 0x232a || (cp >= 0x2e80 && cp <= 0xa4cf) || (cp >= 0xac00 && cp <= 0xd7a3) || (cp >= 0xf900 && cp <= 0xfaff) || (cp >= 0xfe10 && cp <= 0xfe6f) || (cp >= 0xff00 && cp <= 0xff60) || (cp >= 0xffe0 && cp <= 0xffe6) || (cp >= 0x1f300 && cp <= 0x1faff) || cp >= 0x20000) ? 2 : 1;
40
+ }
41
+ function width(value) { return [...stripVTControlCharacters(value)].reduce((sum, c) => sum + cellWidth(c), 0); }
42
+ function fit(value, limit, pad = false) {
43
+ const input = safe(value);
44
+ let output = '', used = 0;
45
+ const clipped = width(input) > limit;
46
+ for (const c of input) {
47
+ const size = cellWidth(c);
48
+ if (used + size > Math.max(0, limit - (clipped ? 1 : 0)))
49
+ break;
50
+ output += c;
51
+ used += size;
52
+ }
53
+ if (clipped && limit > 0) {
54
+ output += '…';
55
+ used++;
56
+ }
57
+ return output + (pad ? ' '.repeat(Math.max(0, limit - used)) : '');
58
+ }
59
+ function duration(ms) { return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`; }
60
+ function countdown(until, now) {
61
+ const seconds = Math.max(0, Math.ceil((until - now) / 1000));
62
+ return seconds < 60 ? `${seconds}s` : seconds < 3600 ? `${Math.ceil(seconds / 60)}m` : `${Math.ceil(seconds / 3600)}h`;
63
+ }
64
+ export function renderDashboard(snapshot, options = {}) {
65
+ const columns = Math.max(20, Math.min(240, Math.floor(options.width ?? 80)));
66
+ const now = options.now ?? Date.now(), chalk = new Chalk({ level: options.color ? 1 : 0 });
67
+ const offline = options.offline || now - snapshot.updatedAt > 15000 || snapshot.updatedAt > now + 60000;
68
+ const approvals = new Set([...(options.approvals ?? []), ...snapshot.sources.filter(source => source.state === 'approval').map(source => source.id)]);
69
+ const paint = (value, state) => {
70
+ if (offline)
71
+ return chalk.gray(value);
72
+ if (state === 'ready' || state === 'available')
73
+ return state === 'ready' ? chalk.green(value) : chalk.gray(value);
74
+ if (state === 'answering')
75
+ return chalk.cyan(value);
76
+ if (state === 'connecting' || state === 'verifying')
77
+ return chalk.blue(value);
78
+ if (state === 'limited' || state === 'approval')
79
+ return chalk.yellow(value);
80
+ if (state === 'error')
81
+ return chalk.red(value);
82
+ return chalk.gray(value);
83
+ };
84
+ const all = snapshot.sources;
85
+ const visible = all.filter(s => s.state !== 'disabled' || options.showDisabled);
86
+ const selectedIndex = Math.max(0, Math.min(visible.length - 1, options.selected ?? 0));
87
+ const stateOf = (source) => offline ? 'unknown' : approvals.has(source.id) && !source.active ? 'approval' : source.state;
88
+ const counts = new Map();
89
+ for (const source of all) {
90
+ const state = stateOf(source);
91
+ counts.set(state, (counts.get(state) ?? 0) + 1);
92
+ }
93
+ const lines = [];
94
+ const add = (value = '') => lines.push(value);
95
+ add(chalk.bold('grunt / sources') + (columns >= 60 ? chalk.gray(' · live local status') : ''));
96
+ add(chalk.gray('─'.repeat(columns)));
97
+ if (offline) {
98
+ add(chalk.red(fit('Daemon offline or status stale', columns)));
99
+ add(chalk.gray(fit('Ready sources cannot be confirmed.', columns)));
100
+ }
101
+ else {
102
+ const ready = all.filter(source => {
103
+ const state = stateOf(source);
104
+ return state === 'ready' || (state === 'answering' && source.lastSuccessAt !== undefined);
105
+ }).length;
106
+ const pieces = [paint(`${ready} ready`, 'ready')];
107
+ const available = counts.get('available') ?? 0;
108
+ const connecting = (counts.get('connecting') ?? 0) + (counts.get('verifying') ?? 0);
109
+ const approval = Math.max(counts.get('approval') ?? 0, options.approvalCount ?? approvals.size);
110
+ if (available)
111
+ pieces.push(chalk.gray(`${available} available`));
112
+ if (connecting)
113
+ pieces.push(paint(`${connecting} connecting`, 'connecting'));
114
+ if (approval)
115
+ pieces.push(paint(`${approval} approval${approval === 1 ? '' : 's'}`, 'approval'));
116
+ if (counts.get('limited'))
117
+ pieces.push(paint(`${counts.get('limited')} limited`, 'limited'));
118
+ if (counts.get('error'))
119
+ pieces.push(paint(`${counts.get('error')} error${counts.get('error') === 1 ? '' : 's'}`, 'error'));
120
+ // Wrap summary at separators so narrow panes keep every count legible.
121
+ let line = '';
122
+ for (const piece of pieces) {
123
+ if (line && width(line) + 3 + width(piece) > columns) {
124
+ add(line);
125
+ line = piece;
126
+ }
127
+ else
128
+ line += (line ? ' · ' : '') + piece;
129
+ }
130
+ add(line);
131
+ add(chalk.gray(fit(`${snapshot.activeRequests} request${snapshot.activeRequests === 1 ? '' : 's'} active${options.setup ? ' · setup continues' : ''}`, columns)));
132
+ }
133
+ add();
134
+ const wide = columns >= 72, mid = columns >= 48;
135
+ const sourceWidth = Math.min(19, Math.max(10, Math.floor(columns * (wide ? .23 : .48))));
136
+ const stateWidth = wide ? 17 : columns - sourceWidth - 2;
137
+ const modelWidth = wide ? columns - sourceWidth - stateWidth - 12 : 0;
138
+ add(chalk.gray(fit('SOURCE', sourceWidth, true) + ' ' + fit('STATE', stateWidth, true) + (wide ? ' ' + fit('MODEL', modelWidth, true) + ' ' + fit('REPLY', 6) : '')));
139
+ // Keep source selection visible even in short split panes.
140
+ const hasApproval = !offline && (approvals.size > 0 || (options.approvalCount ?? 0) > 0);
141
+ const hasHidden = !options.showDisabled && all.some(source => source.state === 'disabled');
142
+ const reserved = 4 + (hasApproval ? 2 : 0) + (hasHidden ? 1 : 0) + (options.details ? 7 : 0);
143
+ let rowLimit = Math.max(1, (options.height ?? 100) - lines.length - reserved);
144
+ if (rowLimit < visible.length)
145
+ rowLimit = Math.max(1, rowLimit - 1);
146
+ const start = Math.max(0, selectedIndex - rowLimit + 1), rows = visible.slice(start, start + rowLimit);
147
+ if (!rows.length)
148
+ add(chalk.gray(fit('No source observations yet.', columns)));
149
+ rows.forEach((source, offset) => {
150
+ const state = stateOf(source), selected = start + offset === selectedIndex;
151
+ const title = `${selected && options.interactive !== false ? '>' : ' '} ${names[source.id] ?? source.id}`;
152
+ const label = (labels[state] ?? labels.unknown) + (source.active > 1 && !offline ? ` (${source.active})` : '');
153
+ const model = source.model ?? 'Not observed';
154
+ const reply = source.lastReplyMs === undefined ? '—' : duration(source.lastReplyMs);
155
+ add((selected ? chalk.bold : (s) => s)(fit(title, sourceWidth, true)) + ' ' + paint(fit(label, stateWidth, true), state) + (wide ? ' ' + chalk.gray(fit(model, modelWidth, true)) + ' ' + chalk.gray(fit(reply, 6)) : ''));
156
+ });
157
+ if (rows.length < visible.length)
158
+ add(chalk.gray(fit(`${start + 1}–${start + rows.length} of ${visible.length} sources${options.interactive === false ? ' · expand pane for all' : ' · ↑↓ to scroll'}`, columns)));
159
+ const disabled = all.filter(source => source.state === 'disabled').length;
160
+ if (disabled && !options.showDisabled)
161
+ add(chalk.gray(fit(`${disabled} disabled source${disabled === 1 ? '' : 's'} hidden${options.interactive === false ? '' : ' · d to show'}`, columns)));
162
+ if (options.details && visible[selectedIndex]) {
163
+ const selected = visible[selectedIndex];
164
+ add();
165
+ add(chalk.bold(fit(names[selected.id] ?? selected.id, columns)));
166
+ add(fit(`Model: ${selected.model ?? 'Not observed'}`, columns));
167
+ if (selected.detail && !offline)
168
+ add(chalk.gray(fit(selected.detail, columns)));
169
+ if (selected.lastSuccessAt)
170
+ add(chalk.gray(fit(`Last success: ${new Date(selected.lastSuccessAt).toISOString()}`, columns)));
171
+ if (selected.retryAt && !offline)
172
+ add(chalk.yellow(fit(`Retry in ${countdown(selected.retryAt, now)} (reported or routing cooldown)`, columns)));
173
+ add(chalk.gray(fit('Credit balance: not reported', columns)));
174
+ }
175
+ add();
176
+ add(chalk.gray('─'.repeat(columns)));
177
+ if (!offline && (approvals.size || options.approvalCount)) {
178
+ add(chalk.yellow(fit(`${Math.max(approvals.size, options.approvalCount ?? 0)} action${approvals.size === 1 ? '' : 's'} needed${approvals.size ? ` · ${[...approvals].map(id => names[id] ?? id).join(', ')}` : ''}`, columns)));
179
+ add(fit(options.setup ? 'Complete the Trusty Squire prompt when shown.' : 'Run usegrunt setup to resume approvals.', columns));
180
+ add(chalk.gray(fit('Other ready sources keep working.', columns)));
181
+ }
182
+ else if (options.notice)
183
+ add(chalk.yellow(fit(options.notice, columns)));
184
+ else
185
+ add(chalk.gray(fit(offline ? 'Run usegrunt setup if the daemon is stopped.' : 'Available = configured; ready = verified reply.', columns)));
186
+ add(chalk.gray(fit(options.interactive === false ? (options.setup ? 'Keep this terminal open for setup approvals.' : 'Live view: usegrunt status --watch') : mid ? '↑↓ select · enter details · a approvals · d disabled · q close view' : '↑↓ select · enter details · q close', columns)));
187
+ return lines.join('\n');
188
+ }
189
+ function number(value) { return typeof value === 'number' && Number.isFinite(value) && value >= 0; }
190
+ export function parseStatus(value) {
191
+ if (!value || typeof value !== 'object')
192
+ throw new Error('Invalid local status');
193
+ const item = value;
194
+ if (item.version !== 1 || !number(item.updatedAt) || !number(item.activeRequests) || !Array.isArray(item.sources) || item.sources.length > 256)
195
+ throw new Error('Invalid local status');
196
+ const ids = new Set();
197
+ const sources = item.sources.map((raw) => {
198
+ if (!raw || typeof raw !== 'object')
199
+ throw new Error('Invalid local source status');
200
+ const source = raw;
201
+ if (typeof source.id !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(source.id) || ids.has(source.id) || typeof source.state !== 'string' || !states.has(source.state) || !number(source.active))
202
+ throw new Error('Invalid local source status');
203
+ ids.add(source.id);
204
+ const result = { id: source.id, state: source.state, active: source.active };
205
+ if (source.modelKind !== undefined) {
206
+ if (source.modelKind !== 'registry')
207
+ throw new Error('Invalid local source status');
208
+ result.modelKind = 'registry';
209
+ }
210
+ if (source.errorCode !== undefined) {
211
+ if (typeof source.errorCode !== 'string' || !errorCodes.has(source.errorCode))
212
+ throw new Error('Invalid local source status');
213
+ result.errorCode = source.errorCode;
214
+ }
215
+ for (const key of ['model', 'detail']) {
216
+ if (source[key] !== undefined) {
217
+ if (typeof source[key] !== 'string' || source[key].length > 512)
218
+ throw new Error('Invalid local source status');
219
+ result[key] = safe(source[key]);
220
+ }
221
+ }
222
+ for (const key of ['lastReplyMs', 'lastSuccessAt', 'retryAt']) {
223
+ if (source[key] !== undefined) {
224
+ if (!number(source[key]) || (key === 'lastSuccessAt' && source[key] > 8640000000000000))
225
+ throw new Error('Invalid local source status');
226
+ result[key] = source[key];
227
+ }
228
+ }
229
+ return result;
230
+ });
231
+ return { version: 1, updatedAt: item.updatedAt, activeRequests: item.activeRequests, sources };
232
+ }
233
+ export async function fetchStatus(options) {
234
+ if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65535)
235
+ throw new Error('Invalid Grunt port');
236
+ const signal = AbortSignal.any([AbortSignal.timeout(3000), ...(options.signal ? [options.signal] : [])]);
237
+ const response = await (options.fetcher ?? fetch)(`http://127.0.0.1:${options.port}/v1/status`, { signal, redirect: 'error', headers: { Accept: 'application/json' } });
238
+ if (!response.ok || !response.body)
239
+ throw new Error('Local Grunt status unavailable');
240
+ const reader = response.body.getReader(), chunks = [];
241
+ let length = 0;
242
+ try {
243
+ for (;;) {
244
+ const { done, value } = await reader.read();
245
+ if (done)
246
+ break;
247
+ length += value.length;
248
+ if (length > 131072)
249
+ throw new Error('Local status response too large');
250
+ chunks.push(value);
251
+ }
252
+ }
253
+ finally {
254
+ await reader.cancel().catch(() => { });
255
+ reader.releaseLock();
256
+ }
257
+ return parseStatus(JSON.parse(Buffer.concat(chunks).toString('utf8')));
258
+ }
259
+ export function startDashboard(options) {
260
+ const input = options.input ?? process.stdin, output = options.output ?? process.stdout;
261
+ if (!output.isTTY || (options.env ?? process.env).TERM === 'dumb' || options.signal?.aborted)
262
+ return { done: Promise.resolve(), stop: async () => { }, pause: () => { }, resume: () => { } };
263
+ const interactive = options.interactive === true && input.isTTY === true;
264
+ const env = options.env ?? process.env, controller = new AbortController();
265
+ let snapshot = { version: 1, updatedAt: Date.now(), sources: [], activeRequests: 0 };
266
+ let offline = false, selected = 0, details = false, showDisabled = false, notice = '';
267
+ let paused = false, screen = false, closed = false, pendingKey = '';
268
+ let done;
269
+ const stopped = new Promise(resolve => { done = resolve; });
270
+ const previousRaw = input.isRaw ?? false, previousPaused = input.isPaused(), previousFlowing = input.readableFlowing;
271
+ const leave = () => { if (screen) {
272
+ output.write('\u001b[?25h\u001b[?1049l');
273
+ screen = false;
274
+ } };
275
+ const paint = () => {
276
+ if (closed || paused || options.isSuspended?.()) {
277
+ leave();
278
+ return;
279
+ }
280
+ if (!screen) {
281
+ output.write('\u001b[?1049h\u001b[?25l');
282
+ screen = true;
283
+ }
284
+ output.write('\u001b[H\u001b[2J' + renderDashboard(snapshot, { width: output.columns ?? 80, height: output.rows ?? 24, color: env.NO_COLOR === undefined && env.TERM !== 'dumb', selected, details, offline, approvals: options.approvals?.() ?? [], setup: options.setup ?? false, interactive, showDisabled, notice }));
285
+ };
286
+ const close = () => {
287
+ if (closed)
288
+ return;
289
+ closed = true;
290
+ controller.abort();
291
+ process.off('SIGINT', close);
292
+ process.off('SIGTERM', close);
293
+ process.off('SIGINT', interrupt);
294
+ process.off('SIGTERM', terminate);
295
+ process.off('exit', leave);
296
+ options.signal?.removeEventListener('abort', close);
297
+ output.off('resize', paint);
298
+ if (interactive) {
299
+ input.off('data', key);
300
+ input.off('end', close);
301
+ input.off('close', close);
302
+ input.setRawMode?.(previousRaw);
303
+ // A fresh TTY starts with readableFlowing=null but isPaused()=false.
304
+ // Leaving it resumed after removing our listener keeps the CLI alive.
305
+ if (previousPaused || previousFlowing !== true) {
306
+ input.pause();
307
+ input.unref?.();
308
+ }
309
+ }
310
+ leave();
311
+ done();
312
+ };
313
+ const signalClose = (signal, handler) => {
314
+ const ownedElsewhere = process.listeners(signal).some(listener => listener !== handler);
315
+ close();
316
+ // Passive rendering must restore the terminal without replacing setup's
317
+ // existing cancellation behavior or consuming the default signal action.
318
+ if (!ownedElsewhere) {
319
+ let relayed = false;
320
+ const relay = () => { if (!relayed) {
321
+ relayed = true;
322
+ clearTimeout(flushDeadline);
323
+ process.kill(process.pid, signal);
324
+ } };
325
+ // A custom output may ignore write callbacks; it must not consume Ctrl-C.
326
+ const flushDeadline = setTimeout(relay, 100);
327
+ output.write('', relay);
328
+ }
329
+ };
330
+ const interrupt = () => signalClose('SIGINT', interrupt);
331
+ const terminate = () => signalClose('SIGTERM', terminate);
332
+ const key = (chunk) => {
333
+ if (closed || paused || options.isSuspended?.())
334
+ return;
335
+ pendingKey += Buffer.isBuffer(chunk) ? chunk.toString('utf8') : chunk;
336
+ while (pendingKey) {
337
+ if ('\u001b[A'.startsWith(pendingKey) || '\u001b[B'.startsWith(pendingKey)) {
338
+ if (pendingKey.length < 3)
339
+ break;
340
+ }
341
+ if (pendingKey.startsWith('\u001b[A')) {
342
+ selected = Math.max(0, selected - 1);
343
+ pendingKey = pendingKey.slice(3);
344
+ }
345
+ else if (pendingKey.startsWith('\u001b[B')) {
346
+ selected = Math.min(snapshot.sources.filter(s => showDisabled || s.state !== 'disabled').length - 1, selected + 1);
347
+ pendingKey = pendingKey.slice(3);
348
+ }
349
+ else {
350
+ const char = pendingKey[0];
351
+ pendingKey = pendingKey.slice(1);
352
+ if (char === 'q' || char === '\u0003' || char === '\u0004') {
353
+ close();
354
+ return;
355
+ }
356
+ if (char === '\r' || char === '\n')
357
+ details = !details;
358
+ if (char === 'd') {
359
+ showDisabled = !showDisabled;
360
+ selected = 0;
361
+ }
362
+ if (char === 'a')
363
+ notice = 'Run usegrunt setup in its own terminal to resume approvals.';
364
+ }
365
+ }
366
+ paint();
367
+ };
368
+ process.once('exit', leave);
369
+ if (interactive) {
370
+ process.once('SIGINT', close);
371
+ process.once('SIGTERM', close);
372
+ }
373
+ else {
374
+ process.prependOnceListener('SIGINT', interrupt);
375
+ process.prependOnceListener('SIGTERM', terminate);
376
+ }
377
+ options.signal?.addEventListener('abort', close, { once: true });
378
+ output.on('resize', paint);
379
+ if (interactive) {
380
+ if (previousFlowing !== true)
381
+ input.ref?.();
382
+ input.setRawMode?.(true);
383
+ input.on('data', key);
384
+ input.on('end', close);
385
+ input.on('close', close);
386
+ input.resume();
387
+ }
388
+ const poll = (async () => {
389
+ while (!closed) {
390
+ try {
391
+ snapshot = await fetchStatus({ port: options.port, ...(options.fetcher ? { fetcher: options.fetcher } : {}), signal: controller.signal });
392
+ offline = false;
393
+ }
394
+ catch {
395
+ if (closed)
396
+ break;
397
+ offline = true;
398
+ }
399
+ paint();
400
+ if (!closed)
401
+ await new Promise(resolve => {
402
+ const finish = () => { clearTimeout(timer); controller.signal.removeEventListener('abort', finish); resolve(); };
403
+ const timer = setTimeout(finish, Math.max(100, options.interval ?? 1000));
404
+ controller.signal.addEventListener('abort', finish, { once: true });
405
+ if (controller.signal.aborted)
406
+ finish();
407
+ });
408
+ }
409
+ })().finally(close);
410
+ return { done: stopped.then(() => poll), stop: async () => { close(); await poll; }, pause: () => { paused = true; leave(); }, resume: () => { paused = false; paint(); } };
411
+ }
412
+ async function installedPort(env) {
413
+ const directory = env.MILO_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
414
+ let file;
415
+ try {
416
+ file = await open(join(directory, 'installed-port.json'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
417
+ }
418
+ catch (error) {
419
+ if (error.code === 'ENOENT')
420
+ return 8788;
421
+ throw new Error('Cannot read installed Grunt port; use --port explicitly');
422
+ }
423
+ try {
424
+ const stat = await file.stat();
425
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || stat.size > 32)
426
+ throw new Error('Invalid installed Grunt port');
427
+ const raw = await file.readFile('utf8');
428
+ if (raw.length > 32)
429
+ throw new Error('Invalid installed Grunt port');
430
+ const port = JSON.parse(raw);
431
+ if (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535)
432
+ throw new Error('Invalid installed Grunt port');
433
+ return port;
434
+ }
435
+ catch {
436
+ throw new Error('Invalid saved Grunt port; use --port explicitly or rerun setup');
437
+ }
438
+ finally {
439
+ await file.close();
440
+ }
441
+ }
442
+ export async function statusCommand(args, options = {}) {
443
+ const env = options.env ?? process.env, input = options.input ?? process.stdin, output = options.output ?? process.stdout;
444
+ let watch = false, json = false, portText = env.MILO_PORT;
445
+ for (let i = 0; i < args.length; i++) {
446
+ const arg = args[i];
447
+ if (arg === '--watch')
448
+ watch = true;
449
+ else if (arg === '--json')
450
+ json = true;
451
+ else if (arg === '--port' && args[i + 1] !== undefined)
452
+ portText = args[++i];
453
+ else
454
+ throw new Error('Usage: usegrunt status [--watch] [--json] [--port <1-65535>]');
455
+ }
456
+ portText ??= String(await installedPort(env));
457
+ if (!/^\d+$/.test(portText) || Number(portText) < 1 || Number(portText) > 65535)
458
+ throw new Error('Invalid Grunt port; use --port <1-65535>');
459
+ const port = Number(portText);
460
+ if (json && watch)
461
+ throw new Error('Use --json for one snapshot or --watch for the terminal dashboard');
462
+ if (watch && output.isTTY && input.isTTY && env.TERM !== 'dumb') {
463
+ await startDashboard({ ...options, env, input, output, port, interactive: true }).done;
464
+ return;
465
+ }
466
+ let snapshot;
467
+ try {
468
+ snapshot = await fetchStatus({ port, ...(options.fetcher ? { fetcher: options.fetcher } : {}), ...(options.signal ? { signal: options.signal } : {}) });
469
+ }
470
+ catch {
471
+ throw new Error(`Grunt status unavailable on 127.0.0.1:${port}. Run usegrunt setup if the daemon is stopped.`);
472
+ }
473
+ output.write((json ? JSON.stringify(snapshot, null, 2) : renderDashboard(snapshot, { width: output.columns ?? 80, color: output.isTTY === true && env.NO_COLOR === undefined && env.TERM !== 'dumb', interactive: false })) + '\n');
474
+ }
@@ -94,6 +94,10 @@ export function start(env = process.env) {
94
94
  for (const id of session?.verifying ?? [])
95
95
  if (sources.pending.has(id))
96
96
  sources.verifying.add(id);
97
+ sources.approvals.clear();
98
+ for (const id of session?.approvals ?? [])
99
+ if (sources.pending.has(id))
100
+ sources.approvals.add(id);
97
101
  reconcile();
98
102
  return session;
99
103
  });
@@ -157,7 +161,20 @@ export function start(env = process.env) {
157
161
  return { server, close };
158
162
  }
159
163
  if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
160
- if (process.argv[2] === 'dots' && process.argv[3] === 'link') {
164
+ if (process.argv[2] === 'status') {
165
+ const { statusCommand } = await import('./dashboard.js');
166
+ try {
167
+ await statusCommand(process.argv.slice(3));
168
+ }
169
+ catch (error) {
170
+ console.error(error instanceof Error ? error.message : 'Could not read grunt status');
171
+ process.exitCode = 1;
172
+ }
173
+ }
174
+ else if (['--help', '-h'].includes(process.argv[2] ?? '')) {
175
+ console.log('Usage: usegrunt [setup | add <provider> | status [--watch] [--json] [--port <port>]]\n\nRun setup to connect free sources, or status --watch in a separate terminal to view the pool.');
176
+ }
177
+ else if (process.argv[2] === 'dots' && process.argv[3] === 'link') {
161
178
  const { dotsLink } = await import('./dots-link.js');
162
179
  try {
163
180
  await dotsLink(process.argv[4]);
@@ -11,15 +11,22 @@ export class StickyRouter {
11
11
  options;
12
12
  tasks = new Map();
13
13
  bars = new Map();
14
+ barFailures = new Map();
14
15
  constructor(sources, options) {
15
16
  this.sources = sources;
16
17
  this.options = options;
17
18
  }
18
19
  now() { return (this.options.now ?? Date.now)(); }
19
20
  needsHealthCheck(id) { return this.bars.get(id) === Infinity; }
20
- healthy(id) { if (this.bars.get(id) === Infinity)
21
- this.bars.delete(id); }
22
- verified(id) { this.bars.delete(id); }
21
+ healthy(id) { if (this.bars.get(id) === Infinity) {
22
+ this.bars.delete(id);
23
+ this.barFailures.delete(id);
24
+ } }
25
+ verified(id) { this.bars.delete(id); this.barFailures.delete(id); }
26
+ cooldown(id) {
27
+ const until = this.bars.get(id), code = this.barFailures.get(id);
28
+ return until !== undefined ? { until, ...(code ? { code } : {}) } : undefined;
29
+ }
23
30
  listed(id) { return knownAdapters.has(id) && this.options.registry().adapters.some(a => a.id === id); }
24
31
  supportsInput(id, imageInput = false) {
25
32
  return knownAdapters.has(id) && this.options.registry().adapters.some(adapter => adapter.id === id && adapter.modalities.includes('text') && (!imageInput || adapter.modalities.includes('image')));
@@ -82,7 +89,7 @@ export class StickyRouter {
82
89
  continue;
83
90
  if (!adapter || this.options.pending?.has(source.id) || (this.bars.get(source.id) ?? 0) > this.now())
84
91
  continue;
85
- if (source.id === task.source || await source.available().catch(() => false))
92
+ if (source.id === task.source || await (this.options.observation ? this.options.observation.available(source) : source.available()).catch(() => false))
86
93
  eligible.push({ source, weight: adapter.weight });
87
94
  }
88
95
  signal.throwIfAborted();
@@ -98,7 +105,7 @@ export class StickyRouter {
98
105
  }
99
106
  try {
100
107
  const input = task.switched ? await this.handoff({ ...request, cwd }, task) : { ...request, cwd };
101
- const result = await selected.source.complete(input, signal);
108
+ const result = await (this.options.observation ? this.options.observation.complete(selected.source, input, signal) : selected.source.complete(input, signal));
102
109
  task.output = Buffer.from(result.text).subarray(-4096).toString('utf8');
103
110
  task.switched = false;
104
111
  answeredBy.set(result, selected.source.id);
@@ -120,6 +127,7 @@ export class StickyRouter {
120
127
  else
121
128
  until = this.now() + 15 * 60 * 1000;
122
129
  this.bars.set(selected.source.id, until);
130
+ this.barFailures.set(selected.source.id, failure.code);
123
131
  task.switched = true;
124
132
  }
125
133
  }
@@ -0,0 +1,27 @@
1
+ import { startDashboard, statusCommand } from './dashboard.js';
2
+ import { observeTerminal, terminalBusy } from './terminal.js';
3
+ export function setupDashboardEnabled() {
4
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY && process.env.TERM !== 'dumb'
5
+ && process.env.MILO_SETUP_NO_HUMAN !== '1');
6
+ }
7
+ // During onboarding this display is passive: the existing confirmation queue
8
+ // owns stdin. A terminal lease restores the main screen before any prompt.
9
+ export function startSetupDashboard(options) {
10
+ if (!setupDashboardEnabled())
11
+ return;
12
+ const display = startDashboard({ ...options, interactive: false, setup: true, isSuspended: terminalBusy });
13
+ const unsubscribe = observeTerminal(busy => { if (busy)
14
+ display.pause();
15
+ else
16
+ display.resume(); });
17
+ let stopping;
18
+ const stop = () => stopping ??= (async () => { unsubscribe(); await display.stop(); })();
19
+ // Signal handling belongs to the renderer; release our observation too when
20
+ // it ends independently, so an old view cannot resume on a later prompt.
21
+ void display.done.then(unsubscribe, unsubscribe);
22
+ return { stop };
23
+ }
24
+ export async function watchSetupDashboard(port) {
25
+ if (setupDashboardEnabled())
26
+ await statusCommand(['--watch', '--port', String(port)]);
27
+ }
@@ -93,9 +93,13 @@ export async function readSetupSession(directory) {
93
93
  const valid = states.filter((state) => state !== undefined && state.expires > Date.now());
94
94
  if (!valid.length)
95
95
  return;
96
+ // Approval metadata is display-only. Malformed optional fields must never
97
+ // change a valid owner's routing exclusions or expose capability links.
98
+ const approvals = new Set(valid.flatMap(state => Array.isArray(state.approvals)
99
+ ? state.approvals.filter(id => typeof id === 'string' && state.pending.includes(id) && !state.verifying.includes(id)) : []));
96
100
  return {
97
101
  owned: new Set(valid.flatMap(state => state.owned)), pending: new Set(valid.flatMap(state => state.pending)),
98
- verifying: new Set(valid.flatMap(state => state.verifying))
102
+ verifying: new Set(valid.flatMap(state => state.verifying)), ...(approvals.size ? { approvals } : {})
99
103
  };
100
104
  }
101
105
  catch {
@@ -122,7 +126,7 @@ export async function beginSetupSession(directory, ids) {
122
126
  await rm(path, { recursive: true, force: true });
123
127
  throw error;
124
128
  }
125
- const pending = new Set(ids), verifying = new Set(), controller = new AbortController();
129
+ const pending = new Set(ids), verifying = new Set(), approvals = new Set(), controller = new AbortController();
126
130
  let closed = false, initialized = false, failure, tail = Promise.resolve();
127
131
  let expires = Date.now() + ttl;
128
132
  let timer, expiryTimer;
@@ -165,7 +169,7 @@ export async function beginSetupSession(directory, ids) {
165
169
  await assertOwner();
166
170
  const temporary = join(path, `state.${randomUUID()}.tmp`), nextExpiry = Date.now() + ttl;
167
171
  try {
168
- const state = { version: 1, id, pid, expires: nextExpiry, owned: [...ids], pending: [...pending], verifying: [...verifying] };
172
+ const state = { version: 1, id, pid, expires: nextExpiry, owned: [...ids], pending: [...pending], verifying: [...verifying], ...(approvals.size ? { approvals: [...approvals] } : {}) };
169
173
  await writeFile(temporary, JSON.stringify(state), { flag: 'wx', mode: 0o600 });
170
174
  // Slow IO must not resurrect a lease after its TTL or watchdog abort.
171
175
  await assertOwner();
@@ -200,11 +204,14 @@ export async function beginSetupSession(directory, ids) {
200
204
  if (state === 'release') {
201
205
  pending.delete(source);
202
206
  verifying.delete(source);
207
+ approvals.delete(source);
203
208
  }
204
209
  else {
205
210
  pending.add(source);
206
- if (state === 'verify')
211
+ if (state === 'verify') {
207
212
  verifying.add(source);
213
+ approvals.delete(source);
214
+ }
208
215
  else
209
216
  verifying.delete(source);
210
217
  }
@@ -215,6 +222,15 @@ export async function beginSetupSession(directory, ids) {
215
222
  verify: source => update(source, 'verify'),
216
223
  hold: source => update(source, 'hold'),
217
224
  release: source => update(source, 'release'),
225
+ async setApprovals(selected) {
226
+ if (closed || controller.signal.aborted || selected.some(source => !ids.includes(source)))
227
+ throw unavailable();
228
+ approvals.clear();
229
+ for (const source of selected)
230
+ if (pending.has(source) && !verifying.has(source))
231
+ approvals.add(source);
232
+ await persist();
233
+ },
218
234
  async close() {
219
235
  if (closed)
220
236
  return;
@@ -166,6 +166,8 @@ export class BrowserSquire {
166
166
  this.options = options;
167
167
  }
168
168
  approveDataSharing(providers) { this.options.dataSharingApproved = [...new Set(providers)]; }
169
+ pendingVerificationServices() { return this.verification.services(); }
170
+ onVerificationChange(observer) { return this.verification.subscribe(observer); }
169
171
  client = new Client({ name: 'grunt setup', version: '0.1.0' });
170
172
  sessions = new Map();
171
173
  services = new Map();
@@ -0,0 +1,129 @@
1
+ const codes = new Set(['not_installed', 'logged_out', 'quota', 'timeout', 'upstream', 'refused', 'cancelled']);
2
+ const failureCode = (error) => {
3
+ const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
4
+ return typeof code === 'string' && codes.has(code) ? code : 'upstream';
5
+ };
6
+ const detail = {
7
+ unknown: 'No runtime activity observed yet', available: 'Configured; awaiting a verified reply', ready: 'A successful reply was observed',
8
+ answering: 'Request in progress', connecting: 'Setup or a background check is in progress', verifying: 'Setup is verifying this source', approval: 'Needs foreground verification',
9
+ limited: 'Free quota or rate limit reached', error: 'Source failed; another source may answer', disabled: 'Routing is disabled',
10
+ unavailable: 'Not currently available; setup may be needed'
11
+ };
12
+ // This observer records only events the runtime already performs. Reading a
13
+ // snapshot never calls a provider, reads credentials, or stores request content.
14
+ export class SourceStatus {
15
+ now;
16
+ observations = new Map();
17
+ constructor(ids, now = Date.now) {
18
+ this.now = now;
19
+ for (const id of ids)
20
+ this.observations.set(id, { state: 'unknown', active: 0, revision: 0 });
21
+ }
22
+ entry(id) {
23
+ let entry = this.observations.get(id);
24
+ if (!entry) {
25
+ entry = { state: 'unknown', active: 0, revision: 0 };
26
+ this.observations.set(id, entry);
27
+ }
28
+ return entry;
29
+ }
30
+ healthy(id) {
31
+ const entry = this.entry(id);
32
+ entry.revision++;
33
+ delete entry.failure;
34
+ delete entry.retryAt;
35
+ if (entry.state !== 'ready')
36
+ entry.state = 'available';
37
+ }
38
+ async available(source, healthCheck = false) {
39
+ const entry = this.entry(source.id), revision = entry.revision;
40
+ try {
41
+ const result = await (healthCheck ? source.healthCheck() : source.available());
42
+ // A reply or explicit recovery observed after this probe started is
43
+ // newer evidence. The caller still receives the actual probe result.
44
+ if (entry.revision === revision) {
45
+ if (!result)
46
+ entry.state = 'unavailable';
47
+ else if (healthCheck)
48
+ this.healthy(source.id);
49
+ else if (entry.state === 'unknown' || entry.state === 'unavailable')
50
+ entry.state = 'available';
51
+ }
52
+ return result;
53
+ }
54
+ catch (error) {
55
+ if (entry.revision === revision)
56
+ entry.state = 'unavailable';
57
+ throw error;
58
+ }
59
+ }
60
+ async complete(source, request, signal) {
61
+ const entry = this.entry(source.id), started = this.now();
62
+ entry.active++;
63
+ try {
64
+ const result = await source.complete(request, signal);
65
+ // A provider may finish after the caller cancelled. That is not evidence
66
+ // of an admitted successful response, and must not resurrect readiness.
67
+ if (!signal.aborted) {
68
+ entry.revision++;
69
+ entry.state = 'ready';
70
+ entry.lastSuccessAt = this.now();
71
+ entry.lastReplyMs = Math.max(0, this.now() - started);
72
+ delete entry.failure;
73
+ delete entry.retryAt;
74
+ }
75
+ return result;
76
+ }
77
+ catch (error) {
78
+ const code = failureCode(error);
79
+ if (!signal.aborted && code !== 'cancelled') {
80
+ entry.revision++;
81
+ entry.failure = code;
82
+ entry.state = code === 'quota' ? 'limited' : code === 'logged_out' || code === 'not_installed' ? 'unavailable' : 'error';
83
+ const retry = error && typeof error === 'object' && 'retryAfter' in error ? error.retryAfter : undefined;
84
+ const seconds = code === 'quota' ? (typeof retry === 'number' && Number.isFinite(retry) && retry >= 0 ? retry : undefined) : undefined;
85
+ const until = seconds === undefined ? undefined : this.now() + seconds * 1000;
86
+ if (until !== undefined && Number.isFinite(until))
87
+ entry.retryAt = until;
88
+ else
89
+ delete entry.retryAt;
90
+ }
91
+ throw error;
92
+ }
93
+ finally {
94
+ entry.active--;
95
+ }
96
+ }
97
+ snapshot(options) {
98
+ const now = this.now();
99
+ const sources = [...new Set([...options.ids, ...options.disabled])].map((id) => {
100
+ const entry = this.entry(id), model = options.model?.(id);
101
+ const row = { id, state: entry.state, active: entry.active,
102
+ ...(model ? { model, modelKind: 'registry' } : {}), ...(entry.failure ? { errorCode: entry.failure } : {}), ...(entry.lastReplyMs !== undefined ? { lastReplyMs: entry.lastReplyMs } : {}),
103
+ ...(entry.lastSuccessAt !== undefined ? { lastSuccessAt: entry.lastSuccessAt } : {}) };
104
+ const cooldown = options.cooldown?.(id);
105
+ if (options.disabled.has(id) || options.listed && !options.listed(id))
106
+ row.state = 'disabled';
107
+ else if (options.pending.has(id))
108
+ row.state = options.verifying.has(id) ? 'verifying' : options.approvals.has(id) ? 'approval' : 'connecting';
109
+ else if (entry.active)
110
+ row.state = 'answering';
111
+ else if (cooldown !== undefined && cooldown.until > now) {
112
+ row.state = cooldown.code === 'quota' ? 'limited' : cooldown.until === Infinity ? 'unavailable' : 'error';
113
+ if (Number.isFinite(cooldown.until))
114
+ row.retryAt = cooldown.until;
115
+ }
116
+ else if (options.preparing.has(id) && entry.state !== 'ready')
117
+ row.state = 'connecting';
118
+ else if (cooldown !== undefined && (entry.state === 'limited' || entry.state === 'error'))
119
+ row.state = 'available';
120
+ else if (entry.retryAt !== undefined && entry.retryAt > now)
121
+ row.retryAt = entry.retryAt;
122
+ else if (entry.retryAt !== undefined && entry.state === 'limited')
123
+ row.state = 'available';
124
+ row.detail = `${detail[row.state]}${model ? '; model label comes from the registry, not response attestation' : ''}`;
125
+ return row;
126
+ });
127
+ return { version: 1, updatedAt: now, sources, activeRequests: sources.reduce((total, source) => total + source.active, 0) };
128
+ }
129
+ }
@@ -13,8 +13,10 @@ export class SourceError extends Error {
13
13
  export const answeredBy = new WeakMap();
14
14
  export class Sources {
15
15
  sources;
16
+ routing;
16
17
  disabledModels;
17
18
  router;
19
+ observation;
18
20
  // Adapters whose background setup has not finished yet.
19
21
  preparing = new Set();
20
22
  // Foreground signups must not probe or dispatch incomplete sources. Routine
@@ -22,20 +24,36 @@ export class Sources {
22
24
  pending = new Set();
23
25
  // An exact-ID setup probe may run without admitting that source to the pool.
24
26
  verifying = new Set();
27
+ // Foreground approval metadata contains adapter IDs only, never handoff URLs.
28
+ approvals = new Set();
25
29
  constructor(sources, routing, disabledModels = new Set()) {
26
30
  this.sources = sources;
31
+ this.routing = routing;
27
32
  this.disabledModels = disabledModels;
28
33
  if ((!sources.length && !disabledModels.size) || new Set(sources.map(s => s.id)).size !== sources.length)
29
34
  throw new Error('Configure distinct grunt sources');
35
+ this.observation = new SourceStatus(sources.map(source => source.id), routing?.now);
30
36
  if (routing)
31
- this.router = new StickyRouter(sources, { ...routing, pending: this.pending });
37
+ this.router = new StickyRouter(sources, { ...routing, pending: this.pending, observation: this.observation });
38
+ }
39
+ healthy(id) { this.router?.healthy(id); this.observation.healthy(id); }
40
+ status() {
41
+ return this.observation.snapshot({ ids: this.sources.map(source => source.id), disabled: this.disabledModels,
42
+ pending: this.pending, verifying: this.verifying, approvals: this.approvals, preparing: this.preparing,
43
+ ...(this.router ? { listed: (id) => this.router.listed(id), cooldown: (id) => this.router.cooldown(id) } : {}),
44
+ model: id => {
45
+ const adapter = this.routing?.registry().adapters.find(adapter => adapter.id === id);
46
+ // A rotation is a configured set, not an assertion about which model
47
+ // generated the latest answer. Never inspect private adapter configs.
48
+ const model = adapter?.models && adapter.models.length > 1 ? 'Free model rotation' : adapter?.models?.[0] ?? adapter?.model;
49
+ return model && /^[a-zA-Z0-9][a-zA-Z0-9._:/+ -]{0,159}$/.test(model) ? model : undefined;
50
+ } });
32
51
  }
33
- healthy(id) { this.router?.healthy(id); }
34
52
  async models() {
35
53
  const available = await Promise.all(this.sources.map(async (s) => {
36
- if (this.pending.has(s.id) || this.router && !this.router.listed(s.id) || !await s.available())
54
+ if (this.pending.has(s.id) || this.router && !this.router.listed(s.id) || !await this.observation.available(s))
37
55
  return null;
38
- if (this.router?.needsHealthCheck(s.id) && await s.healthCheck?.().catch(() => false))
56
+ if (this.router?.needsHealthCheck(s.id) && s.healthCheck && await this.observation.available(s, true).catch(() => false))
39
57
  this.healthy(s.id);
40
58
  return s.id;
41
59
  }));
@@ -57,7 +75,7 @@ export class Sources {
57
75
  throw new SourceError('refused', `${request.model} does not support this input modality`);
58
76
  // A setup probe is one exact-source call, never sticky failover or a
59
77
  // retry of a provider refusal. The source retains every normal guard.
60
- const completion = await source.complete(request, signal);
78
+ const completion = await this.observation.complete(source, request, signal);
61
79
  signal.throwIfAborted();
62
80
  this.router?.verified(source.id);
63
81
  answeredBy.set(completion, source.id);
@@ -76,7 +94,7 @@ export class Sources {
76
94
  continue;
77
95
  let completion;
78
96
  try {
79
- completion = await source.complete(request, signal);
97
+ completion = await this.observation.complete(source, request, signal);
80
98
  }
81
99
  catch (error) {
82
100
  if (signal.aborted || (error instanceof SourceError && error.code === 'cancelled')) {
@@ -139,3 +157,4 @@ export class Gateway {
139
157
  }
140
158
  }
141
159
  import { StickyRouter } from './routing.js';
160
+ import { SourceStatus } from './source-status.js';
@@ -1,8 +1,38 @@
1
1
  // Interactive child processes (for example sudo) and browser confirmations
2
2
  // must never read stdin at the same time. Noninteractive jobs stay concurrent.
3
3
  let tail = Promise.resolve();
4
+ let active = false;
5
+ const observers = new Set();
6
+ export const terminalBusy = () => active;
7
+ // Status displays may observe terminal ownership, but never receive the prompt,
8
+ // browser capability link, or any data entered by the user.
9
+ export function observeTerminal(observer) {
10
+ observers.add(observer);
11
+ try {
12
+ observer(active);
13
+ }
14
+ catch { /* A display cannot block confirmation. */ }
15
+ return () => { observers.delete(observer); };
16
+ }
17
+ function changed(busy) {
18
+ active = busy;
19
+ for (const observer of observers) {
20
+ try {
21
+ observer(busy);
22
+ }
23
+ catch { /* Observability is independent of setup. */ }
24
+ }
25
+ }
4
26
  export function withTerminal(task) {
5
- const result = tail.then(task);
27
+ const result = tail.then(async () => {
28
+ changed(true);
29
+ try {
30
+ return await task();
31
+ }
32
+ finally {
33
+ changed(false);
34
+ }
35
+ });
6
36
  tail = result.catch(() => { });
7
37
  return result;
8
38
  }
@@ -4,11 +4,35 @@ export class VerificationQueue {
4
4
  confirm;
5
5
  pending = [];
6
6
  running = false;
7
+ active = [];
8
+ observers = new Set();
7
9
  constructor(confirm) {
8
10
  this.confirm = confirm;
9
11
  }
12
+ services() {
13
+ // This safe projection deliberately excludes URLs and requested goals.
14
+ return [...new Set([...this.active, ...this.pending.map(entry => entry.item)]
15
+ .map(item => item.service).filter(service => /^[a-z0-9][a-z0-9-]{0,63}$/.test(service)))];
16
+ }
17
+ subscribe(observer) {
18
+ this.observers.add(observer);
19
+ try {
20
+ observer(this.services());
21
+ }
22
+ catch { /* Status cannot stop approval. */ }
23
+ return () => { this.observers.delete(observer); };
24
+ }
25
+ changed() {
26
+ for (const observer of this.observers) {
27
+ try {
28
+ observer(this.services());
29
+ }
30
+ catch { /* Isolate display failures. */ }
31
+ }
32
+ }
10
33
  wait(item) {
11
34
  const result = new Promise((resolve, reject) => this.pending.push({ item, resolve, reject }));
35
+ this.changed();
12
36
  if (!this.running) {
13
37
  this.running = true;
14
38
  setImmediate(() => { void this.drain(); });
@@ -18,13 +42,19 @@ export class VerificationQueue {
18
42
  async drain() {
19
43
  while (this.pending.length) {
20
44
  const batch = this.pending.splice(0);
45
+ this.active = batch.map(entry => entry.item);
46
+ this.changed();
21
47
  try {
22
- await this.confirm(batch.map(entry => entry.item));
48
+ await this.confirm(this.active);
23
49
  batch.forEach(entry => entry.resolve());
24
50
  }
25
51
  catch (error) {
26
52
  [...batch, ...this.pending.splice(0)].forEach(entry => entry.reject(error));
27
53
  }
54
+ finally {
55
+ this.active = [];
56
+ this.changed();
57
+ }
28
58
  }
29
59
  this.running = false;
30
60
  }
@@ -1,7 +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
4
  import { constants } from 'node:fs';
4
- import { mkdir, readFile, writeFile, cp, mkdtemp, rm, access, lstat, open } from 'node:fs/promises';
5
+ import { mkdir, readFile, writeFile, cp, mkdtemp, rm, access, lstat, open, rename } from 'node:fs/promises';
5
6
  import { homedir, tmpdir } from 'node:os';
6
7
  import { dirname, join } from 'node:path';
7
8
  import { fileURLToPath, pathToFileURL } from 'node:url';
@@ -10,7 +11,7 @@ import { intro, outro, spinner, log, note, multiselect, isCancel } from '@clack/
10
11
  import chalk from 'chalk';
11
12
  import { setupFallbacks } from './fallback-setup.js';
12
13
  import { parallelMap, SETUP_CONCURRENCY } from './parallel.js';
13
- import { withTerminal } from './terminal.js';
14
+ import { withTerminal, terminalBusy } from './terminal.js';
14
15
  import { DOCTOR_TIMEOUT_MS } from './freebuff.js';
15
16
  import { BrowserSquire, PROVIDERS, setup, squireEnvironment } from './setup.js';
16
17
  import { RegistrySync } from './registry.js';
@@ -19,6 +20,7 @@ import { banner } from './banner.js';
19
20
  import { approveDataSharing, requiresDataSharing } from './data-sharing.js';
20
21
  import { configurePi, connectHarness, detectHarnesses } from './harnesses.js';
21
22
  import { beginSetupSession } from './setup-session.js';
23
+ import { startSetupDashboard, watchSetupDashboard } from './setup-dashboard.js';
22
24
  export const configDir = (env = process.env) => env.MILO_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
23
25
  export async function command(binary, args, interactive = false, signal, env) {
24
26
  signal?.throwIfAborted();
@@ -233,6 +235,14 @@ export async function installService(adapters, options = {}) {
233
235
  }
234
236
  await stage(() => installBackgroundService('milo', entry, env, options));
235
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
+ }
236
246
  }
237
247
  export async function installBackgroundService(name, entry, env, options = {}) {
238
248
  const stage = async (operation) => {
@@ -423,14 +433,26 @@ const report = (shown = new Set()) => (line) => {
423
433
  else
424
434
  log.info(line);
425
435
  };
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
+ }
426
448
  export async function prepareHarnesses(port, options = {}) {
427
- log.step('Connect grunt to your coding tools');
449
+ queueUi(() => log.step('Connect grunt to your coding tools'));
428
450
  const found = await detectHarnesses(options.harnesses);
429
451
  if (!found.length) {
430
- log.info('No supported coding tool is currently installed. Grunt will become usable through its local API.');
452
+ queueUi(() => log.info('No supported coding tool is currently installed. Grunt will become usable through its local API.'));
431
453
  return Object.assign(async () => [], { discoverLater: true });
432
454
  }
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.`);
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.`));
434
456
  const interactive = process.stdin.isTTY && process.stdout.isTTY && process.env.MILO_SETUP_NO_HUMAN !== '1';
435
457
  const choose = options.choose ?? (async (list) => {
436
458
  if (!interactive)
@@ -445,28 +467,29 @@ export async function prepareHarnesses(port, options = {}) {
445
467
  return async () => {
446
468
  const connected = [];
447
469
  for (const harness of selected) {
448
- const progress = spinner();
449
- progress.start(`${harness.name}: adding grunt and sending a test request through it`);
470
+ queueUi(() => log.step(`${harness.name}: adding grunt and sending a test request through it`));
450
471
  try {
451
472
  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}`);
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
+ });
455
478
  connected.push(harness);
456
479
  }
457
480
  catch (error) {
458
- progress.error(`${harness.name}: FAIL — ${error instanceof Error ? error.message : String(error)}`);
481
+ queueUi(() => log.error(`${harness.name}: FAIL — ${error instanceof Error ? error.message : String(error)}`));
459
482
  }
460
483
  }
461
484
  if (connected.length)
462
- note(connected.map(h => `${chalk.bold(h.name)}\n ${h.launch(port)}`).join('\n'), 'Start coding with grunt');
485
+ queueUi(() => note(connected.map(h => `${chalk.bold(h.name)}\n ${h.launch(port)}`).join('\n'), 'Start coding with grunt'));
463
486
  return connected;
464
487
  };
465
488
  }
466
489
  export async function connectHarnesses(port, options = {}) {
467
490
  return (await prepareHarnesses(port, options))();
468
491
  }
469
- const wizardActions = { installedSources, createSquire: () => new BrowserSquire(), banner, preflight, connectSquire, setup, setupFallbacks, installService, configurePi, checkService, checkFallbackServices, loadRegistry, checkServiceSources, connectHarnesses, prepareHarnesses, approveDataSharing };
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 };
470
493
  export async function wizard(add, actions = wizardActions) {
471
494
  if (add && disabledAdapters.has(add))
472
495
  throw new Error(`${add} routing is disabled`);
@@ -477,8 +500,37 @@ export async function wizard(add, actions = wizardActions) {
477
500
  let connection;
478
501
  let closing;
479
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
+ };
480
528
  const closeSquire = () => closing ??= (async () => { await squire?.close(); })();
481
- const connect = () => connection ??= step('Connecting Trusty Squire', () => actions.connectSquire({ ...(squire ? { squire } : {}), ...(session ? { signal: session.signal } : {}) }));
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
+ })();
482
534
  try {
483
535
  await actions.banner?.();
484
536
  intro(chalk.hex('#f4b41a').bold('grunt') + chalk.dim(' — npx usegrunt setup'));
@@ -531,7 +583,6 @@ export async function wizard(add, actions = wizardActions) {
531
583
  const ids = requested.filter(id => !consent.skipped.includes(id));
532
584
  const results = new Map(requested.map(id => [id, consent.skipped.includes(id) ? { signup: 'skip', daemon: 'skip', check: 'skip' } : {}]));
533
585
  const unavailable = [];
534
- const notify = report();
535
586
  if (consent.skipped.length)
536
587
  log.info(`Skipped data-sharing services: ${consent.skipped.join(', ')}. Other free services continue.`);
537
588
  if (!ids.length) {
@@ -551,10 +602,21 @@ export async function wizard(add, actions = wizardActions) {
551
602
  const applyHarnesses = harnessPlan ?? (async () => {
552
603
  if (actions.connectHarnesses)
553
604
  await actions.connectHarnesses(port);
554
- else if (actions.configurePi)
555
- await step('Pi provider', () => actions.configurePi(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
+ }
556
610
  });
557
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
+ });
619
+ });
558
620
  abortSetup = () => { void closeSquire().catch(() => { }); };
559
621
  session.signal.addEventListener('abort', abortSetup, { once: true });
560
622
  session.signal.throwIfAborted();
@@ -584,13 +646,22 @@ export async function wizard(add, actions = wizardActions) {
584
646
  let firstReady;
585
647
  let readyCount = 0;
586
648
  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.');
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
+ });
589
653
  try {
590
654
  await applyHarnesses();
591
655
  }
592
656
  catch {
593
- log.warn('grunt is ready; coding-tool configuration needs attention. Rerun setup to finish connecting your tool.');
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.'));
594
665
  }
595
666
  })();
596
667
  const onSettled = (id, available) => {
@@ -658,19 +729,26 @@ export async function wizard(add, actions = wizardActions) {
658
729
  await parallelMap(ids, id => onSettled(id, !outcome.unavailable.includes(id)));
659
730
  await Promise.all(settled.values());
660
731
  session.signal.throwIfAborted();
661
- note([`${'service'.padEnd(10)} sign-in daemon test`, ...requested.map(id => {
732
+ await stopDashboard();
733
+ await drainUi();
734
+ await withTerminal(async () => note([`${'service'.padEnd(10)} sign-in daemon test`, ...requested.map(id => {
662
735
  const r = results.get(id);
663
736
  return `${id.padEnd(10)} ${mark(r.signup)} ${mark(r.daemon)} ${mark(r.check)}`;
664
- })].join('\n'), 'Free services');
737
+ })].join('\n'), 'Free services'));
665
738
  if (!readyCount)
666
739
  throw new Error('No adapters passed verification. Run usegrunt setup to resume.');
667
740
  // OpenCode may have been installed by its provider job. Only rediscover
668
741
  // when no tool existed initially, never after the user selected none.
669
742
  if (harnessPlan?.discoverLater && actions.connectHarnesses)
670
743
  await actions.connectHarnesses(port);
671
- outro(unavailable.length ? `grunt is ready; incomplete fallbacks: ${unavailable.join(', ')}. Rerun setup to finish them.` : 'grunt is ready');
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;
672
747
  }
673
748
  finally {
749
+ await stopDashboard();
750
+ stopVerificationStatus?.();
751
+ await verificationStatus;
674
752
  if (session && abortSetup)
675
753
  session.signal.removeEventListener('abort', abortSetup);
676
754
  try {
@@ -678,6 +756,12 @@ export async function wizard(add, actions = wizardActions) {
678
756
  }
679
757
  finally {
680
758
  await session?.close();
759
+ await stopDashboard();
760
+ await drainUi();
681
761
  }
682
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);
683
767
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "usegrunt",
3
- "version": "0.6.7",
3
+ "version": "0.6.8",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22"