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.
- package/README.md +31 -3
- package/dist/local/api.js +1 -0
- package/dist/local/dashboard.js +474 -0
- package/dist/local/fallback-setup.js +52 -13
- package/dist/local/main.js +69 -11
- package/dist/local/managed-router.js +4 -2
- package/dist/local/opencode.js +38 -18
- package/dist/local/routing.js +17 -5
- package/dist/local/setup-dashboard.js +27 -0
- package/dist/local/setup-session.js +248 -0
- package/dist/local/setup.js +14 -1
- package/dist/local/source-status.js +129 -0
- package/dist/local/source.js +49 -5
- package/dist/local/terminal.js +31 -1
- package/dist/local/verification-queue.js +31 -1
- package/dist/local/wizard.js +353 -98
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,12 +14,40 @@ npx usegrunt
|
|
|
14
14
|
|
|
15
15
|
usegrunt installs grunt on this machine. It pools free AI quota and serves one local agent.
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
Use Node 22 or 24 LTS on Linux with systemd or macOS with launchd. Setup needs npm and tar; browser sign-in also needs a working browser/display path, especially on a headless server. Mistral Vibe needs `uv` or Python 3.12 or later.
|
|
18
|
+
|
|
19
|
+
Daemon restarts reuse saved connections. Background verification preserves them on
|
|
18
20
|
temporary failures and asks for foreground setup when human verification is needed.
|
|
19
21
|
|
|
20
22
|
https://grunt.run. `milo` and `milo-local` remain aliases.
|
|
21
23
|
|
|
22
|
-
The
|
|
24
|
+
The curated pool has eleven sources: OpenCode, Kilo, Zro, Token Harbor, Runcrate, Mistral Vibe Free, LiveKit, Pollinations, BeatAPI, Clixad and Perch. Pi is optional.
|
|
25
|
+
|
|
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
|
+
|
|
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.
|
|
23
51
|
|
|
24
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).
|
|
25
53
|
|
|
@@ -27,7 +55,7 @@ In 0.6.6, one grouped data-sharing approval covers nine active providers. Setup
|
|
|
27
55
|
|
|
28
56
|
LiveKit adds DeepSeek V4.1 Flash through its free Build plan, using one free project and the official CLI's browser login. The documented included inference allowance is $2.50 per calendar month with a hard stop and no card. Keep the account on Build. LiveKit documents [zero data retention and no training for inference](https://docs.livekit.io/agents/models/inference/), so it needs no sharing approval. The route passed short-prompt, tool-call and 210,077-token context checks through Grunt.
|
|
29
57
|
|
|
30
|
-
The four additions are BeatAPI, Pollinations, Clixad and Perch. BeatAPI's ongoing free DeepSeek route permits one successful request per minute and leaves its separate $2 welcome credit untouched. Pollinations' fixed community GLM route needs a numeric zero-budget, Quest-only key and a positive unused Quest balance; the zero-priced route does not spend its one-time first-key reward. Clixad uses its native free GLM route with a zero wallet balance. Perch uses active Starter access with 20,000 Perch Tokens per month, the optional Data Program off, and both memory switches off. Native CLI output limits are local checks and cannot hard-cap upstream generation; keep Clixad's wallet at zero and Perch on Starter. See the reference for model-attestation and billing limits.
|
|
58
|
+
The four additions in 0.6.6 are BeatAPI, Pollinations, Clixad and Perch. BeatAPI's ongoing free DeepSeek route permits one successful request per minute and leaves its separate $2 welcome credit untouched. Pollinations' fixed community GLM route needs a numeric zero-budget, Quest-only key and a positive unused Quest balance; the zero-priced route does not spend its one-time first-key reward. Clixad uses its native free GLM route with a zero wallet balance. Perch uses active Starter access with 20,000 Perch Tokens per month, the optional Data Program off, and both memory switches off. Native CLI output limits are local checks and cannot hard-cap upstream generation; keep Clixad's wallet at zero and Perch on Starter. See the reference for model-attestation and billing limits.
|
|
31
59
|
|
|
32
60
|
Within OpenCode, new conversations rotate across DeepSeek V4.1 Flash Free,
|
|
33
61
|
GLM 5.3 Flash Free and Big Pickle. Follow-ups keep their model, and quota errors
|
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
|
+
}
|
|
@@ -67,9 +67,12 @@ export async function verifyOpenCode(source = new OpenCode(), signal = AbortSign
|
|
|
67
67
|
export async function setupFallbacks(options) {
|
|
68
68
|
const squire = options.squire ?? new BrowserSquire({ dataSharingApproved: options.dataSharingApproved ?? [] });
|
|
69
69
|
const owned = squire instanceof BrowserSquire && !options.squire;
|
|
70
|
-
const requested = options.adapters ?? ['opencode'];
|
|
70
|
+
const requested = [...new Set(options.adapters ?? ['opencode'])];
|
|
71
|
+
// A registry may list account-based providers first. Keep their shared
|
|
72
|
+
// browser login from occupying every worker before anonymous routes start.
|
|
73
|
+
const anonymous = ['kilo', 'opencode'];
|
|
74
|
+
const execution = [...anonymous.filter(id => requested.includes(id)), ...requested.filter(id => !anonymous.includes(id))];
|
|
71
75
|
const unavailable = requested.filter(id => disabledAdapters.has(id));
|
|
72
|
-
const adapters = requested.filter(id => !disabledAdapters.has(id));
|
|
73
76
|
for (const id of unavailable)
|
|
74
77
|
options.notify(`${id}: routing is disabled; other free services continue`);
|
|
75
78
|
const approved = [...new Set([...(options.dataSharingApproved ?? []), ...await readDataSharingConsent(options.directory, DATA_SHARING_POLICIES.map(policy => policy.provider))])];
|
|
@@ -98,6 +101,16 @@ export async function setupFallbacks(options) {
|
|
|
98
101
|
await options.run('npm', ['install', '--global', pkg]);
|
|
99
102
|
}
|
|
100
103
|
};
|
|
104
|
+
const settled = new Set(), callbacks = [], callbackFailures = [];
|
|
105
|
+
const onSettled = (id, available) => {
|
|
106
|
+
if (!options.onSettled || settled.has(id))
|
|
107
|
+
return;
|
|
108
|
+
settled.add(id);
|
|
109
|
+
// Observers may verify the daemon or configure coding tools. Start that
|
|
110
|
+
// work immediately without holding a provider worker or rejecting early.
|
|
111
|
+
callbacks.push(Promise.resolve().then(() => options.onSettled(id, available && !options.signal?.aborted))
|
|
112
|
+
.catch(error => { callbackFailures.push(error); }));
|
|
113
|
+
};
|
|
101
114
|
options.notify('Free routes run their own tools with your filesystem permissions in the working directory. Free model providers may retain prompts.');
|
|
102
115
|
try {
|
|
103
116
|
const tasks = {
|
|
@@ -335,18 +348,44 @@ export async function setupFallbacks(options) {
|
|
|
335
348
|
}
|
|
336
349
|
}
|
|
337
350
|
};
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
351
|
+
let failure;
|
|
352
|
+
try {
|
|
353
|
+
await parallelMap(execution, async (id) => {
|
|
354
|
+
let available = false;
|
|
355
|
+
try {
|
|
356
|
+
if (disabledAdapters.has(id))
|
|
357
|
+
return;
|
|
358
|
+
if (requiresDataSharing(id) && !approved.includes(id)) {
|
|
359
|
+
unavailable.push(id);
|
|
360
|
+
options.notify(`${id}: skipped until the grouped data-sharing approval is granted`);
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
const task = tasks[id];
|
|
364
|
+
if (!task)
|
|
365
|
+
throw new Error('Unsupported vetted adapter');
|
|
366
|
+
await task();
|
|
367
|
+
available = !unavailable.includes(id);
|
|
368
|
+
}
|
|
369
|
+
finally {
|
|
370
|
+
onSettled(id, available);
|
|
371
|
+
}
|
|
372
|
+
}, SETUP_CONCURRENCY, options.signal);
|
|
373
|
+
}
|
|
374
|
+
catch (error) {
|
|
375
|
+
failure = { error };
|
|
376
|
+
}
|
|
377
|
+
finally {
|
|
378
|
+
// Cancellation can leave queued providers unstarted. Settle those as
|
|
379
|
+
// unavailable and keep the shared client alive until observers finish.
|
|
380
|
+
for (const id of requested)
|
|
381
|
+
onSettled(id, false);
|
|
382
|
+
await Promise.all(callbacks);
|
|
383
|
+
}
|
|
384
|
+
if (failure)
|
|
385
|
+
throw failure.error;
|
|
349
386
|
options.signal?.throwIfAborted();
|
|
387
|
+
if (callbackFailures.length)
|
|
388
|
+
throw callbackFailures[0];
|
|
350
389
|
return { unavailable: requested.filter(id => unavailable.includes(id)) };
|
|
351
390
|
}
|
|
352
391
|
finally {
|