usegrunt 0.6.1 → 0.6.3

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
@@ -16,11 +16,18 @@ usegrunt installs grunt on this machine. It pools free AI quota and serves one l
16
16
 
17
17
  https://grunt.run. `milo` and `milo-local` remain aliases.
18
18
 
19
- Setup is Trusty Squire, the free-service list, sign-in, then your coding tools.
19
+ Setup connects Trusty Squire, installs and connects the vetted Freebuff, OpenCode, Kilo and Zro pool, plus opt-in Token Harbor (up to three services at once), tests each service, then connects your coding tools. Browser verification is queued when a provider needs you. Pi is optional.
20
20
 
21
21
  [Reference](https://github.com/bananaman614305/milo/blob/main/docs/reference.md).
22
22
 
23
- Run `usegrunt add kilo` to connect Kilo and restart grunt with its API sources enabled. This reuses saved Squire access or opens Kilo's free signup flow. Requests using model `grunt`, `milo`, or `freellmapi` try free Nemotron 3 Ultra before `kilo-auto/free`; model `kilo` selects Auto explicitly. Freebuff and OpenCode remain available. Repeat setup preserves the API sources. If Nemotron disappears from Kilo's catalog, setup uses Auto.
23
+ New installs offer Zro's daily free DeepSeek V4.1 Flash and, after one grouped data-sharing approval, Freebuff, OpenCode, Kilo Auto and Token Harbor's weekly free route. `usegrunt add groq`, `usegrunt add cerebras`, `usegrunt add kilo`, `usegrunt add zro` and `usegrunt add tokenharbor` remain available. NVIDIA stays optional while its account verification is unvetted. Existing `freellmapi` routes keep their Nemotron-first Kilo chain; the default `kilo` source selects `kilo-auto/free`. Repeat setup preserves previously connected API sources.
24
+
25
+ Within OpenCode, new conversations rotate across DeepSeek V4.1 Flash Free,
26
+ GLM 5.3 Flash Free and Big Pickle. Follow-ups keep their model, and quota errors
27
+ try another free model. These models may share provider limits; the pool does
28
+ not create extra credit balances or purchase credits.
29
+
30
+ Zro setup confirms the Free plan, no purchased usage balance and no payment method before connecting it. Keep that account free: Zro uses the same model ID on its paid plans, so changing the account outside grunt can change billing. Token Harbor uses its explicit `:free` model ID and requires approval for retained prompts, staff review and upstream-provider training. Setup asks once for Freebuff, OpenCode (including Big Pickle), Kilo and Token Harbor together, showing each provider's disclosure. It remembers the approved policy versions in a private local receipt. Declining or cancelling skips those providers and continues with Zro. Changed or newly added policies require another grouped approval. Background setup never prompts, and both signup and routing require the current receipt.
24
31
 
25
32
  Kilo free models may log prompts or use them for training; avoid sensitive prompts. Their free limits are unknown. Kilo quota errors fall through FreeLLMAPI's fallback chain. Requests allow a long timeout for Nemotron reasoning.
26
33
 
@@ -0,0 +1,27 @@
1
+ import { readDataSharingConsent } from './data-sharing.js';
2
+ import { SourceError } from './source.js';
3
+ // Every request rechecks the policy receipt, including requests made with an
4
+ // existing grant. A daemon cannot silently keep sharing after approval changes.
5
+ export class ConsentSource {
6
+ source;
7
+ directory;
8
+ id;
9
+ supportsFunctionTools;
10
+ constructor(source, directory) {
11
+ this.source = source;
12
+ this.directory = directory;
13
+ this.id = source.id;
14
+ if (source.supportsFunctionTools !== undefined)
15
+ this.supportsFunctionTools = source.supportsFunctionTools;
16
+ }
17
+ async approved() { return (await readDataSharingConsent(this.directory, [this.id])).includes(this.id); }
18
+ async available() { return await this.approved() && await this.source.available(); }
19
+ async healthCheck() { return await this.approved() && await (this.source.healthCheck?.() ?? this.source.available()); }
20
+ async complete(request, signal) {
21
+ signal.throwIfAborted();
22
+ if (!await this.approved())
23
+ throw new SourceError('refused', `${this.id} data sharing is not approved; rerun usegrunt setup`);
24
+ return this.source.complete(request, signal);
25
+ }
26
+ async close() { await this.source.close?.(); }
27
+ }
@@ -0,0 +1,100 @@
1
+ import { constants } from 'node:fs';
2
+ import { mkdir, open, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { join } from 'node:path';
5
+ import { confirm, isCancel } from '@clack/prompts';
6
+ import { withTerminal } from './terminal.js';
7
+ // Keep these provider-specific. An unknown policy must not inherit consent to
8
+ // another provider merely because both offer free inference.
9
+ export const DATA_SHARING_POLICIES = [{
10
+ provider: 'freebuff', name: 'Freebuff', version: '2026-11-15',
11
+ disclosure: 'Prompt, code, and project data may be retained and reviewed for safety, analyzed for advertising and ad-model training. For features marked for AI training, data may also be shared or sold for training and research.',
12
+ url: 'https://freebuff.com/privacy-policy'
13
+ }, {
14
+ provider: 'opencode', name: 'OpenCode free model pool', version: '2026-11-15',
15
+ disclosure: 'DeepSeek and GLM free routes have zero-retention and no-training policies. The pool also includes Big Pickle, whose collected data may be used for model improvement.',
16
+ url: 'https://opencode.ai/docs/console/models/#privacy'
17
+ }, {
18
+ provider: 'kilo', name: 'Kilo Auto Free', version: '2026-11-15',
19
+ disclosure: 'Auto Free may select providers that log prompts and outputs and use them to improve their services. Do not submit personal or confidential data.',
20
+ url: 'https://kilo.ai/docs/getting-started/using-kilo-for-free'
21
+ }, {
22
+ provider: 'tokenharbor', name: 'Token Harbor', version: '2026-11-15',
23
+ disclosure: 'Prompts and responses may be retained, read by staff, and used by upstream providers for training.',
24
+ url: 'https://team.tokenharbor.ai/faq'
25
+ }];
26
+ const fileName = 'data-sharing-consent.json';
27
+ const emptyReceipt = () => ({ version: 1, approved: {} });
28
+ const fingerprint = (policy) => createHash('sha256').update(JSON.stringify(policy)).digest('hex');
29
+ export function dataSharingPolicies(providers) {
30
+ const selected = new Set(providers);
31
+ return DATA_SHARING_POLICIES.filter(policy => selected.has(policy.provider));
32
+ }
33
+ export const requiresDataSharing = (provider) => DATA_SHARING_POLICIES.some(policy => policy.provider === provider);
34
+ async function receipt(directory) {
35
+ try {
36
+ const file = await open(join(directory, fileName), constants.O_RDONLY | constants.O_NOFOLLOW);
37
+ try {
38
+ const stat = await file.stat();
39
+ if (!stat.isFile() || (stat.mode & 0o777) !== 0o600 || stat.uid !== process.getuid?.())
40
+ return emptyReceipt();
41
+ const value = JSON.parse(await file.readFile('utf8'));
42
+ if (value.version !== 1 || !value.approved || typeof value.approved !== 'object' || Array.isArray(value.approved))
43
+ return emptyReceipt();
44
+ const approved = Object.fromEntries(Object.entries(value.approved).filter(([, item]) => item
45
+ && typeof item.policy === 'string' && typeof item.approvedAt === 'string' && Number.isFinite(Date.parse(item.approvedAt))));
46
+ return { version: 1, approved };
47
+ }
48
+ finally {
49
+ await file.close();
50
+ }
51
+ }
52
+ catch {
53
+ return emptyReceipt();
54
+ }
55
+ }
56
+ // Background setup only reads this receipt; it never opens an approval prompt.
57
+ export async function readDataSharingConsent(directory, providers) {
58
+ const saved = await receipt(directory);
59
+ return dataSharingPolicies(providers).filter(policy => saved.approved[policy.provider]?.policy === fingerprint(policy)).map(policy => policy.provider);
60
+ }
61
+ // Also used when an operator has already obtained explicit approval outside the
62
+ // CLI. This records the same current provider policies as the grouped prompt.
63
+ export async function recordDataSharingConsent(directory, providers) {
64
+ const policies = dataSharingPolicies(providers);
65
+ if (!policies.length)
66
+ return;
67
+ const saved = await receipt(directory);
68
+ const approvedAt = new Date().toISOString();
69
+ for (const policy of policies)
70
+ saved.approved[policy.provider] = { policy: fingerprint(policy), approvedAt };
71
+ await mkdir(directory, { recursive: true, mode: 0o700 });
72
+ const temporary = join(directory, `${fileName}.${randomUUID()}.tmp`);
73
+ try {
74
+ await writeFile(temporary, JSON.stringify(saved), { mode: 0o600, flag: 'wx' });
75
+ await rename(temporary, join(directory, fileName));
76
+ }
77
+ finally {
78
+ await rm(temporary, { force: true });
79
+ }
80
+ }
81
+ export async function approveDataSharing(options) {
82
+ const policies = dataSharingPolicies(options.providers);
83
+ const approved = await readDataSharingConsent(options.directory, options.providers);
84
+ const pending = policies.filter(policy => !approved.includes(policy.provider));
85
+ if (!pending.length)
86
+ return { approved, skipped: [] };
87
+ const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY && process.env.MILO_SETUP_NO_HUMAN !== '1');
88
+ const prompt = options.prompt ?? (async (list) => withTerminal(async () => confirm({
89
+ message: `Allow data sharing for all these free services?\n${list.map(policy => `${policy.name}: ${policy.disclosure} ${policy.url}`).join('\n')}\nDeclining skips these services; other free services continue.`,
90
+ initialValue: false
91
+ })));
92
+ if (!interactive)
93
+ return { approved, skipped: pending.map(policy => policy.provider) };
94
+ const answer = await prompt(pending);
95
+ if (isCancel(answer) || answer !== true)
96
+ return { approved, skipped: pending.map(policy => policy.provider) };
97
+ const newlyApproved = pending.map(policy => policy.provider);
98
+ await recordDataSharingConsent(options.directory, newlyApproved);
99
+ return { approved: [...approved, ...newlyApproved], skipped: [] };
100
+ }
@@ -0,0 +1,16 @@
1
+ import { isDeepSeekV41Model } from './free-api.js';
2
+ // A provider must acknowledge the pinned model before its completion can be
3
+ // attributed to this route. Error payloads and model mismatches stay private.
4
+ export function verifiedDeepSeekFetch(fetcher) {
5
+ return async (input, init) => {
6
+ const response = await (fetcher ?? fetch)(input, init);
7
+ if (response.ok && String(input).endsWith('/chat/completions')) {
8
+ const result = await response.clone().json();
9
+ if (!isDeepSeekV41Model(result.model)) {
10
+ await response.body?.cancel();
11
+ return new Response(null, { status: 502 });
12
+ }
13
+ }
14
+ return response;
15
+ };
16
+ }
@@ -2,10 +2,12 @@ import { spawn, execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
3
  import { mkdir, writeFile, access } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
- import { BrowserSquire } from './setup.js';
5
+ import { BrowserSquire, setup } from './setup.js';
6
+ import { parallelMap } from './parallel.js';
6
7
  import { OpenCode } from './opencode.js';
7
8
  import { DOCTOR_TIMEOUT_MS } from './freebuff.js';
8
9
  import { SourceError, Sources } from './source.js';
10
+ import { DATA_SHARING_POLICIES, readDataSharingConsent, requiresDataSharing } from './data-sharing.js';
9
11
  const exec = promisify(execFile);
10
12
  class FreebuffCompatibilityError extends Error {
11
13
  }
@@ -61,9 +63,13 @@ export async function verifyOpenCode(source = new OpenCode(), signal = AbortSign
61
63
  }
62
64
  }
63
65
  export async function setupFallbacks(options) {
64
- const squire = options.squire ?? new BrowserSquire();
66
+ const squire = options.squire ?? new BrowserSquire({ dataSharingApproved: options.dataSharingApproved ?? [] });
65
67
  const owned = squire instanceof BrowserSquire && !options.squire;
66
68
  const unavailable = [];
69
+ const adapters = options.adapters ?? ['freebuff', 'opencode'];
70
+ const approved = [...new Set([...(options.dataSharingApproved ?? []), ...await readDataSharingConsent(options.directory, DATA_SHARING_POLICIES.map(policy => policy.provider))])];
71
+ if (squire instanceof BrowserSquire)
72
+ squire.approveDataSharing(approved);
67
73
  // Reuse a grant created by an earlier setup before probing the free model.
68
74
  const savedConfig = join(options.directory, 'opencode-free.json');
69
75
  try {
@@ -74,119 +80,185 @@ export async function setupFallbacks(options) {
74
80
  if (error.code !== 'ENOENT')
75
81
  throw error;
76
82
  }
77
- let connected = false;
78
- const connect = async () => { if (!connected) {
79
- if (options.connect)
80
- await options.connect();
81
- else if (owned)
82
- await squire.connect();
83
- connected = true;
84
- } };
83
+ let connection;
84
+ const connect = () => connection ??= (async () => { if (options.connect)
85
+ await options.connect();
86
+ else if (owned)
87
+ await squire.connect(); })();
85
88
  const install = async (binary, pkg) => {
86
89
  try {
87
90
  await options.run(binary, ['--version']);
88
91
  }
89
92
  catch {
90
- await options.run('npm', ['install', '--global', pkg], true);
93
+ await options.run('npm', ['install', '--global', pkg]);
91
94
  }
92
95
  };
93
96
  options.notify('Free routes run their own tools with your filesystem permissions in the working directory. Free model providers may retain prompts.');
94
97
  try {
95
- if (!options.adapters || options.adapters.includes('freebuff'))
96
- try {
97
- await install('freebuff', 'freebuff');
98
- // Older CLIs accept --version but cannot run the login diagnostic.
98
+ const tasks = {
99
+ freebuff: async () => {
99
100
  try {
100
- await options.run('freebuff', ['doctor']);
101
- }
102
- catch {
103
- options.notify('Freebuff: repairing the installed CLI before checking sign-in');
101
+ await install('freebuff', 'freebuff');
102
+ // Older CLIs accept --version but cannot run the login diagnostic.
104
103
  try {
105
- await options.run('npm', ['install', '--global', 'freebuff@latest'], true);
106
104
  await options.run('freebuff', ['doctor']);
107
105
  }
108
106
  catch {
109
- throw new FreebuffCompatibilityError('Freebuff CLI repair incomplete. The active freebuff on PATH must support doctor. Run npm install --global freebuff@latest, remove older Freebuff binaries earlier on PATH, then rerun usegrunt setup. Continuing with OpenCode.');
107
+ options.notify('Freebuff: repairing the installed CLI before checking sign-in');
108
+ try {
109
+ await options.run('npm', ['install', '--global', 'freebuff@latest']);
110
+ await options.run('freebuff', ['doctor']);
111
+ }
112
+ catch {
113
+ throw new FreebuffCompatibilityError('Freebuff CLI repair incomplete. The active freebuff on PATH must support doctor. Run npm install --global freebuff@latest, remove older Freebuff binaries earlier on PATH, then rerun usegrunt setup. Continuing with OpenCode.');
114
+ }
115
+ }
116
+ try {
117
+ await options.run('tmux', ['-V']);
118
+ }
119
+ catch {
120
+ if (process.platform === 'darwin')
121
+ await options.run('brew', ['install', 'tmux'], true);
122
+ else {
123
+ let manager;
124
+ for (const candidate of ['apt-get', 'dnf']) {
125
+ try {
126
+ await options.run(candidate, ['--version']);
127
+ manager = candidate;
128
+ break;
129
+ }
130
+ catch { /* Try the next supported OS package manager. */ }
131
+ }
132
+ if (!manager)
133
+ throw new Error('Install tmux with your OS package manager');
134
+ const args = ['install', '-y', 'tmux'];
135
+ await options.run(process.getuid?.() === 0 ? manager : 'sudo', process.getuid?.() === 0 ? args : [manager, ...args], true);
136
+ }
110
137
  }
138
+ const signedIn = options.signedIn ?? freebuffSignedIn;
139
+ if (!await signedIn()) {
140
+ await connect();
141
+ if (options.login)
142
+ await options.login(squire);
143
+ else
144
+ await loginFreebuff(squire, options.signal);
145
+ }
146
+ if (!await signedIn())
147
+ throw new Error('Freebuff is still signed out; rerun setup to resume');
148
+ options.notify('Freebuff: signed in; grunt will start its loopback bridge with the background service');
111
149
  }
112
- try {
113
- await options.run('tmux', ['-V']);
150
+ catch (error) {
151
+ unavailable.push('freebuff');
152
+ if (error instanceof FreebuffCompatibilityError)
153
+ options.notify(error.message);
154
+ else
155
+ options.notify('Freebuff setup incomplete. Run freebuff doctor, install tmux if missing, then rerun usegrunt setup. Continuing with OpenCode.');
114
156
  }
115
- catch {
116
- if (process.platform === 'darwin')
117
- await options.run('brew', ['install', 'tmux'], true);
118
- else {
119
- let manager;
120
- for (const candidate of ['apt-get', 'dnf']) {
121
- try {
122
- await options.run(candidate, ['--version']);
123
- manager = candidate;
124
- break;
125
- }
126
- catch { /* Try the next supported OS package manager. */ }
157
+ },
158
+ opencode: async () => {
159
+ try {
160
+ await install('opencode', 'opencode-ai');
161
+ const verify = options.verify ?? (() => verifyOpenCode(new OpenCode(), options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(120000)]) : AbortSignal.timeout(120000)));
162
+ try {
163
+ await verify();
164
+ }
165
+ catch (error) {
166
+ if (!(error instanceof SourceError) || error.code !== 'logged_out')
167
+ throw error;
168
+ await connect();
169
+ const findCredential = async () => (await squire.credentials.list()).find(c => c.service?.trim().toLowerCase() === 'opencode'
170
+ && c.auth_strategy !== 'username_password' && c.field_names.some(field => /^(?:api_?key|token|key)$/i.test(field)));
171
+ let credential = await findCredential();
172
+ if (!credential) {
173
+ await squire.signup('opencode', 'https://opencode.ai/auth', "Use the user's existing OpenCode account or sign up for free access. Use operate_extract to store an OpenCode Zen API key directly in this user's Squire vault under service opencode. Never include its value in your answer. No payment, paid plans, extra accounts or account switching. Stop if free access requires payment. Report human verification for browser handoff; do not bypass it.");
174
+ credential = await findCredential();
127
175
  }
128
- if (!manager)
129
- throw new Error('Install tmux with your OS package manager');
130
- const args = ['install', '-y', 'tmux'];
131
- await options.run(process.getuid?.() === 0 ? manager : 'sudo', process.getuid?.() === 0 ? args : [manager, ...args], true);
176
+ if (!credential)
177
+ throw new Error('No OpenCode access was created');
178
+ const grant = await squire.credentials.grant(credential.reference);
179
+ const path = join(options.directory, 'opencode-free.json');
180
+ await mkdir(options.directory, { recursive: true, mode: 0o700 });
181
+ await writeFile(path, JSON.stringify({ provider: { opencode: { options: { baseURL: grant.base_url.replace(/\/$/, '') + '/zen/v1', apiKey: grant.token } } } }), { mode: 0o600 });
182
+ process.env.OPENCODE_CONFIG = path;
183
+ await verify();
132
184
  }
185
+ options.notify('OpenCode: free model answered');
186
+ }
187
+ catch {
188
+ unavailable.push('opencode');
189
+ options.notify('OpenCode free model check failed or signup was refused. Rerun usegrunt setup after repairing OpenCode; other routes remain available.');
133
190
  }
134
- const signedIn = options.signedIn ?? freebuffSignedIn;
135
- if (!await signedIn()) {
191
+ },
192
+ kilo: async () => {
193
+ try {
136
194
  await connect();
137
- if (options.login)
138
- await options.login(squire);
139
- else
140
- await loginFreebuff(squire, options.signal);
195
+ if (!squire.runs)
196
+ throw new Error('Provider signup requires Squire');
197
+ await (options.setupProvider ?? setup)(options.notify, ['kilo'], { squire: squire, directory: options.directory, dataSharingApproved: approved, ...(options.signal ? { signal: options.signal } : {}) });
198
+ options.notify('Kilo: free API access connected through Squire');
141
199
  }
142
- if (!await signedIn())
143
- throw new Error('Freebuff is still signed out; rerun setup to resume');
144
- options.notify('Freebuff: signed in; grunt will start its loopback bridge with the background service');
145
- }
146
- catch (error) {
147
- unavailable.push('freebuff');
148
- if (error instanceof FreebuffCompatibilityError)
149
- options.notify(error.message);
150
- else
151
- options.notify('Freebuff setup incomplete. Run freebuff doctor, install tmux if missing, then rerun usegrunt setup. Continuing with OpenCode.');
152
- }
153
- if (!options.adapters || options.adapters.includes('opencode'))
154
- try {
155
- await install('opencode', 'opencode-ai');
156
- const verify = options.verify ?? (() => verifyOpenCode(new OpenCode(), options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(120000)]) : AbortSignal.timeout(120000)));
200
+ catch {
201
+ unavailable.push('kilo');
202
+ options.notify('Kilo setup incomplete. Rerun usegrunt setup to resume; other routes remain available.');
203
+ }
204
+ },
205
+ zro: async () => {
157
206
  try {
158
- await verify();
207
+ await connect();
208
+ if (!squire.runs)
209
+ throw new Error('Provider signup requires Squire');
210
+ await (options.setupProvider ?? setup)(options.notify, ['zro'], { squire: squire, directory: options.directory, ...(options.signal ? { signal: options.signal } : {}) });
211
+ options.notify('Zro: daily free DeepSeek V4.1 Flash access connected through Squire');
159
212
  }
160
- catch (error) {
161
- if (!(error instanceof SourceError) || error.code !== 'logged_out')
162
- throw error;
213
+ catch {
214
+ unavailable.push('zro');
215
+ options.notify('Zro setup incomplete. Rerun usegrunt setup to resume; other routes remain available.');
216
+ }
217
+ },
218
+ tokenharbor: async () => {
219
+ try {
163
220
  await connect();
164
- const findCredential = async () => (await squire.credentials.list()).find(c => c.service?.trim().toLowerCase() === 'opencode'
165
- && c.auth_strategy !== 'username_password' && c.field_names.some(field => /^(?:api_?key|token|key)$/i.test(field)));
166
- let credential = await findCredential();
167
- if (!credential) {
168
- await squire.signup('opencode', 'https://opencode.ai/auth', "Use the user's existing OpenCode account or sign up for free access. Use operate_extract to store an OpenCode Zen API key directly in this user's Squire vault under service opencode. Never include its value in your answer. No payment, paid plans, extra accounts or account switching. Stop if free access requires payment. Report human verification for browser handoff; do not bypass it.");
169
- credential = await findCredential();
170
- }
171
- if (!credential)
172
- throw new Error('No OpenCode access was created');
173
- const grant = await squire.credentials.grant(credential.reference);
174
- const path = join(options.directory, 'opencode-free.json');
175
- await mkdir(options.directory, { recursive: true, mode: 0o700 });
176
- await writeFile(path, JSON.stringify({ provider: { opencode: { options: { baseURL: grant.base_url.replace(/\/$/, '') + '/zen/v1', apiKey: grant.token } } } }), { mode: 0o600 });
177
- process.env.OPENCODE_CONFIG = path;
178
- await verify();
221
+ if (!squire.runs)
222
+ throw new Error('Provider signup requires Squire');
223
+ await (options.setupProvider ?? setup)(options.notify, ['tokenharbor'], { squire: squire, directory: options.directory,
224
+ dataSharingApproved: approved, ...(options.signal ? { signal: options.signal } : {}) });
225
+ options.notify('Token Harbor: approved free DeepSeek V4.1 Flash access connected through Squire');
226
+ }
227
+ catch {
228
+ unavailable.push('tokenharbor');
229
+ options.notify('Token Harbor setup incomplete or data sharing not approved. Run usegrunt setup to finish; other routes remain available.');
230
+ }
231
+ },
232
+ nvidia: async () => {
233
+ try {
234
+ await connect();
235
+ if (!squire.runs)
236
+ throw new Error('Provider signup requires Squire');
237
+ await (options.setupProvider ?? setup)(options.notify, ['nvidia'], { squire: squire, ...(options.signal ? { signal: options.signal } : {}) });
238
+ options.notify('NVIDIA: free DeepSeek V4.1 Flash API access connected through Squire');
239
+ }
240
+ catch {
241
+ unavailable.push('nvidia');
242
+ options.notify('NVIDIA setup incomplete. Rerun usegrunt setup to resume; other routes remain available.');
179
243
  }
180
- options.notify('OpenCode: free model answered');
181
244
  }
182
- catch {
183
- unavailable.push('opencode');
184
- options.notify('OpenCode free model check failed or signup was refused. Rerun usegrunt setup after repairing OpenCode; other routes remain available.');
245
+ };
246
+ await parallelMap(adapters, async (id) => {
247
+ if (requiresDataSharing(id) && !approved.includes(id)) {
248
+ unavailable.push(id);
249
+ options.notify(`${id}: skipped until the grouped data-sharing approval is granted`);
250
+ return;
185
251
  }
186
- return { unavailable };
252
+ const task = tasks[id];
253
+ if (!task)
254
+ throw new Error('Unsupported vetted adapter');
255
+ await task();
256
+ }, 3, options.signal);
257
+ options.signal?.throwIfAborted();
258
+ return { unavailable: adapters.filter(id => unavailable.includes(id)) };
187
259
  }
188
260
  finally {
189
- if (owned && connected)
261
+ if (owned && connection)
190
262
  await squire.close();
191
263
  }
192
264
  }
@@ -0,0 +1,137 @@
1
+ import { constants } from 'node:fs';
2
+ import { open } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { SourceError } from './source.js';
6
+ // Probe-only providers: these are not enabled by the published adapter registry.
7
+ export const FREE_API_PROVIDERS = {
8
+ zro: { model: 'deepseek-v4.1-flash', prefix: '/v1' },
9
+ amd: { model: 'DeepSeek-V4.1-Flash', prefix: '/radeon/api/v1' },
10
+ tokenharbor: { model: 'deepseek-v4.1-flash:free', prefix: '/v1' }
11
+ };
12
+ // Official API metadata maps deepseek-flash to DeepSeek-V4.1-Flash:
13
+ // https://api-docs.deepseek.com/api/list-models/ . Other aliases below are the
14
+ // explicit V4.1 IDs used by these providers, not loose family-name matches.
15
+ const deepSeekV41Aliases = new Set(['deepseek-flash', 'deepseek-v4.1-flash', 'deepseek-v4.1-flash-1017',
16
+ 'deepseek-v4.1-flash-free', 'deepseek-v4.1-flash:free']);
17
+ export function isDeepSeekV41Model(value) {
18
+ return typeof value === 'string' && deepSeekV41Aliases.has(value.toLowerCase().replace(/^deepseek\//, ''));
19
+ }
20
+ const directory = () => process.env.MILO_CONFIG_DIR || join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
21
+ function providerName(value) {
22
+ if (!Object.hasOwn(FREE_API_PROVIDERS, value))
23
+ throw new Error('Unsupported free API provider');
24
+ return value;
25
+ }
26
+ function validateGrant(value) {
27
+ const grant = value;
28
+ if (!grant || typeof grant.base_url !== 'string' || typeof grant.token !== 'string' || !grant.token.trim())
29
+ throw new Error('Invalid free API grant');
30
+ let url;
31
+ try {
32
+ url = new URL(grant.base_url);
33
+ }
34
+ catch {
35
+ throw new Error('Invalid free API grant endpoint');
36
+ }
37
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash)
38
+ throw new Error('Invalid free API grant endpoint');
39
+ return { base_url: grant.base_url.replace(/\/$/, ''), token: grant.token };
40
+ }
41
+ export async function readFreeApiGrant(provider, location = directory()) {
42
+ const name = providerName(provider);
43
+ const file = await open(join(location, `${name}.json`), constants.O_RDONLY | constants.O_NOFOLLOW);
44
+ try {
45
+ const stat = await file.stat();
46
+ if (!stat.isFile() || (stat.mode & 0o777) !== 0o600 || stat.uid !== process.getuid?.())
47
+ throw new Error('Unsafe free API grant file');
48
+ return validateGrant(JSON.parse(await file.readFile('utf8')));
49
+ }
50
+ finally {
51
+ await file.close();
52
+ }
53
+ }
54
+ const tokens = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
55
+ const validCalls = (value) => Array.isArray(value) && value.every(call => call && typeof call.id === 'string'
56
+ && call.type === 'function' && typeof call.function?.name === 'string' && typeof call.function?.arguments === 'string');
57
+ export class FreeApi {
58
+ options;
59
+ id;
60
+ supportsFunctionTools = true;
61
+ shutdown = new AbortController();
62
+ constructor(provider, options = {}) {
63
+ this.options = options;
64
+ this.id = providerName(provider);
65
+ }
66
+ get spec() { return FREE_API_PROVIDERS[this.id]; }
67
+ grant() { return (this.options.loadGrant?.() ?? readFreeApiGrant(this.id, this.options.directory)).then(validateGrant); }
68
+ // Availability here means private access is configured. Only the live probe
69
+ // establishes whether the provider will serve the requested free model.
70
+ async available() { try {
71
+ await this.grant();
72
+ return true;
73
+ }
74
+ catch {
75
+ return false;
76
+ } }
77
+ async complete(request, caller) {
78
+ caller.throwIfAborted();
79
+ if (![this.id, 'milo'].includes(request.model))
80
+ throw new SourceError('upstream', 'Free API probe requires an explicit provider');
81
+ if (request.tools.some(tool => tool.type !== 'function'))
82
+ throw new SourceError('upstream', 'Free API probe requires function tools');
83
+ let grant;
84
+ try {
85
+ grant = await this.grant();
86
+ }
87
+ catch {
88
+ throw new SourceError('logged_out', `${this.id} access is not configured`);
89
+ }
90
+ const signal = AbortSignal.any([caller, this.shutdown.signal, AbortSignal.timeout(this.options.timeout ?? 180000)]);
91
+ let response;
92
+ try {
93
+ response = await (this.options.fetcher ?? fetch)(`${grant.base_url}${this.spec.prefix}/chat/completions`, {
94
+ method: 'POST', redirect: 'error', signal,
95
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${grant.token}` },
96
+ body: JSON.stringify({ model: this.spec.model, messages: request.messages,
97
+ tools: request.tools.length ? request.tools : undefined, stream: false,
98
+ max_tokens: Math.min(4096, Math.max(1, request.maxTokens ?? 4096)) })
99
+ });
100
+ }
101
+ catch {
102
+ caller.throwIfAborted();
103
+ if (this.shutdown.signal.aborted)
104
+ throw new SourceError('cancelled', 'Free API probe closed');
105
+ throw new SourceError(signal.aborted ? 'timeout' : 'upstream', `${this.id} endpoint is unavailable`);
106
+ }
107
+ if (!response.ok) {
108
+ const raw = response.headers.get('retry-after');
109
+ const retry = raw === null ? NaN : /^\d+(?:\.\d+)?$/.test(raw) ? Number(raw) : (Date.parse(raw) - Date.now()) / 1000;
110
+ await response.body?.cancel();
111
+ throw new SourceError(response.status === 401 ? 'logged_out' : [402, 429].includes(response.status) ? 'quota' : response.status === 403 ? 'refused' : 'upstream', `${this.id} returned HTTP ${response.status}`, Number.isFinite(retry) ? Math.max(1, retry) : undefined);
112
+ }
113
+ try {
114
+ const body = await response.json();
115
+ signal.throwIfAborted();
116
+ const message = body.choices?.[0]?.message;
117
+ if (message?.refusal)
118
+ throw new SourceError('refused', `${this.id} refused the request`);
119
+ const calls = message?.tool_calls;
120
+ if (!message || (typeof message.content !== 'string' && !(validCalls(calls) && calls.length)) || (calls !== undefined && !validCalls(calls)))
121
+ throw new SourceError('upstream', `${this.id} returned an invalid completion`);
122
+ return { text: typeof message.content === 'string' ? message.content : '', ...(validCalls(calls) && calls.length ? { calls } : {}),
123
+ inputTokens: tokens(body.usage?.prompt_tokens), outputTokens: tokens(body.usage?.completion_tokens) };
124
+ }
125
+ catch (error) {
126
+ caller.throwIfAborted();
127
+ if (this.shutdown.signal.aborted)
128
+ throw new SourceError('cancelled', 'Free API probe closed');
129
+ if (signal.aborted)
130
+ throw new SourceError('timeout', `${this.id} endpoint is unavailable`);
131
+ if (error instanceof SourceError)
132
+ throw error;
133
+ throw new SourceError('upstream', `${this.id} returned an invalid completion`);
134
+ }
135
+ }
136
+ async close() { this.shutdown.abort(); }
137
+ }
@@ -67,6 +67,12 @@ export class FreeLLMAPI {
67
67
  }
68
68
  if (!response.ok)
69
69
  throw new SourceError(response.status === 403 ? 'refused' : response.status === 401 ? 'logged_out' : response.status === 429 ? 'quota' : 'upstream', `FreeLLMAPI returned HTTP ${response.status}`);
70
+ // FreeLLMAPI treats a pinned model as a preference and can fall back to
71
+ // another provider. Never attribute that provider's answer to Kilo.
72
+ if (this.id === 'kilo' && response.headers.get('x-routed-via') !== `custom/${this.options.model}`) {
73
+ await response.body?.cancel();
74
+ throw new SourceError('upstream', 'Kilo did not answer; the local backend selected another route');
75
+ }
70
76
  const result = await response.json();
71
77
  const message = result.choices?.[0]?.message;
72
78
  if (message?.refusal)