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.
@@ -2,7 +2,7 @@
2
2
  import { disabledAdapters, knownAdapters } from '../registry.js';
3
3
  import { realpathSync } from 'node:fs';
4
4
  import { pathToFileURL } from 'node:url';
5
- import { basename } from 'node:path';
5
+ import { basename, join } from 'node:path';
6
6
  import { serve } from '@hono/node-server';
7
7
  import { createLocalApp } from './api.js';
8
8
  import { positive } from './freebuff.js';
@@ -31,6 +31,7 @@ import { RegistrySync } from './registry.js';
31
31
  import { configDir, command } from './wizard.js';
32
32
  import { setupFallbacks } from './fallback-setup.js';
33
33
  import { BrowserSquire } from './setup.js';
34
+ import { readSetupSession } from './setup-session.js';
34
35
  export const HOST = '127.0.0.1';
35
36
  export function configure(env = process.env, registry = () => bundledRegistry) {
36
37
  const url = env.MILO_FREELLMAPI_URL ?? 'http://127.0.0.1:3001/v1';
@@ -55,7 +56,7 @@ export function configure(env = process.env, registry = () => bundledRegistry) {
55
56
  // default while retaining explicit environment and custom-model overrides.
56
57
  return adapter?.models ?? (adapter?.model && adapter.model !== 'big-pickle' ? [adapter.model] : DEFAULT_OPENCODE_MODELS);
57
58
  };
58
- const registered = [dots, new Codex(env.MILO_CODEX_MODEL ? { model: env.MILO_CODEX_MODEL } : {}), new ManagedRouter(new FreeLLMAPI(connection), url, configDir(env)), new Kilo({ directory: configDir(env) }), new Nvidia({ directory: configDir(env) }), new Zro({ directory: configDir(env) }), new TokenHarbor({ directory: configDir(env) }), new Runcrate({ directory: configDir(env) }), new MistralVibe({ directory: configDir(env) }), new LiveKit({ directory: configDir(env) }), new Pollinations({ directory: configDir(env) }), new BeatAPI({ directory: configDir(env) }), new Clixad({ directory: configDir(env) }), new Perch({ directory: configDir(env) }), new OpenCode({ models: opencodeModels, ...(env.MILO_OPENCODE_URL ? { url: env.MILO_OPENCODE_URL } : {}) })];
59
+ const registered = [dots, new Codex(env.MILO_CODEX_MODEL ? { model: env.MILO_CODEX_MODEL } : {}), new ManagedRouter(new FreeLLMAPI(connection), url, configDir(env)), new Kilo({ directory: configDir(env) }), new Nvidia({ directory: configDir(env) }), new Zro({ directory: configDir(env) }), new TokenHarbor({ directory: configDir(env) }), new Runcrate({ directory: configDir(env) }), new MistralVibe({ directory: configDir(env) }), new LiveKit({ directory: configDir(env) }), new Pollinations({ directory: configDir(env) }), new BeatAPI({ directory: configDir(env) }), new Clixad({ directory: configDir(env) }), new Perch({ directory: configDir(env) }), new OpenCode({ models: opencodeModels, configFile: join(configDir(env), 'opencode-free.json'), ...(env.MILO_OPENCODE_URL ? { url: env.MILO_OPENCODE_URL } : {}) })];
59
60
  const ids = (env.MILO_SOURCES?.split(',').map(id => id.trim()) ?? registry().adapters.filter(adapter => knownAdapters.has(adapter.id)).map(adapter => adapter.id)).filter(id => id && !disabledAdapters.has(id));
60
61
  const routing = ids.every(id => knownAdapters.has(id)) ? { registry } : undefined;
61
62
  return new Sources(ids.map(id => {
@@ -71,16 +72,55 @@ export function start(env = process.env) {
71
72
  const sources = configure(env, () => registry);
72
73
  const directory = configDir(env);
73
74
  let squire;
75
+ const backgroundPreparing = new Set();
76
+ const reconcile = () => {
77
+ sources.preparing.clear();
78
+ for (const id of backgroundPreparing)
79
+ sources.preparing.add(id);
80
+ for (const id of sources.pending)
81
+ sources.preparing.add(id);
82
+ };
83
+ // Serialize snapshots so an older filesystem read cannot overwrite a newer
84
+ // provider release while requests and registry checks run concurrently.
85
+ let sessionRead = Promise.resolve();
86
+ const refreshSession = () => {
87
+ const result = sessionRead.then(async () => {
88
+ const session = await readSetupSession(directory);
89
+ sources.pending.clear();
90
+ for (const id of session?.pending ?? [])
91
+ if (sources.sources.some(source => source.id === id))
92
+ sources.pending.add(id);
93
+ sources.verifying.clear();
94
+ for (const id of session?.verifying ?? [])
95
+ if (sources.pending.has(id))
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);
101
+ reconcile();
102
+ return session;
103
+ });
104
+ sessionRead = result.catch(() => { });
105
+ return result;
106
+ };
74
107
  const sync = new RegistrySync({ directory, ...(env.GRUNT_REGISTRY_URL ? { url: env.GRUNT_REGISTRY_URL } : {}),
75
108
  afterEnsure: async () => { await squire?.close(); squire = undefined; },
76
109
  changed: current => { registry = current; }, notify: console.error,
77
110
  ensure: async (adapter, signal) => {
78
111
  if (!sources.sources.some(source => source.id === adapter.id))
79
112
  return;
113
+ const session = await refreshSession();
114
+ if (session?.owned.has(adapter.id)) {
115
+ backgroundPreparing.delete(adapter.id);
116
+ reconcile();
117
+ return;
118
+ }
80
119
  const approved = await readDataSharingConsent(directory, [adapter.id]);
81
120
  if (requiresDataSharing(adapter.id) && !approved.includes(adapter.id))
82
121
  return;
83
- sources.preparing.add(adapter.id);
122
+ backgroundPreparing.add(adapter.id);
123
+ reconcile();
84
124
  const client = squire ??= new BrowserSquire({ background: true, signal, dataSharingApproved: approved });
85
125
  client.approveDataSharing([...new Set([...(await readDataSharingConsent(directory, [...knownAdapters])), ...approved])]);
86
126
  try {
@@ -91,23 +131,28 @@ export function start(env = process.env) {
91
131
  sources.healthy(adapter.id);
92
132
  }
93
133
  finally {
94
- sources.preparing.delete(adapter.id);
134
+ backgroundPreparing.delete(adapter.id);
135
+ reconcile();
95
136
  }
96
137
  }
97
138
  });
98
139
  // Load the private cache before accepting tasks, without waiting for the network.
99
140
  // Mark adapters as preparing until their first background setup finishes.
100
- const ready = sync.load().then(() => { for (const adapter of sync.enabled)
101
- if (sources.sources.some(source => source.id === adapter.id))
102
- sources.preparing.add(adapter.id); });
103
- void ready.then(() => sync.start()).catch(() => console.error('Registry sync could not start; using the bundled list')).finally(() => sources.preparing.clear());
141
+ const ready = sync.load().then(async () => {
142
+ const session = await refreshSession();
143
+ for (const adapter of sync.enabled)
144
+ if (!session?.owned.has(adapter.id) && sources.sources.some(source => source.id === adapter.id))
145
+ backgroundPreparing.add(adapter.id);
146
+ reconcile();
147
+ });
148
+ void ready.then(() => sync.start()).catch(() => console.error('Registry sync could not start; using the bundled list')).finally(() => { backgroundPreparing.clear(); reconcile(); });
104
149
  // Warm the saved login without delaying the server; failed loads retry lazily.
105
- void sources.sources.find(source => ['freellmapi', 'kilo'].includes(source.id))?.available();
150
+ void ready.then(() => sources.sources.find(source => !sources.pending.has(source.id) && ['freellmapi', 'kilo'].includes(source.id))?.available()).catch(() => { });
106
151
  const port = positive(env.MILO_PORT, 8788);
107
152
  if (port > 65535)
108
153
  throw new Error('MILO_PORT must be at most 65535');
109
154
  const app = createLocalApp(sources, { port, dotsEnv: env, log: cwd => console.error(`grunt working directory: ${cwd}`) });
110
- const server = serve({ fetch: async (request) => { await ready; return app.fetch(request); }, hostname: HOST, port }, () => console.error(`grunt model API: http://${HOST}:${port}/v1`));
155
+ const server = serve({ fetch: async (request) => { await ready; await refreshSession(); return app.fetch(request); }, hostname: HOST, port }, () => console.error(`grunt model API: http://${HOST}:${port}/v1`));
111
156
  let closing = false;
112
157
  const close = async () => { if (closing)
113
158
  return; closing = true; await sync.close(); await sources.close(); server.close(); };
@@ -116,7 +161,20 @@ export function start(env = process.env) {
116
161
  return { server, close };
117
162
  }
118
163
  if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
119
- 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') {
120
178
  const { dotsLink } = await import('./dots-link.js');
121
179
  try {
122
180
  await dotsLink(process.argv[4]);
@@ -1,4 +1,4 @@
1
- import { guardRouterSharing } from './setup.js';
1
+ import { guardRouterSharing, RouterSetupPending } from './setup.js';
2
2
  import { SourceError } from './source.js';
3
3
  // The legacy backend can contain Grunt-created sharing providers alongside the
4
4
  // user's custom rows. Enforce current consent without disabling custom sources.
@@ -22,7 +22,9 @@ export class ManagedRouter {
22
22
  try {
23
23
  await guardRouterSharing(this.url, this.directory);
24
24
  }
25
- catch {
25
+ catch (error) {
26
+ if (error instanceof RouterSetupPending)
27
+ throw new SourceError('not_installed', 'A managed provider is still being verified; other ready sources remain available');
26
28
  throw new SourceError('refused', 'Cannot enforce saved router data-sharing choices; rerun usegrunt setup');
27
29
  }
28
30
  signal.throwIfAborted();
@@ -1,7 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { tmpdir } from 'node:os';
4
- import { realpath } from 'node:fs/promises';
4
+ import { lstat, realpath } from 'node:fs/promises';
5
5
  import { userTurns } from './harness.js';
6
6
  import { executable } from './multiplexer.js';
7
7
  import { loopback } from './freellmapi.js';
@@ -53,31 +53,51 @@ export class OpenCode {
53
53
  return this.options.url.replace(/\/$/, '');
54
54
  if (this.starting)
55
55
  return this.starting;
56
- const binary = await executable('opencode');
57
- this.starting = new Promise((resolve, reject) => {
56
+ const starting = (async () => {
57
+ const binary = await executable('opencode');
58
58
  // Keep the normal OS home and the user's existing OpenCode login.
59
59
  const config = JSON.parse(process.env.OPENCODE_CONFIG_CONTENT || '{}');
60
60
  const permission = typeof config.permission === 'string' ? { '*': config.permission } : config.permission;
61
61
  const env = { ...process.env, OPENCODE_CONFIG_CONTENT: JSON.stringify({
62
62
  ...config, permission: { ...permission, external_directory: 'deny' }
63
63
  }) };
64
- const child = spawn(binary, ['serve', '--hostname', '127.0.0.1', '--port', '0'], { stdio: ['ignore', 'pipe', 'ignore'], env });
65
- this.child = child;
66
- const timer = setTimeout(() => { child.kill(); reject(new SourceError('timeout', 'OpenCode server startup timed out')); }, 30000);
67
- let output = '';
68
- child.stdout.on('data', (chunk) => {
69
- output = (output + chunk.toString()).slice(-8192);
70
- const address = output.match(/http:\/\/127\.0\.0\.1:\d+/)?.[0];
71
- if (address) {
72
- clearTimeout(timer);
73
- resolve(address);
64
+ if (this.options.configFile) {
65
+ try {
66
+ const stat = await lstat(this.options.configFile);
67
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600)
68
+ throw new Error('Invalid private config');
69
+ // Signup may create this private grant after the daemon was started.
70
+ // Let the CLI read it; provider values never enter this process.
71
+ env.OPENCODE_CONFIG = this.options.configFile;
72
+ }
73
+ catch (error) {
74
+ if (error.code !== 'ENOENT')
75
+ throw new SourceError('logged_out', 'OpenCode private configuration is unavailable; rerun usegrunt setup');
74
76
  }
77
+ }
78
+ this.shutdown.signal.throwIfAborted();
79
+ return new Promise((resolve, reject) => {
80
+ const child = spawn(binary, ['serve', '--hostname', '127.0.0.1', '--port', '0'], { stdio: ['ignore', 'pipe', 'ignore'], env });
81
+ this.child = child;
82
+ const timer = setTimeout(() => { child.kill(); reject(new SourceError('timeout', 'OpenCode server startup timed out')); }, 30000);
83
+ let output = '';
84
+ child.stdout.on('data', (chunk) => {
85
+ output = (output + chunk.toString()).slice(-8192);
86
+ const address = output.match(/http:\/\/127\.0\.0\.1:\d+/)?.[0];
87
+ if (address) {
88
+ clearTimeout(timer);
89
+ resolve(address);
90
+ }
91
+ });
92
+ const failed = () => { clearTimeout(timer); this.starting = undefined; this.sessions.clear(); this.sessionModels.clear(); this.sessionParents.clear(); this.prepared.clear(); reject(new SourceError('upstream', 'OpenCode server stopped; run opencode serve to check installation')); };
93
+ child.once('error', failed);
94
+ child.once('exit', failed);
75
95
  });
76
- const failed = () => { clearTimeout(timer); this.starting = undefined; this.sessions.clear(); this.sessionModels.clear(); this.sessionParents.clear(); this.prepared.clear(); reject(new SourceError('upstream', 'OpenCode server stopped; run opencode serve to check installation')); };
77
- child.once('error', failed);
78
- child.once('exit', failed);
79
- });
80
- return this.starting;
96
+ })();
97
+ this.starting = starting;
98
+ void starting.catch(() => { if (this.starting === starting)
99
+ this.starting = undefined; });
100
+ return starting;
81
101
  }
82
102
  async complete(request, caller) {
83
103
  const signal = AbortSignal.any([caller, this.shutdown.signal, ...(this.options.timeout ? [AbortSignal.timeout(this.options.timeout)] : [])]);
@@ -11,15 +11,26 @@ 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); }
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
+ }
22
30
  listed(id) { return knownAdapters.has(id) && this.options.registry().adapters.some(a => a.id === id); }
31
+ supportsInput(id, imageInput = false) {
32
+ return knownAdapters.has(id) && this.options.registry().adapters.some(adapter => adapter.id === id && adapter.modalities.includes('text') && (!imageInput || adapter.modalities.includes('image')));
33
+ }
23
34
  async git(cwd, args) {
24
35
  return (await exec('git', ['-C', cwd, ...args], { timeout: 10000, maxBuffer: 1024 * 1024 })).stdout.trim();
25
36
  }
@@ -76,9 +87,9 @@ export class StickyRouter {
76
87
  const adapter = adapters.find(a => a.id === source.id);
77
88
  if (!task.source && this.sources.some(s => s.id === request.model) && source.id !== request.model)
78
89
  continue;
79
- if (!adapter || (this.bars.get(source.id) ?? 0) > this.now())
90
+ if (!adapter || this.options.pending?.has(source.id) || (this.bars.get(source.id) ?? 0) > this.now())
80
91
  continue;
81
- 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))
82
93
  eligible.push({ source, weight: adapter.weight });
83
94
  }
84
95
  signal.throwIfAborted();
@@ -94,7 +105,7 @@ export class StickyRouter {
94
105
  }
95
106
  try {
96
107
  const input = task.switched ? await this.handoff({ ...request, cwd }, task) : { ...request, cwd };
97
- 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));
98
109
  task.output = Buffer.from(result.text).subarray(-4096).toString('utf8');
99
110
  task.switched = false;
100
111
  answeredBy.set(result, selected.source.id);
@@ -116,6 +127,7 @@ export class StickyRouter {
116
127
  else
117
128
  until = this.now() + 15 * 60 * 1000;
118
129
  this.bars.set(selected.source.id, until);
130
+ this.barFailures.set(selected.source.id, failure.code);
119
131
  task.switched = true;
120
132
  }
121
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
+ }
@@ -0,0 +1,248 @@
1
+ import { constants } from 'node:fs';
2
+ import { mkdir, lstat, readdir, open, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { join } from 'node:path';
5
+ import { knownAdapters } from '../registry.js';
6
+ const prefix = '.setup-session-';
7
+ const ttl = 90000;
8
+ const heartbeat = 15000;
9
+ const claimName = /^\.setup-session-(\d+)-([a-f0-9-]{36})$/;
10
+ const sourceId = /^[a-z][a-z0-9-]{0,63}$/;
11
+ const unavailable = () => new Error('Cannot coordinate provider setup safely; finish the existing setup or rerun usegrunt setup');
12
+ function alive(pid) { try {
13
+ process.kill(pid, 0);
14
+ return true;
15
+ }
16
+ catch (error) {
17
+ return error.code === 'EPERM';
18
+ } }
19
+ async function privateDirectory(path) {
20
+ const stat = await lstat(path);
21
+ return stat.isDirectory() && !stat.isSymbolicLink() && stat.uid === process.getuid?.() && (stat.mode & 0o777) === 0o700;
22
+ }
23
+ async function claims(directory) {
24
+ if (!await privateDirectory(directory))
25
+ throw unavailable();
26
+ const result = [];
27
+ for (const name of await readdir(directory)) {
28
+ const match = claimName.exec(name);
29
+ if (!match)
30
+ continue;
31
+ const pid = Number(match[1]), path = join(directory, name);
32
+ if (!Number.isSafeInteger(pid) || pid < 1 || !alive(pid))
33
+ continue;
34
+ try {
35
+ if (await privateDirectory(path))
36
+ result.push({ path, id: match[2], pid });
37
+ }
38
+ catch { /* A completed setup may remove its own directory concurrently. */ }
39
+ }
40
+ return result;
41
+ }
42
+ async function readState(claim, allowExpired = false) {
43
+ let file;
44
+ try {
45
+ file = await open(join(claim.path, 'state.json'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
46
+ const stat = await file.stat();
47
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || stat.size > 32768)
48
+ return;
49
+ const state = JSON.parse(await file.readFile('utf8'));
50
+ if (state.version !== 1 || state.id !== claim.id || state.pid !== claim.pid || typeof state.expires !== 'number'
51
+ || !Number.isFinite(state.expires) || (!allowExpired && state.expires <= Date.now()) || state.expires > Date.now() + ttl + 60000
52
+ || !Array.isArray(state.owned) || state.owned.length > 100 || state.owned.some(id => typeof id !== 'string' || !sourceId.test(id))
53
+ || new Set(state.owned).size !== state.owned.length || !Array.isArray(state.pending)
54
+ || state.pending.some(id => typeof id !== 'string' || !state.owned.includes(id)) || new Set(state.pending).size !== state.pending.length
55
+ || !Array.isArray(state.verifying) || state.verifying.some(id => typeof id !== 'string' || !state.pending.includes(id))
56
+ || new Set(state.verifying).size !== state.verifying.length)
57
+ return;
58
+ return state;
59
+ }
60
+ catch {
61
+ return;
62
+ }
63
+ finally {
64
+ await file?.close();
65
+ }
66
+ }
67
+ async function blockingClaim(claim) {
68
+ const state = await readState(claim, true);
69
+ if (state)
70
+ return state.expires > Date.now();
71
+ // Protect the atomic mkdir -> initial snapshot handshake. Old partial claims
72
+ // cannot block a new installer indefinitely, including after PID reuse.
73
+ try {
74
+ return Date.now() - (await lstat(claim.path)).mtimeMs < ttl;
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+ /** No credentials are stored here. Dead or expired owners never block routing. */
81
+ export async function readSetupSession(directory) {
82
+ try {
83
+ const active = await claims(directory);
84
+ const states = await Promise.all(active.map(claim => readState(claim, true)));
85
+ // An active initializing/corrupt claim has no trustworthy provider subset.
86
+ // Hold provisioning and dispatch conservatively until its owner repairs or
87
+ // aborts, rather than treating unsafe IO as permission to duplicate signup.
88
+ for (let i = 0; i < active.length; i++)
89
+ if (!states[i] && await blockingClaim(active[i])) {
90
+ const all = new Set([...knownAdapters, 'freellmapi']);
91
+ return { owned: all, pending: all, verifying: new Set() };
92
+ }
93
+ const valid = states.filter((state) => state !== undefined && state.expires > Date.now());
94
+ if (!valid.length)
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)) : []));
100
+ return {
101
+ owned: new Set(valid.flatMap(state => state.owned)), pending: new Set(valid.flatMap(state => state.pending)),
102
+ verifying: new Set(valid.flatMap(state => state.verifying)), ...(approvals.size ? { approvals } : {})
103
+ };
104
+ }
105
+ catch {
106
+ return;
107
+ }
108
+ }
109
+ /** Claim before starting the daemon. Keep this owner alive while later approvals run. */
110
+ export async function beginSetupSession(directory, ids) {
111
+ if (ids.length > 100 || ids.some(id => !sourceId.test(id)) || new Set(ids).size !== ids.length)
112
+ throw unavailable();
113
+ await mkdir(directory, { recursive: true, mode: 0o700 });
114
+ if (!await privateDirectory(directory))
115
+ throw unavailable();
116
+ const id = randomUUID(), pid = process.pid, path = join(directory, `${prefix}${pid}-${id}`), claim = { id, pid, path };
117
+ await mkdir(path, { mode: 0o700 });
118
+ // Every contender creates its unique claim before scanning. At most one can
119
+ // observe no other live claim; rejected contenders remove only their own.
120
+ try {
121
+ for (const peer of await claims(directory))
122
+ if (peer.id !== id && await blockingClaim(peer))
123
+ throw unavailable();
124
+ }
125
+ catch (error) {
126
+ await rm(path, { recursive: true, force: true });
127
+ throw error;
128
+ }
129
+ const pending = new Set(ids), verifying = new Set(), approvals = new Set(), controller = new AbortController();
130
+ let closed = false, initialized = false, failure, tail = Promise.resolve();
131
+ let expires = Date.now() + ttl;
132
+ let timer, expiryTimer;
133
+ const fail = () => {
134
+ failure ??= unavailable();
135
+ controller.abort(failure);
136
+ if (timer)
137
+ clearInterval(timer);
138
+ timer = undefined;
139
+ if (expiryTimer)
140
+ clearTimeout(expiryTimer);
141
+ };
142
+ const armExpiry = () => {
143
+ if (expiryTimer)
144
+ clearTimeout(expiryTimer);
145
+ expiryTimer = setTimeout(fail, Math.max(0, expires - Date.now()));
146
+ expiryTimer.unref();
147
+ };
148
+ armExpiry();
149
+ const assertOwner = async () => {
150
+ if (closed || controller.signal.aborted || expires <= Date.now() || !await privateDirectory(path))
151
+ throw unavailable();
152
+ if (initialized) {
153
+ const state = await readState(claim, true);
154
+ if (!state || state.expires !== expires)
155
+ throw unavailable();
156
+ }
157
+ // A committed newer owner means this one has lost authority. Initializing
158
+ // peers will reject our current valid claim, so they cannot evict us.
159
+ for (const peer of await claims(directory))
160
+ if (peer.id !== id && await readState(peer))
161
+ throw unavailable();
162
+ if (controller.signal.aborted || expires <= Date.now())
163
+ throw unavailable();
164
+ };
165
+ const persist = () => {
166
+ const work = tail.then(async () => {
167
+ if (closed)
168
+ return;
169
+ await assertOwner();
170
+ const temporary = join(path, `state.${randomUUID()}.tmp`), nextExpiry = Date.now() + ttl;
171
+ try {
172
+ const state = { version: 1, id, pid, expires: nextExpiry, owned: [...ids], pending: [...pending], verifying: [...verifying], ...(approvals.size ? { approvals: [...approvals] } : {}) };
173
+ await writeFile(temporary, JSON.stringify(state), { flag: 'wx', mode: 0o600 });
174
+ // Slow IO must not resurrect a lease after its TTL or watchdog abort.
175
+ await assertOwner();
176
+ await rename(temporary, join(path, 'state.json'));
177
+ if (controller.signal.aborted || expires <= Date.now())
178
+ throw unavailable();
179
+ expires = nextExpiry;
180
+ initialized = true;
181
+ armExpiry();
182
+ }
183
+ finally {
184
+ await rm(temporary, { force: true });
185
+ }
186
+ }).catch(() => { fail(); throw failure; });
187
+ tail = work.catch(() => { });
188
+ return work;
189
+ };
190
+ try {
191
+ await persist();
192
+ }
193
+ catch (error) {
194
+ closed = true;
195
+ fail();
196
+ await rm(path, { recursive: true, force: true });
197
+ throw error;
198
+ }
199
+ timer = setInterval(() => { void persist().catch(() => { }); }, heartbeat);
200
+ timer.unref();
201
+ const update = async (source, state) => {
202
+ if (closed || controller.signal.aborted || !ids.includes(source))
203
+ throw unavailable();
204
+ if (state === 'release') {
205
+ pending.delete(source);
206
+ verifying.delete(source);
207
+ approvals.delete(source);
208
+ }
209
+ else {
210
+ pending.add(source);
211
+ if (state === 'verify') {
212
+ verifying.add(source);
213
+ approvals.delete(source);
214
+ }
215
+ else
216
+ verifying.delete(source);
217
+ }
218
+ await persist();
219
+ };
220
+ return {
221
+ signal: controller.signal,
222
+ verify: source => update(source, 'verify'),
223
+ hold: source => update(source, 'hold'),
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
+ },
234
+ async close() {
235
+ if (closed)
236
+ return;
237
+ closed = true;
238
+ if (timer)
239
+ clearInterval(timer);
240
+ timer = undefined;
241
+ if (expiryTimer)
242
+ clearTimeout(expiryTimer);
243
+ controller.abort(new Error('Provider setup session ended'));
244
+ await tail;
245
+ await rm(path, { recursive: true, force: true });
246
+ }
247
+ };
248
+ }
@@ -30,6 +30,7 @@ import { setupPerch } from './perch-setup.js';
30
30
  import { disabledAdapters } from '../registry.js';
31
31
  import { KILO_PARTICLE, verifyKiloAccess } from './kilo.js';
32
32
  import { DATA_SHARING_POLICIES, dataSharingPolicies, readDataSharingConsent } from './data-sharing.js';
33
+ import { readSetupSession } from './setup-session.js';
33
34
  const exec = promisify(execFile);
34
35
  export const FREELLMAPI_IMAGE = 'ghcr.io/tashfeenahmed/freellmapi@sha256:845a4b568a20fffd5112e1b9c0258e7782d9eabbba2430612d2f7c811eee267e';
35
36
  export const PROVIDERS = { groq: 'https://console.groq.com/keys', cerebras: 'https://cloud.cerebras.ai/platform/api-keys', kilo: 'https://app.kilo.ai/profile', nvidia: 'https://build.nvidia.com/settings/api-keys', zro: 'https://zro.moonmath.ai/overview', tokenharbor: 'https://tokenharbor.ai/dashboard', runcrate: 'https://www.runcrate.ai/auth/signup', apinex: 'https://apinex.bond/register', 'mistral-vibe': 'https://console.mistral.ai', livekit: 'https://cloud.livekit.io', pollinations: 'https://enter.pollinations.ai', beatapi: 'https://beatapi.io', clixad: 'https://app.clixad.io', perch: 'https://www.perchai.app' };
@@ -165,6 +166,8 @@ export class BrowserSquire {
165
166
  this.options = options;
166
167
  }
167
168
  approveDataSharing(providers) { this.options.dataSharingApproved = [...new Set(providers)]; }
169
+ pendingVerificationServices() { return this.verification.services(); }
170
+ onVerificationChange(observer) { return this.verification.subscribe(observer); }
168
171
  client = new Client({ name: 'grunt setup', version: '0.1.0' });
169
172
  sessions = new Map();
170
173
  services = new Map();
@@ -837,6 +840,8 @@ const retiredManagedAdapter = (row) => {
837
840
  };
838
841
  // Reconcile only Grunt-owned sharing rows before a legacy backend request. This
839
842
  // never provisions a router, changes custom rows, or enables a disabled row.
843
+ export class RouterSetupPending extends Error {
844
+ }
840
845
  export async function guardRouterSharing(url, directory) {
841
846
  const approved = await readDataSharingConsent(directory, ['kilo']);
842
847
  const admin = await readLocalAdmin(join(directory, 'router-admin.json'));
@@ -850,7 +855,15 @@ export async function guardRouterSharing(url, directory) {
850
855
  if (updates.length)
851
856
  await router.call('/fallback', updates, 'PUT');
852
857
  const patched = chain.map(row => ({ ...row, ...updates.find(update => update.modelDbId === row.modelDbId) }));
853
- await router.migrateKiloModels(approved, patched);
858
+ const pending = (await readSetupSession(directory))?.pending;
859
+ if (patched.some(row => {
860
+ const provider = managedSharingProvider(row);
861
+ return provider && row.enabled !== false && pending?.has(provider);
862
+ }))
863
+ throw new RouterSetupPending('A managed provider is still being verified');
864
+ // An old aggregate backend must not create a new owned route before the
865
+ // corresponding direct source has passed its foreground verification.
866
+ await router.migrateKiloModels(approved.filter(provider => !pending?.has(provider)), patched);
854
867
  }
855
868
  // Read the login already created by setup; never provision or change router state.
856
869
  export async function loadRouterKey(url) {