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.
@@ -0,0 +1,480 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, lstat, mkdir, mkdtemp, open, readdir, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { Ajv } from 'ajv';
7
+ import { readDataSharingConsent } from './data-sharing.js';
8
+ import { FreebuffTools } from './freebuff-tools.js';
9
+ import { SourceError } from './source.js';
10
+ import { openPerchACP, runPerchCommand, runPerchMemorySettings, verifyPerchCoreFiles } from './perch-process.js';
11
+ export { openPerchACP, runPerchCommand, runPerchMemorySettings } from './perch-process.js';
12
+ export const PERCH_VERSION = '2.4.132';
13
+ export const PERCH_MODEL_ALIAS = 'deepseek-flash-starter';
14
+ export const PERCH_MODEL_OPTION_ID = 'openrouter-deepseek-deepseek-v4-1-flash-crusoe';
15
+ export const PERCH_MODEL_ID = 'deepseek/deepseek-v4.1-flash';
16
+ export const PERCH_MODEL_LABEL = 'DeepSeek V4.1 Flash 1017 (Starter)';
17
+ export const PERCH_NPM_TARBALL_URL = 'https://registry.npmjs.org/perchai-cli/-/perchai-cli-2.4.132.tgz';
18
+ export const PERCH_NPM_INTEGRITY = 'sha512-eQJWzHXhlBGKho1yFwjBCLNi7ttl23NyCumRMCO5j/oT0oM7DkuJZeSVUxlKqyf5ntM9JeN9z5/Goe9vE+SLqw==';
19
+ export const PERCH_TARBALL_SHA256 = '01966bb687db6b2ac5a66540a41e2723291791b385f05cc06796e1c50f79f4cc';
20
+ export const PERCH_CORE_SHA256 = {
21
+ 'bin/perch': 'be23ce6d6bff5663a2fe005199e5090ce7fc0795cb1acf082cb42ac184471c8e',
22
+ 'dist/perch.mjs': '7802f39dd70cf1eace49a1bf0b44e632ed055be368f55dbde11c0866dffd1180',
23
+ 'package.json': 'a905a496431cd9c589b1c83a79a7fe00145e3e41466c84e73c15d3e863d02e34'
24
+ };
25
+ export const PERCH_RECEIPT_MAX_AGE_MS = 30 * 86400000;
26
+ export const PERCH_TIMEOUT_MS = 175000;
27
+ export const PERCH_MAX_OUTPUT_TOKENS = 4096;
28
+ // These public vendor prompts are inline rC in the pinned, hashed CLI bundle.
29
+ // They are NOT user SKILL.md files. Preflight guarantees gre(cwd).meta is null:
30
+ // mIe then passes no userSkills to zle, so user files cannot shadow these IDs.
31
+ export const PERCH_BUILTIN_SKILLS = ['about-perch', 'browser-operator', 'data-quality', 'diagrams', 'documents', 'github', 'pdf',
32
+ 'presentations', 'release', 'research', 'skill-creator', 'spreadsheets', 'wait-operator', 'workspace'];
33
+ const builtinSkills = new Set(PERCH_BUILTIN_SKILLS);
34
+ const directoryDefault = () => process.env.MILO_CONFIG_DIR || join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo');
35
+ const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
36
+ export function perchPaths(directory = directoryDefault()) {
37
+ const home = resolve(directory, 'perch'), binRoot = join(home, 'bin'), versionHome = join(binRoot, PERCH_VERSION), packageDirectory = join(versionHome, 'package');
38
+ return { home, binRoot, versionHome, package: packageDirectory, binary: join(packageDirectory, 'bin', 'perch'),
39
+ bundle: join(packageDirectory, 'dist', 'perch.mjs'), packageJSON: join(packageDirectory, 'package.json'),
40
+ auth: join(home, 'auth'), authFile: join(home, 'auth', 'cli-auth-session.json'), settings: join(home, 'settings'),
41
+ state: join(home, 'state'), grants: join(home, 'grants'), telemetry: join(home, 'telemetry'),
42
+ nativeHome: join(home, 'native-home'), consent: join(home, 'consent'), splash: join(home, 'splash'), background: join(home, 'background'),
43
+ work: join(home, 'work'), receipt: join(home, 'free-plan.json'), installReceipt: join(home, 'installation.json') };
44
+ }
45
+ /** HOME stays unchanged. Only documented native configuration paths are isolated. */
46
+ export function perchEnvironment(directory = directoryDefault(), requestDirectory) {
47
+ const p = perchPaths(directory), local = (name) => requestDirectory ? join(requestDirectory, name) : p[name];
48
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(?:perch_|aws_|azure_|google_|gcp_|openai_|openrouter_|anthropic_|grok_|deepseek_|mistral_|qianfan_|cloudflare_|cf_|fireworks_|coreweave_|together_|crusoe_|gemini_|vertex_|wandb_|kimi_|moonshot_|zai_|zhipu_|minimax_|modal_|bedrock_|ai_gateway_|hf_|huggingface_)/i.test(key) && !/^node_(?:options|path|compile_cache)$/i.test(key)
49
+ && !/^(?:SHELL|BASH_ENV|ENV|ZDOTDIR|LD_PRELOAD|DYLD_INSERT_LIBRARIES)$/i.test(key)
50
+ && !/(?:^|_)(?:api_key|auth_token|access_token|refresh_token|secret|secret_key|token)$/i.test(key)));
51
+ return { ...env, PERCH_HOME: local('nativeHome'), PERCH_CLI_AUTH_DIR: p.auth, PERCH_CLI_SETTINGS_DIR: local('settings'),
52
+ PERCH_CLI_STATE_DIR: local('state'), PERCH_CLI_GRANTS_DIR: local('grants'), PERCH_CLI_TELEMETRY_DIR: local('telemetry'),
53
+ PERCH_CLI_CONSENT_DIR: local('consent'), PERCH_CLI_SPLASH_DIR: local('splash'), PERCH_BACKGROUND_TASK_DIR: local('background'),
54
+ PERCH_CLI_HEAP_DIAG: 'off', PERCH_GIT_ATTRIBUTION: 'off' };
55
+ }
56
+ const eligibilityError = () => new SourceError('logged_out', 'Perch Starter verification is missing or expired; rerun usegrunt setup');
57
+ function receipt(value) {
58
+ const r = object(value), checked = typeof r.checkedAt === 'string' ? Date.parse(r.checkedAt) : NaN;
59
+ if (r.version !== 1 || r.plan !== 'Starter' || r.monthlyAllowancePT !== 20000 || r.dataProgramEnabled !== false || r.memoryUseEnabled !== false || r.memoryLearningEnabled !== false
60
+ || typeof r.email !== 'string' || r.email.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r.email)
61
+ || !Number.isFinite(checked) || checked > Date.now() + 60000 || Date.now() - checked > PERCH_RECEIPT_MAX_AGE_MS)
62
+ throw eligibilityError();
63
+ return { version: 1, plan: 'Starter', email: r.email.toLowerCase(), monthlyAllowancePT: 20000, dataProgramEnabled: false, memoryUseEnabled: false, memoryLearningEnabled: false, checkedAt: r.checkedAt };
64
+ }
65
+ function installation(value) {
66
+ const r = object(value);
67
+ if (r.version !== 1 || r.packageVersion !== PERCH_VERSION || r.tarballSha256 !== PERCH_TARBALL_SHA256 || r.npmIntegrity !== PERCH_NPM_INTEGRITY)
68
+ throw new SourceError('not_installed', 'Perch pinned installation receipt is missing');
69
+ return { version: 1, packageVersion: PERCH_VERSION, tarballSha256: PERCH_TARBALL_SHA256, npmIntegrity: PERCH_NPM_INTEGRITY };
70
+ }
71
+ export async function perchPrivateDirectory(path, create = false) {
72
+ if (create)
73
+ await mkdir(path, { recursive: true, mode: 0o700 });
74
+ const st = await lstat(path);
75
+ if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid?.() || (st.mode & 0o077))
76
+ throw eligibilityError();
77
+ }
78
+ async function privateJSON(path, limit = 4096) {
79
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
80
+ try {
81
+ const st = await file.stat();
82
+ if (!st.isFile() || st.uid !== process.getuid?.() || (st.mode & 0o777) !== 0o600 || st.size > limit)
83
+ throw eligibilityError();
84
+ return JSON.parse(await file.readFile('utf8'));
85
+ }
86
+ finally {
87
+ await file.close();
88
+ }
89
+ }
90
+ async function writeReceipt(directory, path, value) {
91
+ const p = perchPaths(directory);
92
+ await perchPrivateDirectory(p.home, true);
93
+ const temporary = join(p.home, `.receipt-${randomUUID()}`);
94
+ try {
95
+ await writeFile(temporary, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
96
+ await rename(temporary, path);
97
+ }
98
+ finally {
99
+ await rm(temporary, { force: true });
100
+ }
101
+ }
102
+ export async function preparePerchDirectories(directory) {
103
+ const p = perchPaths(directory);
104
+ await perchPrivateDirectory(resolve(directory), true);
105
+ await perchPrivateDirectory(p.home, true);
106
+ for (const path of [p.binRoot, p.versionHome, p.auth, p.settings, p.state, p.grants, p.telemetry, p.nativeHome, p.consent, p.splash, p.background, p.work])
107
+ await perchPrivateDirectory(path, true);
108
+ return p;
109
+ }
110
+ export async function readPerchFreePlanReceipt(directory = directoryDefault()) { return receipt(await privateJSON(perchPaths(directory).receipt)); }
111
+ export async function writePerchFreePlanReceipt(directory, value) { await writeReceipt(directory, perchPaths(directory).receipt, receipt(value)); }
112
+ export async function readPerchInstallReceipt(directory = directoryDefault()) { return installation(await privateJSON(perchPaths(directory).installReceipt)); }
113
+ export async function writePerchInstallReceipt(directory) {
114
+ await verifyPerchCore(directory);
115
+ await writeReceipt(directory, perchPaths(directory).installReceipt, installation({ version: 1, packageVersion: PERCH_VERSION, tarballSha256: PERCH_TARBALL_SHA256, npmIntegrity: PERCH_NPM_INTEGRITY }));
116
+ }
117
+ export async function verifyPerchCore(directory, signal = AbortSignal.timeout(10000)) {
118
+ const p = perchPaths(directory);
119
+ for (const path of [p.home, p.binRoot, p.versionHome])
120
+ await perchPrivateDirectory(path);
121
+ const pkg = await lstat(p.package);
122
+ if (!pkg.isDirectory() || pkg.isSymbolicLink() || pkg.uid !== process.getuid?.() || (pkg.mode & 0o022))
123
+ throw new SourceError('not_installed', 'Perch package directory is unsafe');
124
+ await verifyPerchCoreFiles(p.package, PERCH_CORE_SHA256, signal);
125
+ await access(p.binary, constants.X_OK);
126
+ }
127
+ export async function verifyPerchInstallation(directory, signal = AbortSignal.timeout(10000)) {
128
+ await readPerchInstallReceipt(directory);
129
+ await verifyPerchCore(directory, signal);
130
+ }
131
+ export async function assertPerchPrivateAuth(directory) {
132
+ const p = perchPaths(directory);
133
+ await perchPrivateDirectory(p.auth);
134
+ const st = await lstat(p.authFile);
135
+ if (!st.isFile() || st.isSymbolicLink() || st.uid !== process.getuid?.() || (st.mode & 0o777) !== 0o600 || st.size < 1 || st.size > 65536)
136
+ throw eligibilityError();
137
+ }
138
+ /** No global instructions may make the native empty-workspace metadata nonempty. Never modify those files. */
139
+ export async function verifyPerchStartupIsolation(work, personalHome = homedir()) {
140
+ const projectMetadata = join(resolve(work), '.perch');
141
+ const forbidden = [projectMetadata, join(personalHome, 'Documents', 'Perch', 'PERCH.md'), join(personalHome, '.perch', 'PERCH.md'),
142
+ join(personalHome, '.perch', 'agents'), join(personalHome, '.perch', 'skills'), join(personalHome, '.perch', 'plugins')];
143
+ let current = resolve(work);
144
+ while (current !== dirname(current)) {
145
+ forbidden.push(...['.git', 'AGENTS.md', 'CLAUDE.md', 'PERCH.md', '.perch/PERCH.md', '.perch/agents', '.claude/agents'].map(name => join(current, name)));
146
+ if (current === resolve(personalHome))
147
+ break;
148
+ current = dirname(current);
149
+ }
150
+ for (const path of new Set(forbidden)) {
151
+ try {
152
+ const st = await lstat(path);
153
+ if (path !== projectMetadata && !path.endsWith('/.git') && st.isDirectory() && !st.isSymbolicLink() && !(await readdir(path)).length)
154
+ continue;
155
+ throw new SourceError('refused', 'Perch has external startup instructions or configuration; this isolated route is unavailable');
156
+ }
157
+ catch (error) {
158
+ if (error.code !== 'ENOENT')
159
+ throw error;
160
+ }
161
+ }
162
+ }
163
+ const defaultProcesses = { command: runPerchCommand, acp: openPerchACP, memory: runPerchMemorySettings };
164
+ async function requestWorkspace(directory) {
165
+ const p = perchPaths(directory);
166
+ await perchPrivateDirectory(p.work);
167
+ const request = await mkdtemp(join(p.work, 'request-'));
168
+ try {
169
+ for (const name of ['workspace', 'settings', 'state', 'grants', 'telemetry', 'nativeHome', 'consent', 'splash', 'background'])
170
+ await perchPrivateDirectory(join(request, name), true);
171
+ await writeFile(join(request, 'settings', 'cli-settings.json'), JSON.stringify({ version: 1, language: 'en', chatMode: 'ask',
172
+ personaId: 'saffron', permissionMode: 'plan', manualModelOptionId: PERCH_MODEL_OPTION_ID, cliLocalTools: false, roostChoice: 'standard' }), { flag: 'wx', mode: 0o600 });
173
+ return { request, workspace: join(request, 'workspace'), env: perchEnvironment(directory, request) };
174
+ }
175
+ catch (error) {
176
+ await rm(request, { recursive: true, force: true });
177
+ throw error;
178
+ }
179
+ }
180
+ function parseIdentity(result) {
181
+ const lines = result.stdout.replaceAll('\r', '').trim().split('\n');
182
+ if (result.code === 2 && lines.some(line => line === `Perch CLI ${PERCH_VERSION} · Not signed in`))
183
+ return null;
184
+ const match = lines[0]?.match(/^Perch CLI ([0-9.]+) · Signed in as ([^\s@]+@[^\s@]+\.[^\s@]+) · (https:\/\/[^\s]+)$/);
185
+ if (result.code !== 0 || !match || match[1] !== PERCH_VERSION)
186
+ throw eligibilityError();
187
+ let url;
188
+ try {
189
+ url = new URL(match[3]);
190
+ }
191
+ catch {
192
+ throw eligibilityError();
193
+ }
194
+ if (url.protocol !== 'https:' || !['app.perchai.app', 'chat.perchai.app'].includes(url.hostname) || url.username || url.password || url.port || url.pathname !== '/' || url.search || url.hash)
195
+ throw eligibilityError();
196
+ return { email: match[2].toLowerCase() };
197
+ }
198
+ async function openSession(directory, request, signal, processes) {
199
+ await verifyPerchStartupIsolation(request.workspace);
200
+ const p = perchPaths(directory), options = { cwd: request.workspace, env: request.env, signal, maxOutputBytes: 2 * 1024 * 1024, timeoutMs: PERCH_TIMEOUT_MS };
201
+ const acp = await processes.acp(p.binary, options);
202
+ try {
203
+ const initialized = object(await acp.request('initialize', { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, clientInfo: { name: 'grunt', version: 'perch-adapter-v1' } }));
204
+ const agent = object(initialized.agentInfo);
205
+ if (initialized.protocolVersion !== 1 || agent.name !== 'perch' || agent.version !== PERCH_VERSION)
206
+ throw new SourceError('refused', 'Perch did not acknowledge the pinned native client');
207
+ const session = object(await acp.request('session/new', { cwd: request.workspace, mcpServers: [] }));
208
+ if (typeof session.sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(session.sessionId) || object(session.modes).currentModeId !== 'plan')
209
+ throw new SourceError('refused', 'Perch did not acknowledge isolated native permissions');
210
+ // ACP's official authentication check refreshes an expired native access token.
211
+ // `status` alone does not refresh it, so identity must be read after session/new.
212
+ const identity = parseIdentity(await processes.command(process.execPath, [p.binary, 'status'], { ...options, maxOutputBytes: 65536, timeoutMs: 10000 }));
213
+ signal.throwIfAborted();
214
+ return { acp, sessionId: session.sessionId, identity };
215
+ }
216
+ catch (error) {
217
+ await acp.close();
218
+ throw error;
219
+ }
220
+ }
221
+ /** Nonbillable official native interfaces; the authentication file remains entirely CLI-owned. */
222
+ export async function verifyPerchIdentity(directory, signal = AbortSignal.timeout(30000), processes = defaultProcesses) {
223
+ await verifyPerchInstallation(directory, signal);
224
+ try {
225
+ await assertPerchPrivateAuth(directory);
226
+ }
227
+ catch (error) {
228
+ if (error.code === 'ENOENT')
229
+ return null;
230
+ throw error;
231
+ }
232
+ const request = await requestWorkspace(directory);
233
+ let session;
234
+ try {
235
+ session = await openSession(directory, request, signal, processes);
236
+ return session.identity;
237
+ }
238
+ catch (error) {
239
+ if (error instanceof SourceError && error.code === 'logged_out')
240
+ return null;
241
+ throw error;
242
+ }
243
+ finally {
244
+ try {
245
+ await session?.acp.close().catch(() => { });
246
+ }
247
+ finally {
248
+ await rm(request.request, { recursive: true, force: true }).catch(() => { });
249
+ }
250
+ }
251
+ }
252
+ async function memorySettings(directory, signal, processes, configure) {
253
+ await verifyPerchInstallation(directory, signal);
254
+ await assertPerchPrivateAuth(directory);
255
+ const request = await requestWorkspace(directory);
256
+ try {
257
+ await verifyPerchStartupIsolation(request.workspace);
258
+ return await (processes.memory ?? runPerchMemorySettings)(perchPaths(directory).binary, { cwd: request.workspace, env: request.env, signal, timeoutMs: 30000, maxOutputBytes: 65536 }, configure);
259
+ }
260
+ finally {
261
+ await rm(request.request, { recursive: true, force: true }).catch(() => { });
262
+ }
263
+ }
264
+ /** Read current native account memory switches without generating or modifying account preferences. */
265
+ export async function verifyPerchMemory(directory, signal = AbortSignal.timeout(30000), processes = defaultProcesses) {
266
+ return memorySettings(directory, signal, processes, false);
267
+ }
268
+ /** Setup-only: save both supported account memory switches Off, then read them back. */
269
+ export async function configurePerchMemory(directory, signal = AbortSignal.timeout(30000), processes = defaultProcesses) {
270
+ return memorySettings(directory, signal, processes, true);
271
+ }
272
+ async function readSnapshot(request, sessionId, signal) {
273
+ const state = join(request, 'state');
274
+ for (let attempt = 0; attempt < 25; attempt++) {
275
+ signal.throwIfAborted();
276
+ for (const item of await readdir(state, { withFileTypes: true })) {
277
+ if (!item.isDirectory() || item.isSymbolicLink())
278
+ throw new SourceError('upstream', 'Perch private state is unsafe');
279
+ const folder = join(state, item.name);
280
+ await perchPrivateDirectory(folder);
281
+ try {
282
+ const saved = object(await privateJSON(join(folder, `${sessionId}.json`), 8 * 1024 * 1024)), snapshot = object(saved.contextSnapshot);
283
+ if (saved.threadId !== sessionId)
284
+ throw new SourceError('upstream', 'Perch returned uncorrelated private state');
285
+ if (snapshot.turnApiUsage)
286
+ return snapshot;
287
+ }
288
+ catch (error) {
289
+ if (error.code !== 'ENOENT')
290
+ throw error;
291
+ }
292
+ }
293
+ await new Promise((resolveWait, reject) => {
294
+ const abort = () => { clearTimeout(timer); signal.removeEventListener('abort', abort); reject(signal.reason); };
295
+ const timer = setTimeout(() => { signal.removeEventListener('abort', abort); resolveWait(); }, 100);
296
+ signal.addEventListener('abort', abort, { once: true });
297
+ if (signal.aborted)
298
+ abort();
299
+ });
300
+ }
301
+ throw new SourceError('upstream', 'Perch returned no authoritative native usage');
302
+ }
303
+ function snapshotUsage(snapshot, limit) {
304
+ const sections = object(snapshot.sectionBreakdown), tools = snapshot.toolCallsByType;
305
+ if (snapshot.modelId !== PERCH_MODEL_ID || snapshot.modelLabel !== PERCH_MODEL_LABEL || snapshot.cliLocalTools !== false
306
+ || !Array.isArray(snapshot.selectedSkills) || snapshot.selectedSkills.some(skill => typeof skill !== 'string' || !builtinSkills.has(skill))
307
+ || new Set(snapshot.selectedSkills).size !== snapshot.selectedSkills.length || !Array.isArray(tools) || tools.length
308
+ || object(sections.project_memory).chars !== 0 || object(sections.permanent_memory).chars !== 0
309
+ || snapshot.compacted !== false || snapshot.truncated !== false || !Number.isSafeInteger(snapshot.contextLimitTokens) || Number(snapshot.contextLimitTokens) < 200000) {
310
+ throw new SourceError('refused', 'Perch returned an unverified model, native action, or external context');
311
+ }
312
+ const usage = object(snapshot.turnApiUsage), keys = ['inputTokens', 'outputTokens', 'totalTokens'];
313
+ if (keys.some(key => !Number.isSafeInteger(usage[key]) || Number(usage[key]) < 0)
314
+ || (usage.cacheReadInputTokens !== undefined && (!Number.isSafeInteger(usage.cacheReadInputTokens) || Number(usage.cacheReadInputTokens) < 0)))
315
+ throw new SourceError('upstream', 'Perch returned invalid native usage');
316
+ const inputTokens = Number(usage.inputTokens) + Number(usage.cacheReadInputTokens ?? 0), outputTokens = Number(usage.outputTokens);
317
+ if (!Number.isSafeInteger(inputTokens) || inputTokens < 1 || outputTokens < 1 || outputTokens > limit || usage.totalTokens !== inputTokens + outputTokens)
318
+ throw new SourceError('upstream', 'Perch returned invalid or over-budget native usage');
319
+ return { inputTokens, outputTokens };
320
+ }
321
+ function validatedBridge(request) {
322
+ try {
323
+ const messages = [];
324
+ for (const message of request.messages) {
325
+ const previous = messages.at(-1);
326
+ if (message.role === 'assistant' && message.content === '' && message.tool_calls?.length && !message.tool_call_id && previous?.role === 'assistant' && previous.content === '' && previous.tool_calls?.length && !previous.tool_call_id) {
327
+ previous.tool_calls = [...previous.tool_calls, ...message.tool_calls];
328
+ }
329
+ else
330
+ messages.push({ ...message });
331
+ }
332
+ const normalized = { ...request, messages }, ajv = new Ajv({ strict: true, strictTypes: false, strictTuples: false, validateFormats: true, addUsedSchema: false });
333
+ for (const tool of request.tools)
334
+ ajv.compile(object(tool.function).parameters);
335
+ return new FreebuffTools(normalized);
336
+ }
337
+ catch {
338
+ throw new SourceError('refused', 'Perch rejected unsupported function definitions or an invalid tool conversation');
339
+ }
340
+ }
341
+ function outputBudget(value) {
342
+ if (value === undefined)
343
+ return PERCH_MAX_OUTPUT_TOKENS;
344
+ if (!Number.isSafeInteger(value) || value < 1)
345
+ throw new SourceError('refused', 'Perch requires a positive integer output budget');
346
+ return Math.min(value, PERCH_MAX_OUTPUT_TOKENS);
347
+ }
348
+ export class Perch {
349
+ options;
350
+ id = 'perch';
351
+ supportsFunctionTools = true;
352
+ shutdown = new AbortController();
353
+ pending = new Set();
354
+ busy = false;
355
+ constructor(options = {}) {
356
+ this.options = options;
357
+ }
358
+ get directory() { return this.options.directory ?? directoryDefault(); }
359
+ get processes() { return this.options.processes ?? defaultProcesses; }
360
+ async track(task) { this.pending.add(task); try {
361
+ return await task;
362
+ }
363
+ finally {
364
+ this.pending.delete(task);
365
+ } }
366
+ async ready(signal) {
367
+ signal.throwIfAborted();
368
+ if (!['linux', 'darwin'].includes(process.platform))
369
+ throw new SourceError('not_installed', 'Perch requires the vetted Linux or macOS CLI');
370
+ if (!(await readDataSharingConsent(this.directory, ['perch'])).includes('perch'))
371
+ throw new SourceError('refused', 'Perch data sharing is not approved; rerun usegrunt setup');
372
+ await verifyPerchInstallation(this.directory, signal);
373
+ await assertPerchPrivateAuth(this.directory);
374
+ await verifyPerchStartupIsolation(perchPaths(this.directory).work);
375
+ return readPerchFreePlanReceipt(this.directory);
376
+ }
377
+ async available() { return this.track((async () => { try {
378
+ await this.ready(AbortSignal.any([this.shutdown.signal, AbortSignal.timeout(15000)]));
379
+ return !this.shutdown.signal.aborted && !this.busy;
380
+ }
381
+ catch {
382
+ return false;
383
+ } })()); }
384
+ async healthCheck() {
385
+ return this.track((async () => {
386
+ try {
387
+ const signal = AbortSignal.any([this.shutdown.signal, AbortSignal.timeout(30000)]), r = await this.ready(signal);
388
+ return (await verifyPerchIdentity(this.directory, signal, this.processes))?.email === r.email
389
+ && (await verifyPerchMemory(this.directory, signal, this.processes)).email === r.email;
390
+ }
391
+ catch {
392
+ return false;
393
+ }
394
+ })());
395
+ }
396
+ async complete(request, caller) { return this.track(this.completeOnce(request, caller)); }
397
+ async completeOnce(request, caller) {
398
+ if (this.busy)
399
+ throw new SourceError('quota', 'Perch is serving another request; use another free source', 1);
400
+ this.busy = true;
401
+ const signal = AbortSignal.any([caller, this.shutdown.signal, AbortSignal.timeout(Math.min(this.options.timeout ?? PERCH_TIMEOUT_MS, PERCH_TIMEOUT_MS))]);
402
+ let workspace, session, inferenceStarted = false;
403
+ try {
404
+ signal.throwIfAborted();
405
+ if (request.imageInput)
406
+ throw new SourceError('refused', 'Perch supports text through this isolated route');
407
+ const limit = outputBudget(request.maxTokens), bridge = validatedBridge(request);
408
+ const lines = bridge.prompt().split('\n'), payload = lines.pop();
409
+ // Change only our adapter instructions. The caller's JSON payload stays byte-for-byte intact.
410
+ const prompt = `This is a Grunt caller request using the account owner's official Perch CLI. Keep total output, including the JSON envelope, below ${limit} tokens.\n`
411
+ + lines.map(line => line.replaceAll('Pi', 'Grunt caller').replaceAll('Freebuff', 'Perch')).join('\n') + '\n' + payload;
412
+ if (Buffer.byteLength(prompt) > 2 * 1024 * 1024)
413
+ throw new SourceError('refused', 'Perch prompt exceeds the supported size');
414
+ const r = await this.ready(signal);
415
+ if ((await verifyPerchMemory(this.directory, signal, this.processes)).email !== r.email)
416
+ throw eligibilityError();
417
+ workspace = await requestWorkspace(this.directory);
418
+ session = await openSession(this.directory, workspace, signal, this.processes);
419
+ if (!session.identity || session.identity.email !== r.email)
420
+ throw eligibilityError();
421
+ inferenceStarted = true;
422
+ const result = object(await session.acp.request('session/prompt', { sessionId: session.sessionId, prompt: [{ type: 'text', text: prompt }] }));
423
+ signal.throwIfAborted();
424
+ if (result.stopReason !== 'end_turn')
425
+ throw new SourceError('upstream', 'Perch did not return a complete response');
426
+ let text = '';
427
+ for (const notification of session.acp.notifications) {
428
+ const params = object(notification.params), update = object(params.update), content = object(update.content);
429
+ if (params.sessionId !== session.sessionId)
430
+ throw new SourceError('upstream', 'Perch returned an uncorrelated session update');
431
+ if (update.sessionUpdate === 'tool_call' || update.sessionUpdate === 'tool_call_update')
432
+ throw new SourceError('refused', 'Perch attempted an unexpected native action');
433
+ if (update.sessionUpdate === 'agent_message_chunk') {
434
+ if (content.type !== 'text' || typeof content.text !== 'string')
435
+ throw new SourceError('refused', 'Perch returned unsupported content');
436
+ text += content.text;
437
+ if (Buffer.byteLength(text) > 65536)
438
+ throw new SourceError('upstream', 'Perch completion exceeded the supported size');
439
+ }
440
+ }
441
+ const usage = snapshotUsage(await readSnapshot(workspace.request, session.sessionId, signal), limit);
442
+ // The CLI has no hard upstream output-token option. This validates returned
443
+ // usage after generation; monthly allowance can already have been consumed.
444
+ // No repair generation is attempted, so the caller budget is cumulative.
445
+ try {
446
+ const completion = bridge.parse(text);
447
+ if (!completion.text.trim() && !completion.calls?.length)
448
+ throw new Error('Empty answer');
449
+ return { ...completion, ...usage };
450
+ }
451
+ catch {
452
+ throw new SourceError('upstream', 'Perch returned an invalid caller tool envelope');
453
+ }
454
+ }
455
+ catch (error) {
456
+ if (!caller.aborted && !this.shutdown.signal.aborted && !signal.aborted && error instanceof SourceError && (error.code === 'logged_out' || (inferenceStarted && error.code === 'refused')))
457
+ await rm(perchPaths(this.directory).receipt, { force: true }).catch(() => { });
458
+ if (caller.aborted)
459
+ throw new SourceError('cancelled', 'Perch request cancelled');
460
+ if (this.shutdown.signal.aborted)
461
+ throw new SourceError('cancelled', 'Perch stopped during shutdown');
462
+ if (signal.aborted)
463
+ throw new SourceError('timeout', 'Perch request timed out');
464
+ if (error instanceof SourceError)
465
+ throw error;
466
+ throw new SourceError('upstream', 'Perch request failed; rerun usegrunt setup if native access needs repair');
467
+ }
468
+ finally {
469
+ try {
470
+ await session?.acp.close().catch(() => { });
471
+ }
472
+ finally {
473
+ if (workspace)
474
+ await rm(workspace.request, { recursive: true, force: true }).catch(() => { });
475
+ this.busy = false;
476
+ }
477
+ }
478
+ }
479
+ async close() { this.shutdown.abort(); await Promise.allSettled([...this.pending]); }
480
+ }
@@ -0,0 +1,109 @@
1
+ import { rm } from 'node:fs/promises';
2
+ import { DATA_SHARING_POLICIES, readDataSharingConsent } from './data-sharing.js';
3
+ import { POLLINATIONS_MODEL, pollinationsGrantPath, readPollinationsGrant, verifyPollinationsAccess, writePollinationsGrant } from './pollinations.js';
4
+ const failure = () => new Error('Pollinations free signup or key guard verification did not complete; rerun usegrunt setup');
5
+ const foregroundNeeded = () => new Error('Pollinations needs foreground setup; run usegrunt setup to verify or reconnect access');
6
+ async function bounded(operation, signal) {
7
+ let aborted;
8
+ try {
9
+ return await Promise.race([Promise.resolve().then(() => {
10
+ if (signal.aborted)
11
+ throw failure();
12
+ return operation();
13
+ }), new Promise((_resolve, reject) => {
14
+ aborted = () => reject(failure());
15
+ signal.addEventListener('abort', aborted, { once: true });
16
+ if (signal.aborted)
17
+ aborted();
18
+ })]);
19
+ }
20
+ catch {
21
+ throw failure();
22
+ }
23
+ finally {
24
+ if (aborted)
25
+ signal.removeEventListener('abort', aborted);
26
+ }
27
+ }
28
+ const eligible = (credential) => credential.service?.trim().toLowerCase() === 'pollinations'
29
+ // Squire's egress grant selects its upstream from the first allowed host.
30
+ // A matching service label alone cannot bind an opaque grant to this API.
31
+ && Array.isArray(credential.allowed_hosts) && credential.allowed_hosts[0] === 'gen.pollinations.ai'
32
+ // Summary metadata exposes auth_strategy, not the capture-time auth_shape.
33
+ // Older summaries may leave it unset; reject every explicit non-key strategy.
34
+ && (credential.auth_strategy == null || credential.auth_strategy === 'api_key')
35
+ && Array.isArray(credential.field_names)
36
+ && credential.field_names.some(field => typeof field === 'string' && /^(?:pollinations)?(?:api)?(?:key|token|secret|apitoken|accesstoken)$/.test(field.toLowerCase().replace(/[^a-z0-9]/g, '')));
37
+ const owned = (credential) => (credential.label ?? credential.name)?.trim().toLowerCase() === 'grunt-free-pollinations';
38
+ /** All secrets stay in Squire's vault or the private backend grant file. */
39
+ export async function setupPollinations(options) {
40
+ if (options.background) {
41
+ const signal = AbortSignal.any([...(options.signal ? [options.signal] : []), AbortSignal.timeout(10000)]);
42
+ try {
43
+ if (signal.aborted)
44
+ throw foregroundNeeded();
45
+ const approved = await bounded(() => readDataSharingConsent(options.directory, ['pollinations']), signal);
46
+ if (!approved.includes('pollinations') || (options.dataSharingApproved && !options.dataSharingApproved.includes('pollinations')))
47
+ throw foregroundNeeded();
48
+ const saved = await bounded(() => readPollinationsGrant(options.directory), signal);
49
+ await bounded(() => verifyPollinationsAccess(saved, { signal, ...(options.fetcher ? { fetcher: options.fetcher } : {}) }), signal);
50
+ return;
51
+ }
52
+ catch {
53
+ throw foregroundNeeded();
54
+ }
55
+ }
56
+ const approved = [...new Set([...(options.dataSharingApproved ?? []), ...await readDataSharingConsent(options.directory, DATA_SHARING_POLICIES.map(policy => policy.provider))])];
57
+ if (!approved.includes('pollinations'))
58
+ throw new Error('Pollinations data sharing requires the grouped setup approval');
59
+ if (options.signal?.aborted)
60
+ throw failure();
61
+ options.squire.approveDataSharing?.(approved);
62
+ const deadline = new AbortController();
63
+ const timeout = setTimeout(() => deadline.abort(), 600000);
64
+ const signal = options.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signal;
65
+ const guards = { signal, ...(options.fetcher ? { fetcher: options.fetcher } : {}) };
66
+ const invalidate = () => rm(pollinationsGrantPath(options.directory), { force: true });
67
+ try {
68
+ try {
69
+ const saved = await bounded(() => readPollinationsGrant(options.directory), signal);
70
+ await bounded(() => verifyPollinationsAccess(saved, guards), signal);
71
+ options.notify?.('Pollinations: existing zero-budget free community GLM access verified');
72
+ return;
73
+ }
74
+ catch {
75
+ if (signal.aborted)
76
+ throw failure();
77
+ }
78
+ // A failed fresh verification must never leave an older receipt usable.
79
+ await invalidate();
80
+ const before = await bounded(() => options.squire.credentials.list(), signal);
81
+ const references = new Set(before.filter(eligible).map(credential => credential.reference));
82
+ await bounded(() => options.squire.signup('pollinations', 'https://enter.pollinations.ai/keys', `Use the personal Google identity already connected to Squire for Pollinations, or reuse the same existing account. GitHub OAuth is also permitted for that same user's account if already linked; never switch identities or create an extra account. Use only free access: no card, payment method, purchased Pollen, subscription, paid wallet funds, purchases or top-ups. Stop if these free-account conditions cannot be verified; do not remove billing or modify an unrelated key. Reuse the Grunt-owned secret key named grunt-free-pollinations where available, otherwise create that one key. Its Pollen budget must be exactly 0 (hard zero, not blank/unlimited), Quest Pollen Only must be enabled, and account permissions must be usage only: no profile, keys, model management, agents or other account permissions. Prefer the exact model allowlist ${POLLINATIONS_MODEL} only if the normal dashboard offers an individual model selector. If it only offers categories, keep models unrestricted (null); do not choose a category or use CLI/API key self-edit. Grunt separately enforces the fixed singleton free route and server zero-budget guards. Do not enable default model fallback, edit or rotate an unrelated key, reset a key, or buy/claim paid credits. The small ordinary first-key Quest reward is allowed. Capture or reuse this key directly in this user's Squire vault under service pollinations, label grunt-free-pollinations, api_hosts ["gen.pollinations.ai"], auth_shape bearer. Use operate_extract for a new capture; never return or display the key in chat. Confirm saved key settings and free billing state before finishing. The user approved this provider's community/upstream data sharing in the grouped setup prompt; accept only required disclosures. Leave optional marketing off. Stop on refusal and report human CAPTCHA, phone, passkey or email verification for browser handoff; do not bypass it.`), signal);
83
+ // BrowserSquire invalidates credential metadata after a completed signup;
84
+ // this second list therefore includes a newly captured Grunt key.
85
+ const credentials = (await bounded(() => options.squire.credentials.list(), signal)).filter(eligible);
86
+ const credential = credentials.find(item => !references.has(item.reference)) ?? credentials.find(owned) ?? credentials[0];
87
+ if (!credential)
88
+ throw failure();
89
+ const grant = await bounded(() => options.squire.credentials.grant(credential.reference), signal);
90
+ await bounded(() => verifyPollinationsAccess(grant, guards), signal);
91
+ if (signal.aborted)
92
+ throw failure();
93
+ await writePollinationsGrant({
94
+ version: 1, ...grant, upstream_origin: 'https://gen.pollinations.ai', model: POLLINATIONS_MODEL,
95
+ verified_at: new Date().toISOString(), free_account_verified: true,
96
+ key_zero_budget_verified: true, quest_pollen_only: true
97
+ }, options.directory);
98
+ if (signal.aborted)
99
+ throw failure();
100
+ options.notify?.('Pollinations: zero-budget Quest-only free community GLM access connected through Squire');
101
+ }
102
+ catch {
103
+ await invalidate().catch(() => { });
104
+ throw failure();
105
+ }
106
+ finally {
107
+ clearTimeout(timeout);
108
+ }
109
+ }