usegrunt 0.6.5 → 0.6.7
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 +20 -7
- package/dist/local/beatapi-setup.js +83 -0
- package/dist/local/beatapi.js +298 -0
- package/dist/local/clixad-preload.js +177 -0
- package/dist/local/clixad-setup.js +345 -0
- package/dist/local/clixad.js +398 -0
- package/dist/local/data-sharing.js +18 -2
- package/dist/local/fallback-setup.js +112 -33
- package/dist/local/freebuff.js +5 -1
- package/dist/local/freellmapi.js +3 -5
- package/dist/local/kilo.js +209 -0
- package/dist/local/main.js +62 -20
- package/dist/local/managed-router.js +4 -2
- package/dist/local/opencode.js +38 -18
- package/dist/local/parallel.js +2 -0
- package/dist/local/perch-process.js +377 -0
- package/dist/local/perch-setup.js +297 -0
- package/dist/local/perch.js +480 -0
- package/dist/local/pollinations-setup.js +109 -0
- package/dist/local/pollinations.js +324 -0
- package/dist/local/registry.js +4 -4
- package/dist/local/routing.js +5 -1
- package/dist/local/setup-session.js +232 -0
- package/dist/local/setup.js +343 -62
- package/dist/local/source.js +34 -4
- package/dist/local/wizard.js +283 -109
- package/dist/registry/adapters.json +57 -33
- package/dist/registry.js +4 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,23 +14,36 @@ 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
|
+
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
|
|
20
|
+
temporary failures and asks for foreground setup when human verification is needed.
|
|
21
|
+
|
|
17
22
|
https://grunt.run. `milo` and `milo-local` remain aliases.
|
|
18
23
|
|
|
19
|
-
|
|
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.
|
|
20
27
|
|
|
21
|
-
|
|
28
|
+
The original `npx usegrunt` terminal stays open as the approval console until the remaining jobs finish. Use a connected coding tool in another terminal while it works. Closing the console pauses unfinished signups; verified daemon routes keep running, and rerunning setup resumes the rest. Partial provider failures are reported without failing an installation that has at least one verified route. Perch remains in the default pool, but its human verification does not have to finish before another route becomes usable. Setup duration depends on downloads, prerequisites and verification; no cold-start time is promised.
|
|
22
29
|
|
|
23
|
-
|
|
30
|
+
[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).
|
|
24
31
|
|
|
25
|
-
|
|
32
|
+
In 0.6.6, one grouped data-sharing approval covers nine active providers. Setup reuses the person's Google or GitHub identity; each provider can still require its own verification. `usegrunt add <provider>` remains available for supported providers. Runcrate needs a GitHub account at least 30 days old. Mistral uses its native Vibe Free coding allowance, not ordinary API credit. NVIDIA stays optional while account verification is unvetted; Cloudflare Qwen is excluded by choice. The default `kilo` source selects `particle-ai/particle-1:free`. Repeat setup preserves eligible previously connected API sources.
|
|
33
|
+
|
|
34
|
+
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.
|
|
35
|
+
|
|
36
|
+
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.
|
|
26
37
|
|
|
27
38
|
Within OpenCode, new conversations rotate across DeepSeek V4.1 Flash Free,
|
|
28
39
|
GLM 5.3 Flash Free and Big Pickle. Follow-ups keep their model, and quota errors
|
|
29
40
|
try another free model. These models may share provider limits; the pool does
|
|
30
41
|
not create extra credit balances or purchase credits.
|
|
31
42
|
|
|
32
|
-
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. Runcrate requires no paid balance, no card and automatic top-ups off;
|
|
43
|
+
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. Runcrate requires no paid balance, no card and automatic top-ups off; Mistral Vibe keeps pay-as-you-go off. Setup shows provider-specific data-sharing disclosures together and remembers approved policy versions in a private receipt. Declining or cancelling skips those providers and continues with Zro and LiveKit, subject to their free-account checks. Changed or newly added policies require another grouped approval. Background setup never prompts, and both signup and routing require the current receipt where required.
|
|
44
|
+
|
|
45
|
+
Freebuff and APInex are retired from all grunt routing in 0.6.6. Freebuff's native application is preserved; its saved source selection and legacy fallback no longer enable routing, and no port-8789 bridge starts. APInex changed its recurring daily entitlement to require a $5 top-up; grunt makes no purchase, and a one-time Telegram reward is excluded. Old sharing receipts cannot reactivate either source.
|
|
33
46
|
|
|
34
|
-
Kilo free
|
|
47
|
+
Kilo Particle 1 is post-trained from DeepSeek V4.1 Flash; it is a distinct model with a listed one-million-token context. Its free route requires no account or API key and supports native function calls. Anonymous access is limited to 200 requests per hour per IP and upstream capacity; it uses no one-time credits. The catalog permits training on prompts, so the changed Kilo disclosure requires fresh grouped approval. Standard DeepSeek routes remain paid; Auto Free is a changing pool and is no longer the default in 0.6.6.
|
|
35
48
|
|
|
36
|
-
|
|
49
|
+
API-provider keys stay in Squire. The anonymous Kilo Particle route uses no credential; grunt verifies the exact model and zero reported cost before accepting its answer.
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { rm } from 'node:fs/promises';
|
|
2
|
+
import { DATA_SHARING_POLICIES, readDataSharingConsent } from './data-sharing.js';
|
|
3
|
+
import { BEATAPI_MODEL, BEATAPI_ORIGIN, beatapiGrantPath, readBeatAPIGrant, verifyBeatAPIAccess, writeBeatAPIGrant } from './beatapi.js';
|
|
4
|
+
const failure = () => new Error('BeatAPI free account or key verification did not complete; rerun usegrunt setup');
|
|
5
|
+
async function bounded(operation, signal) {
|
|
6
|
+
let abort;
|
|
7
|
+
try {
|
|
8
|
+
return await Promise.race([Promise.resolve().then(() => { signal.throwIfAborted(); return operation(); }), new Promise((_resolve, reject) => {
|
|
9
|
+
abort = () => reject(failure());
|
|
10
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
11
|
+
if (signal.aborted)
|
|
12
|
+
abort();
|
|
13
|
+
})]);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
throw failure();
|
|
17
|
+
}
|
|
18
|
+
finally {
|
|
19
|
+
if (abort)
|
|
20
|
+
signal.removeEventListener('abort', abort);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const eligible = (c) => c.service?.trim().toLowerCase() === 'beatapi' && c.auth_strategy !== 'username_password'
|
|
24
|
+
&& c.field_names.some(f => ['value', 'apikey', 'key', 'token', 'secret'].includes(f.toLowerCase().replace(/[^a-z]/g, '')))
|
|
25
|
+
&& c.allowed_hosts?.[0] === 'api.beatapi.io';
|
|
26
|
+
export async function setupBeatAPI(options) {
|
|
27
|
+
// The caller may carry approvals already recorded by this wizard turn, but
|
|
28
|
+
// an unknown or changed policy cannot silently inherit another provider's.
|
|
29
|
+
if (!DATA_SHARING_POLICIES.some(policy => policy.provider === 'beatapi'))
|
|
30
|
+
throw new Error('BeatAPI data-sharing policy is unavailable');
|
|
31
|
+
const saved = await readDataSharingConsent(options.directory, ['beatapi']);
|
|
32
|
+
if (!saved.includes('beatapi') || (options.dataSharingApproved && !options.dataSharingApproved.includes('beatapi')))
|
|
33
|
+
throw new Error('BeatAPI data sharing requires the current grouped setup approval');
|
|
34
|
+
const signal = AbortSignal.any([...(options.signal ? [options.signal] : []), AbortSignal.timeout(600000)]);
|
|
35
|
+
// A daemon can verify existing access, but cannot provision accounts, mint
|
|
36
|
+
// grants, invalidate receipts or launch browser verification. Foreground
|
|
37
|
+
// setup also reuses healthy access rather than disrupting a working route.
|
|
38
|
+
try {
|
|
39
|
+
const grant = await bounded(() => readBeatAPIGrant(options.directory), signal);
|
|
40
|
+
const usage = await bounded(() => verifyBeatAPIAccess(grant, { ...(options.fetcher ? { fetcher: options.fetcher } : {}), signal }), signal);
|
|
41
|
+
signal.throwIfAborted();
|
|
42
|
+
if (usage.credit_balance !== grant.baseline_balance)
|
|
43
|
+
throw failure();
|
|
44
|
+
options.notify?.('BeatAPI: existing verified free access reused');
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
if (signal.aborted)
|
|
49
|
+
throw failure();
|
|
50
|
+
}
|
|
51
|
+
if (options.background)
|
|
52
|
+
throw new Error('BeatAPI needs foreground verification; run usegrunt add beatapi');
|
|
53
|
+
const invalidate = () => rm(beatapiGrantPath(options.directory), { force: true });
|
|
54
|
+
try {
|
|
55
|
+
signal.throwIfAborted();
|
|
56
|
+
await invalidate();
|
|
57
|
+
signal.throwIfAborted();
|
|
58
|
+
options.squire.approveDataSharing?.(saved);
|
|
59
|
+
const fresh = async () => {
|
|
60
|
+
const result = await bounded(() => options.squire.call('list_credentials', { service: 'beatapi', fields: 'summary' }), signal);
|
|
61
|
+
if (!Array.isArray(result.credentials))
|
|
62
|
+
throw failure();
|
|
63
|
+
return result.credentials.filter(eligible);
|
|
64
|
+
};
|
|
65
|
+
const before = await fresh();
|
|
66
|
+
await bounded(() => options.squire.signup('beatapi', 'https://beatapi.io/dashboard/apikeys', `Use the personal Google identity already connected to Squire, or the same user's already linked GitHub identity, to sign in to the ordinary BeatAPI account. Reuse this account and existing vaulted BeatAPI key; never create another account, rotate a key or reset it. Verify Credits & billing: lifetime paid $0, no payment method, no subscription, auto recharge Off and unavailable without adding a payment method, no paid top-ups or purchases. Zero balance or the ordinary $2 signup credit is allowed; explicitly verify its signup provenance and no paid payment records. Stop on paid funds, payment method, automatic billing, refusal or unverifiable account facts; never change billing, top up, add a card or buy anything. Reuse the Grunt-owned key named grunt where available. Create exactly one grunt key only if no usable existing key exists. For that owned key, set Usage restrictions to a minimal allowlist containing only ${BEATAPI_MODEL} (an existing grunt key restricted to that model and glm-5.3-flash-free is also allowed). Do not modify an unrelated key. Confirm no paid model is allowed. Capture the new key using operate_extract directly into this user's Squire vault: service beatapi, label grunt, api_hosts ["api.beatapi.io"], auth_shape bearer. Never display, return, fetch or log any raw credential. The user approved BeatAPI's current grouped data-sharing policy; accept required ordinary terms and sharing disclosures only, leave optional marketing off. No phone/SMS, Discord, school approval or payment verification. Required human CAPTCHA/passkey/email verification needs normal browser handoff. Finish only after confirming the account and free-only key settings.`), signal);
|
|
67
|
+
const credentials = await fresh(), owned = credentials.filter(c => c.label === 'grunt');
|
|
68
|
+
const credential = owned.find(c => before.some(old => old.reference === c.reference)) ?? owned[0] ?? credentials.find(c => !before.some(old => old.reference === c.reference));
|
|
69
|
+
if (!credential)
|
|
70
|
+
throw failure();
|
|
71
|
+
const grant = await bounded(() => options.squire.credentials.grant(credential.reference), signal);
|
|
72
|
+
const usage = await bounded(() => verifyBeatAPIAccess(grant, { ...(options.fetcher ? { fetcher: options.fetcher } : {}), signal }), signal);
|
|
73
|
+
signal.throwIfAborted();
|
|
74
|
+
await writeBeatAPIGrant({ version: 1, ...grant, upstream_origin: BEATAPI_ORIGIN, model: BEATAPI_MODEL, verified_at: new Date().toISOString(), free_account_verified: true,
|
|
75
|
+
lifetime_paid: 0, payment_method_present: false, auto_recharge: false, credit_provenance: usage.credit_balance === 0 ? 'zero' : 'signup', baseline_balance: usage.credit_balance }, options.directory);
|
|
76
|
+
signal.throwIfAborted();
|
|
77
|
+
options.notify?.('BeatAPI: free-only DeepSeek V4.1 Flash access connected; one successful request per minute');
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
await invalidate().catch(() => { });
|
|
81
|
+
throw failure();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { lstat, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { Ajv } from 'ajv';
|
|
6
|
+
import { readDataSharingConsent } from './data-sharing.js';
|
|
7
|
+
import { providerGrantDirectory } from './provider-grant.js';
|
|
8
|
+
import { FreebuffTools } from './freebuff-tools.js';
|
|
9
|
+
import { SourceError } from './source.js';
|
|
10
|
+
export const BEATAPI_MODEL = 'deepseek-v4.1-flash-free';
|
|
11
|
+
export const BEATAPI_ORIGIN = 'https://api.beatapi.io';
|
|
12
|
+
export const BEATAPI_RECEIPT_MAX_AGE_MS = 30 * 86400000;
|
|
13
|
+
export const beatapiGrantPath = (directory = providerGrantDirectory()) => join(directory, 'beatapi.json');
|
|
14
|
+
const obj = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
15
|
+
const rejected = () => new SourceError('logged_out', 'BeatAPI private free-account verification is missing or expired; rerun usegrunt setup');
|
|
16
|
+
function access(value) {
|
|
17
|
+
const grant = obj(value);
|
|
18
|
+
if (typeof grant.base_url !== 'string' || typeof grant.token !== 'string' || !/^[\x21-\x7e]{1,16384}$/.test(grant.token))
|
|
19
|
+
throw rejected();
|
|
20
|
+
let url;
|
|
21
|
+
try {
|
|
22
|
+
url = new URL(grant.base_url);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw rejected();
|
|
26
|
+
}
|
|
27
|
+
if (url.origin !== 'https://trusty-squire-api.fly.dev' || url.username || url.password || url.search || url.hash
|
|
28
|
+
|| !/^\/v1\/egress\/g_[A-Za-z0-9_-]{16,64}\/?$/.test(url.pathname))
|
|
29
|
+
throw rejected();
|
|
30
|
+
return { base_url: url.href.replace(/\/$/, ''), token: grant.token };
|
|
31
|
+
}
|
|
32
|
+
function validate(value) {
|
|
33
|
+
const grant = obj(value), auth = access(value), checked = typeof grant.verified_at === 'string' ? Date.parse(grant.verified_at) : NaN;
|
|
34
|
+
if (grant.version !== 1 || grant.upstream_origin !== BEATAPI_ORIGIN || grant.model !== BEATAPI_MODEL || grant.free_account_verified !== true
|
|
35
|
+
|| grant.lifetime_paid !== 0 || grant.payment_method_present !== false || grant.auto_recharge !== false
|
|
36
|
+
|| !Number.isFinite(checked) || checked > Date.now() + 60000 || Date.now() - checked > BEATAPI_RECEIPT_MAX_AGE_MS
|
|
37
|
+
|| typeof grant.baseline_balance !== 'number' || !Number.isFinite(grant.baseline_balance) || grant.baseline_balance < 0 || grant.baseline_balance > 2
|
|
38
|
+
|| (grant.credit_provenance !== 'zero' && grant.credit_provenance !== 'signup')
|
|
39
|
+
|| (grant.credit_provenance === 'zero' ? grant.baseline_balance !== 0 : grant.baseline_balance <= 0))
|
|
40
|
+
throw rejected();
|
|
41
|
+
return { ...auth, version: 1, upstream_origin: BEATAPI_ORIGIN, model: BEATAPI_MODEL, verified_at: grant.verified_at,
|
|
42
|
+
free_account_verified: true, lifetime_paid: 0, payment_method_present: false, auto_recharge: false,
|
|
43
|
+
credit_provenance: grant.credit_provenance, baseline_balance: grant.baseline_balance };
|
|
44
|
+
}
|
|
45
|
+
async function privateDirectory(directory, create = false) {
|
|
46
|
+
if (create)
|
|
47
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
48
|
+
const stat = await lstat(directory);
|
|
49
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o700)
|
|
50
|
+
throw rejected();
|
|
51
|
+
}
|
|
52
|
+
export async function readBeatAPIGrant(directory = providerGrantDirectory()) {
|
|
53
|
+
let file;
|
|
54
|
+
try {
|
|
55
|
+
await privateDirectory(directory);
|
|
56
|
+
file = await open(beatapiGrantPath(directory), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
57
|
+
const stat = await file.stat();
|
|
58
|
+
if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600 || stat.size > 32768)
|
|
59
|
+
throw rejected();
|
|
60
|
+
return validate(JSON.parse(await file.readFile('utf8')));
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
throw rejected();
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
await file?.close();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export async function writeBeatAPIGrant(grant, directory = providerGrantDirectory()) {
|
|
70
|
+
const value = validate(grant);
|
|
71
|
+
await privateDirectory(directory, true);
|
|
72
|
+
const temporary = join(directory, `.beatapi-${randomUUID()}.tmp`);
|
|
73
|
+
try {
|
|
74
|
+
await writeFile(temporary, JSON.stringify(value), { flag: 'wx', mode: 0o600 });
|
|
75
|
+
await rename(temporary, beatapiGrantPath(directory));
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
await rm(temporary, { force: true });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function abortable(promise, signal) {
|
|
82
|
+
let abort;
|
|
83
|
+
try {
|
|
84
|
+
return await Promise.race([promise, new Promise((_resolve, reject) => {
|
|
85
|
+
abort = () => reject(signal.reason);
|
|
86
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
87
|
+
if (signal.aborted)
|
|
88
|
+
abort();
|
|
89
|
+
})]);
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
if (abort)
|
|
93
|
+
signal.removeEventListener('abort', abort);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async function json(response, signal, limit) {
|
|
97
|
+
if (!response.body || Number(response.headers.get('content-length')) > limit) {
|
|
98
|
+
void response.body?.cancel().catch(() => { });
|
|
99
|
+
throw new SourceError('upstream', 'BeatAPI response exceeded the supported size');
|
|
100
|
+
}
|
|
101
|
+
const reader = response.body.getReader(), chunks = [];
|
|
102
|
+
let size = 0;
|
|
103
|
+
try {
|
|
104
|
+
for (;;) {
|
|
105
|
+
const part = await abortable(reader.read(), signal);
|
|
106
|
+
signal.throwIfAborted();
|
|
107
|
+
if (part.done)
|
|
108
|
+
break;
|
|
109
|
+
size += part.value.byteLength;
|
|
110
|
+
if (size > limit)
|
|
111
|
+
throw new SourceError('upstream', 'BeatAPI response exceeded the supported size');
|
|
112
|
+
chunks.push(part.value);
|
|
113
|
+
}
|
|
114
|
+
return obj(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
void reader.cancel().catch(() => { });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function status(response) {
|
|
121
|
+
if (response.ok)
|
|
122
|
+
return;
|
|
123
|
+
const raw = response.headers.get('retry-after'), retry = raw === null ? NaN : /^\d+(?:\.\d+)?$/.test(raw) ? Number(raw) : (Date.parse(raw) - Date.now()) / 1000;
|
|
124
|
+
void response.body?.cancel().catch(() => { });
|
|
125
|
+
throw new SourceError(response.status === 401 ? 'logged_out' : response.status === 429 ? 'quota' : [402, 403].includes(response.status) ? 'refused' : 'upstream', `BeatAPI returned HTTP ${response.status}`, response.status === 429 ? Math.max(1, Number.isFinite(retry) ? Math.ceil(retry) : 60) : undefined);
|
|
126
|
+
}
|
|
127
|
+
// Public nonbillable API metadata. The published -free contract sets the price
|
|
128
|
+
// to zero even at zero balance; browser cookies are never needed at runtime.
|
|
129
|
+
export async function verifyBeatAPIAccess(grant, options = {}) {
|
|
130
|
+
const auth = access(grant), signal = AbortSignal.any([...(options.signal ? [options.signal] : []), AbortSignal.timeout(5000)]);
|
|
131
|
+
try {
|
|
132
|
+
const response = await abortable((options.fetcher ?? fetch)(`${auth.base_url}/v1/usage`, { headers: { Authorization: `Bearer ${auth.token}` }, redirect: 'error', signal }), signal);
|
|
133
|
+
status(response);
|
|
134
|
+
const usage = obj((await json(response, signal, 131072)).data);
|
|
135
|
+
if (usage.object !== 'usage' || typeof usage.credit_balance !== 'number' || !Number.isFinite(usage.credit_balance) || usage.credit_balance < 0 || usage.credit_balance > 2
|
|
136
|
+
|| usage.credits_settled !== 0 || ('lifetime_paid' in usage && usage.lifetime_paid !== 0)
|
|
137
|
+
|| ('payment_method_present' in usage && usage.payment_method_present !== false) || ('auto_recharge' in usage && usage.auto_recharge !== false)) {
|
|
138
|
+
throw new SourceError('refused', 'BeatAPI requires an unspent zero-balance or ordinary signup-credit account');
|
|
139
|
+
}
|
|
140
|
+
return { credit_balance: usage.credit_balance, credits_settled: 0 };
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
if (options.signal?.aborted)
|
|
144
|
+
throw new SourceError('cancelled', 'BeatAPI account check cancelled');
|
|
145
|
+
if (signal.aborted)
|
|
146
|
+
throw new SourceError('timeout', 'BeatAPI account check timed out');
|
|
147
|
+
if (error instanceof SourceError)
|
|
148
|
+
throw error;
|
|
149
|
+
throw new SourceError('upstream', 'BeatAPI account check failed');
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function tools(request) {
|
|
153
|
+
const validators = new Map();
|
|
154
|
+
try {
|
|
155
|
+
// Responses encodes parallel function calls as adjacent assistant items.
|
|
156
|
+
// Reassemble their single native assistant turn before correlation checks
|
|
157
|
+
// and forwarding, preserving every call ID, argument and result.
|
|
158
|
+
const messages = [];
|
|
159
|
+
for (const message of request.messages) {
|
|
160
|
+
const previous = messages.at(-1);
|
|
161
|
+
if (message.role === 'assistant' && message.content === '' && message.tool_calls?.length && !message.tool_call_id
|
|
162
|
+
&& previous?.role === 'assistant' && previous.content === '' && previous.tool_calls?.length && !previous.tool_call_id) {
|
|
163
|
+
previous.tool_calls = [...previous.tool_calls, ...message.tool_calls];
|
|
164
|
+
}
|
|
165
|
+
else
|
|
166
|
+
messages.push({ ...message });
|
|
167
|
+
}
|
|
168
|
+
// Validation only; this does not prompt a bridge or execute a function.
|
|
169
|
+
new FreebuffTools({ ...request, messages });
|
|
170
|
+
const ajv = new Ajv({ strict: true, strictTypes: false, strictTuples: false, addUsedSchema: false });
|
|
171
|
+
for (const tool of request.tools) {
|
|
172
|
+
const fn = obj(tool.function);
|
|
173
|
+
validators.set(fn.name, ajv.compile(fn.parameters));
|
|
174
|
+
}
|
|
175
|
+
return { validators, messages };
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
throw new SourceError('refused', 'BeatAPI rejected invalid function tools or an uncorrelated tool conversation');
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
export class BeatAPI {
|
|
182
|
+
options;
|
|
183
|
+
id = 'beatapi';
|
|
184
|
+
supportsFunctionTools = true;
|
|
185
|
+
shutdown = new AbortController();
|
|
186
|
+
pending = new Set();
|
|
187
|
+
next = 0;
|
|
188
|
+
busy = false;
|
|
189
|
+
constructor(options = {}) {
|
|
190
|
+
this.options = options;
|
|
191
|
+
}
|
|
192
|
+
now() { return (this.options.now ?? Date.now)(); }
|
|
193
|
+
grant() { return (this.options.loadGrant?.() ?? readBeatAPIGrant(this.options.directory)).then(validate); }
|
|
194
|
+
async approved() { return (await readDataSharingConsent(this.options.directory ?? providerGrantDirectory(), [this.id])).includes(this.id); }
|
|
195
|
+
async track(task) { this.pending.add(task); try {
|
|
196
|
+
return await task;
|
|
197
|
+
}
|
|
198
|
+
finally {
|
|
199
|
+
this.pending.delete(task);
|
|
200
|
+
} }
|
|
201
|
+
async available() {
|
|
202
|
+
return this.track((async () => {
|
|
203
|
+
try {
|
|
204
|
+
if (this.shutdown.signal.aborted || this.busy || this.now() < this.next || !await this.approved())
|
|
205
|
+
return false;
|
|
206
|
+
const grant = await this.grant(), usage = await verifyBeatAPIAccess(grant, { ...(this.options.fetcher ? { fetcher: this.options.fetcher } : {}), signal: this.shutdown.signal });
|
|
207
|
+
return !this.shutdown.signal.aborted && usage.credit_balance === grant.baseline_balance;
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
212
|
+
})());
|
|
213
|
+
}
|
|
214
|
+
async healthCheck() { return this.available(); }
|
|
215
|
+
async complete(request, caller) {
|
|
216
|
+
if (caller.aborted)
|
|
217
|
+
throw new SourceError('cancelled', 'BeatAPI request cancelled');
|
|
218
|
+
if (this.busy || this.now() < this.next)
|
|
219
|
+
throw new SourceError('quota', 'BeatAPI free requests are limited to one successful request per minute', Math.max(1, Math.ceil((this.next - this.now()) / 1000)));
|
|
220
|
+
this.busy = true;
|
|
221
|
+
try {
|
|
222
|
+
return await this.track(this.once(request, caller));
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
this.busy = false;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
async once(request, caller) {
|
|
229
|
+
const signal = AbortSignal.any([caller, this.shutdown.signal, AbortSignal.timeout(this.options.timeout ?? 180000)]);
|
|
230
|
+
try {
|
|
231
|
+
signal.throwIfAborted();
|
|
232
|
+
if (![this.id, 'milo'].includes(request.model) || request.imageInput)
|
|
233
|
+
throw new SourceError('refused', 'BeatAPI requires its pinned text-only free route');
|
|
234
|
+
const { validators, messages } = tools(request);
|
|
235
|
+
if (!await this.approved())
|
|
236
|
+
throw new SourceError('refused', 'BeatAPI data sharing is not approved; rerun usegrunt setup');
|
|
237
|
+
const grant = await this.grant(), guards = { ...(this.options.fetcher ? { fetcher: this.options.fetcher } : {}), signal };
|
|
238
|
+
const before = await verifyBeatAPIAccess(grant, guards);
|
|
239
|
+
if (before.credit_balance !== grant.baseline_balance)
|
|
240
|
+
throw new SourceError('refused', 'BeatAPI account balance changed; rerun usegrunt setup');
|
|
241
|
+
const response = await abortable((this.options.fetcher ?? fetch)(`${grant.base_url}/v1/chat/completions`, { method: 'POST', redirect: 'error', signal,
|
|
242
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${grant.token}` }, body: JSON.stringify({ model: BEATAPI_MODEL, messages,
|
|
243
|
+
...(request.tools.length ? { tools: request.tools } : {}), stream: false, max_tokens: Math.min(4096, Math.max(1, Number.isFinite(request.maxTokens) ? Math.floor(request.maxTokens) : 4096)) }) }), signal);
|
|
244
|
+
status(response);
|
|
245
|
+
this.next = this.now() + 60000;
|
|
246
|
+
const body = await json(response, signal, 2 * 1024 * 1024), after = await verifyBeatAPIAccess(grant, guards);
|
|
247
|
+
if (after.credit_balance !== before.credit_balance)
|
|
248
|
+
throw new SourceError('refused', 'BeatAPI free request changed the account balance; routing stopped');
|
|
249
|
+
if (body.model !== BEATAPI_MODEL)
|
|
250
|
+
throw new SourceError('upstream', 'BeatAPI returned an unverified free model identity');
|
|
251
|
+
const choice = obj(Array.isArray(body.choices) && body.choices.length === 1 ? body.choices[0] : undefined), message = obj(choice.message), usage = obj(body.usage);
|
|
252
|
+
if (message.refusal)
|
|
253
|
+
throw new SourceError('refused', 'BeatAPI refused the request');
|
|
254
|
+
if (!(message.content === undefined || message.content === null || typeof message.content === 'string') || !Number.isSafeInteger(usage.prompt_tokens) || Number(usage.prompt_tokens) < 0
|
|
255
|
+
|| !Number.isSafeInteger(usage.completion_tokens) || Number(usage.completion_tokens) < 0 || ['cost', 'total_cost', 'credits_charged'].some(key => key in usage && usage[key] !== 0))
|
|
256
|
+
throw new SourceError('upstream', 'BeatAPI returned an invalid completion or usage');
|
|
257
|
+
const calls = [], ids = new Set();
|
|
258
|
+
if (message.tool_calls !== undefined) {
|
|
259
|
+
if (!Array.isArray(message.tool_calls) || message.tool_calls.length > 16)
|
|
260
|
+
throw new SourceError('upstream', 'BeatAPI returned invalid function calls');
|
|
261
|
+
for (const raw of message.tool_calls) {
|
|
262
|
+
const c = obj(raw), fn = obj(c.function);
|
|
263
|
+
let args;
|
|
264
|
+
try {
|
|
265
|
+
args = JSON.parse(String(fn.arguments));
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
throw new SourceError('upstream', 'BeatAPI returned invalid function arguments');
|
|
269
|
+
}
|
|
270
|
+
if (c.type !== 'function' || typeof c.id !== 'string' || !c.id || ids.has(c.id) || request.messages.some(m => m.tool_calls?.some(old => old.id === c.id))
|
|
271
|
+
|| typeof fn.name !== 'string' || typeof fn.arguments !== 'string' || !validators.get(fn.name)?.(args) || !args || typeof args !== 'object' || Array.isArray(args))
|
|
272
|
+
throw new SourceError('upstream', 'BeatAPI returned invalid function calls');
|
|
273
|
+
ids.add(c.id);
|
|
274
|
+
calls.push({ id: c.id, type: 'function', function: { name: fn.name, arguments: fn.arguments } });
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (!message.content && !calls.length)
|
|
278
|
+
throw new SourceError('upstream', 'BeatAPI returned an empty completion');
|
|
279
|
+
this.next = this.now() + 60000;
|
|
280
|
+
return { text: typeof message.content === 'string' ? message.content : '', ...(calls.length ? { calls } : {}), inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens };
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
if (caller.aborted)
|
|
284
|
+
throw new SourceError('cancelled', 'BeatAPI request cancelled');
|
|
285
|
+
if (this.shutdown.signal.aborted)
|
|
286
|
+
throw new SourceError('cancelled', 'BeatAPI request cancelled during shutdown');
|
|
287
|
+
if (signal.aborted)
|
|
288
|
+
throw new SourceError('timeout', 'BeatAPI request timed out');
|
|
289
|
+
if (error instanceof SourceError) {
|
|
290
|
+
if (error.code === 'quota')
|
|
291
|
+
this.next = this.now() + (error.retryAfter ?? 60) * 1000;
|
|
292
|
+
throw error;
|
|
293
|
+
}
|
|
294
|
+
throw new SourceError('upstream', 'BeatAPI request failed');
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
async close() { this.shutdown.abort(); await Promise.allSettled([...this.pending]); }
|
|
298
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Owned child preload. The official CLI and its provider payloads stay intact.
|
|
2
|
+
// Only metadata crosses IPC; stdout remains untrusted model/CLI output.
|
|
3
|
+
const nonce = process.env.GRUNT_CLIXAD_NONCE;
|
|
4
|
+
const mode = process.argv[2];
|
|
5
|
+
const model = 'glm-5.3-flash', origin = 'https://clixad.onrender.com';
|
|
6
|
+
if (!process.send || !nonce || !/^[a-f0-9]{32}$/.test(nonce) || !['model', 'wallet', 'ask'].includes(mode ?? '') || process.argv.length !== 3)
|
|
7
|
+
throw new Error('Clixad child invocation rejected');
|
|
8
|
+
const send = (event, fields = {}) => process.send?.({ type: 'grunt-clixad', version: 1, nonce, event, ...fields });
|
|
9
|
+
const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
10
|
+
const numeric = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
11
|
+
function fail() {
|
|
12
|
+
send('guard');
|
|
13
|
+
process.exitCode = 73;
|
|
14
|
+
setTimeout(() => process.exit(73), 10).unref();
|
|
15
|
+
throw new Error('Clixad native guard rejected an unsupported action or response');
|
|
16
|
+
}
|
|
17
|
+
let prompt = '';
|
|
18
|
+
if (mode === 'ask') {
|
|
19
|
+
const chunks = [];
|
|
20
|
+
let bytes = 0;
|
|
21
|
+
for await (const chunk of process.stdin) {
|
|
22
|
+
const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
23
|
+
bytes += data.length;
|
|
24
|
+
if (bytes > 2 * 1024 * 1024)
|
|
25
|
+
fail();
|
|
26
|
+
chunks.push(data);
|
|
27
|
+
}
|
|
28
|
+
prompt = Buffer.concat(chunks).toString('utf8');
|
|
29
|
+
if (!prompt)
|
|
30
|
+
fail();
|
|
31
|
+
process.argv = [process.argv[0], process.argv[1], 'ask', prompt];
|
|
32
|
+
}
|
|
33
|
+
async function bounded(response, limit) {
|
|
34
|
+
if (!response.body || Number(response.headers.get('content-length')) > limit)
|
|
35
|
+
fail();
|
|
36
|
+
const reader = response.body.getReader(), chunks = [];
|
|
37
|
+
let bytes = 0;
|
|
38
|
+
try {
|
|
39
|
+
for (;;) {
|
|
40
|
+
const part = await reader.read();
|
|
41
|
+
if (part.done)
|
|
42
|
+
break;
|
|
43
|
+
bytes += part.value.byteLength;
|
|
44
|
+
if (bytes > limit)
|
|
45
|
+
fail();
|
|
46
|
+
chunks.push(part.value);
|
|
47
|
+
}
|
|
48
|
+
return object(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
void reader.cancel().catch(() => { });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function observeStream(response) {
|
|
55
|
+
if (!response.body)
|
|
56
|
+
fail();
|
|
57
|
+
const reader = response.body.getReader(), decoder = new TextDecoder();
|
|
58
|
+
let bytes = 0, buffer = '', done = false;
|
|
59
|
+
let usage, cost, returnedModel;
|
|
60
|
+
function line(value) {
|
|
61
|
+
if (!value.startsWith('data:'))
|
|
62
|
+
return;
|
|
63
|
+
const text = value.slice(5).trim();
|
|
64
|
+
if (!text)
|
|
65
|
+
return;
|
|
66
|
+
if (text === '[DONE]') {
|
|
67
|
+
done = true;
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (done)
|
|
71
|
+
fail();
|
|
72
|
+
const frame = object(JSON.parse(text));
|
|
73
|
+
if (frame.error)
|
|
74
|
+
fail();
|
|
75
|
+
if (frame.model !== undefined) {
|
|
76
|
+
if (frame.model !== model)
|
|
77
|
+
fail();
|
|
78
|
+
returnedModel = frame.model;
|
|
79
|
+
}
|
|
80
|
+
if (Array.isArray(frame.choices) && frame.choices.some(choice => {
|
|
81
|
+
const delta = object(object(choice).delta);
|
|
82
|
+
return ['tool_calls', 'function_call'].some(key => key in delta);
|
|
83
|
+
}))
|
|
84
|
+
fail();
|
|
85
|
+
if (frame.usage !== undefined) {
|
|
86
|
+
const raw = object(frame.usage), projected = { inputTokens: numeric(raw.prompt_tokens), outputTokens: numeric(raw.completion_tokens) };
|
|
87
|
+
if (projected.inputTokens === undefined || projected.outputTokens === undefined || (usage && JSON.stringify(usage) !== JSON.stringify(projected)))
|
|
88
|
+
fail();
|
|
89
|
+
usage = projected;
|
|
90
|
+
}
|
|
91
|
+
if (frame.clixad !== undefined) {
|
|
92
|
+
const raw = object(frame.clixad), projected = { free: raw.free, creditsCharged: numeric(raw.credits_charged), balance: numeric(raw.balance), creditsLeft: numeric(raw.free_credits_left) };
|
|
93
|
+
if (projected.free !== true || projected.creditsCharged !== 0 || projected.balance !== 0 || projected.creditsLeft === undefined
|
|
94
|
+
|| (cost && JSON.stringify(cost) !== JSON.stringify(projected)))
|
|
95
|
+
fail();
|
|
96
|
+
cost = projected;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
for (;;) {
|
|
101
|
+
const part = await reader.read();
|
|
102
|
+
if (part.done)
|
|
103
|
+
break;
|
|
104
|
+
bytes += part.value.byteLength;
|
|
105
|
+
if (bytes > 2 * 1024 * 1024)
|
|
106
|
+
fail();
|
|
107
|
+
buffer += decoder.decode(part.value, { stream: true });
|
|
108
|
+
if (Buffer.byteLength(buffer) > 131072)
|
|
109
|
+
fail();
|
|
110
|
+
let end;
|
|
111
|
+
while ((end = buffer.indexOf('\n')) >= 0) {
|
|
112
|
+
line(buffer.slice(0, end).replace(/\r$/, ''));
|
|
113
|
+
buffer = buffer.slice(end + 1);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
buffer += decoder.decode();
|
|
117
|
+
if (buffer.trim())
|
|
118
|
+
line(buffer.trim());
|
|
119
|
+
if (!done || !usage || !cost)
|
|
120
|
+
fail();
|
|
121
|
+
send('completion', { ...usage, ...cost, ...(returnedModel ? { returnedModel } : {}) });
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
void reader.cancel().catch(() => { });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const original = globalThis.fetch;
|
|
128
|
+
const counts = new Map();
|
|
129
|
+
globalThis.fetch = async function (input, init) {
|
|
130
|
+
const url = new URL(typeof input === 'string' || input instanceof URL ? String(input) : input.url);
|
|
131
|
+
if (url.origin !== origin || url.username || url.password || url.search || url.hash)
|
|
132
|
+
fail();
|
|
133
|
+
const method = String(init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();
|
|
134
|
+
const operation = mode === 'wallet' && method === 'GET' && url.pathname === '/v1/wallet' ? 'wallet'
|
|
135
|
+
: mode === 'wallet' && method === 'POST' && url.pathname === '/v1/streak/claim' ? 'streak'
|
|
136
|
+
: mode === 'ask' && method === 'POST' && url.pathname === '/v1/chat/completions' ? 'chat' : undefined;
|
|
137
|
+
if (!operation || counts.has(operation))
|
|
138
|
+
fail();
|
|
139
|
+
counts.set(operation, 1);
|
|
140
|
+
if (operation === 'chat') {
|
|
141
|
+
// Validate the CLI's actual dispatch immediately before its single POST.
|
|
142
|
+
// Never inspect, change, save or send authorization headers through IPC.
|
|
143
|
+
if (typeof init?.body !== 'string')
|
|
144
|
+
fail();
|
|
145
|
+
let body;
|
|
146
|
+
try {
|
|
147
|
+
body = object(JSON.parse(init.body));
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
fail();
|
|
151
|
+
}
|
|
152
|
+
const messages = body.messages;
|
|
153
|
+
if (body.model !== model || body.stream !== true || body.tools !== undefined || !Array.isArray(messages) || messages.length !== 1
|
|
154
|
+
|| object(messages[0]).role !== 'user' || object(messages[0]).content !== prompt
|
|
155
|
+
|| Object.keys(body).some(key => !['model', 'messages', 'stream', 'reasoning_effort'].includes(key)))
|
|
156
|
+
fail();
|
|
157
|
+
send('dispatch', { model });
|
|
158
|
+
}
|
|
159
|
+
// Redirect policy is a local transport guard. Native URL, body and headers
|
|
160
|
+
// are otherwise passed unchanged; no compressed retry or alternate route.
|
|
161
|
+
const response = await Reflect.apply(original, this, [input, { ...init, redirect: 'error' }]);
|
|
162
|
+
if (response.url && new URL(response.url).origin !== origin)
|
|
163
|
+
fail();
|
|
164
|
+
send('http', { operation, status: response.status });
|
|
165
|
+
if (response.ok && operation === 'wallet') {
|
|
166
|
+
const body = await bounded(response.clone(), 262144), free = object(body.free_tier);
|
|
167
|
+
send('wallet', { balance: numeric(body.balance), dailyCredits: numeric(free.daily_credits), creditsLeft: numeric(free.credits_left),
|
|
168
|
+
modelEligible: Array.isArray(free.models) && free.models.includes(model), turnsLeft: numeric(object(free.turns_left)[model]) });
|
|
169
|
+
}
|
|
170
|
+
if (response.ok && operation === 'chat')
|
|
171
|
+
void observeStream(response.clone()).catch(() => { try {
|
|
172
|
+
fail();
|
|
173
|
+
}
|
|
174
|
+
catch { /* The owned child terminates. */ } });
|
|
175
|
+
return response;
|
|
176
|
+
};
|
|
177
|
+
export {};
|