usegrunt 0.5.0 → 0.6.0

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,164 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomInt } from 'node:crypto';
3
+ import { constants } from 'node:fs';
4
+ import { access, copyFile, mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';
5
+ import { homedir, tmpdir } from 'node:os';
6
+ import { delimiter, dirname, join } from 'node:path';
7
+ // Writes a whole config file only when its text changes, after copying the old
8
+ // file aside. Repeated setup runs therefore leave files and backups untouched.
9
+ export async function writeConfig(path, text, mode = 0o600) {
10
+ let old;
11
+ try {
12
+ old = await readFile(path, 'utf8');
13
+ }
14
+ catch (error) {
15
+ if (error.code !== 'ENOENT')
16
+ throw error;
17
+ }
18
+ if (old === text)
19
+ return { changed: false };
20
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
21
+ let backup;
22
+ if (old !== undefined) {
23
+ backup = `${path}.grunt-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`;
24
+ await copyFile(path, backup, constants.COPYFILE_EXCL);
25
+ }
26
+ const temporary = `${path}.${process.pid}.tmp`;
27
+ try {
28
+ await writeFile(temporary, text, { mode, flag: 'wx' });
29
+ await rename(temporary, path);
30
+ }
31
+ finally {
32
+ await rm(temporary, { force: true });
33
+ }
34
+ return { changed: true, backup };
35
+ }
36
+ const objectOrEmpty = (value, what) => {
37
+ if (value === undefined)
38
+ return {};
39
+ if (!value || typeof value !== 'object' || Array.isArray(value))
40
+ throw new Error(`Invalid ${what}`);
41
+ return value;
42
+ };
43
+ async function readJson(path, what) {
44
+ try {
45
+ return objectOrEmpty(JSON.parse(await readFile(path, 'utf8')), what);
46
+ }
47
+ catch (error) {
48
+ if (error.code === 'ENOENT')
49
+ return {};
50
+ throw new Error(`Cannot read ${what}; repair it before retrying setup`, { cause: error });
51
+ }
52
+ }
53
+ export async function configurePi(port = 8788) {
54
+ const path = join(process.env.PI_CODING_AGENT_DIR || join(homedir(), '.pi', 'agent'), 'models.json');
55
+ const saved = await readJson(path, 'Pi models config');
56
+ const providers = objectOrEmpty(saved.providers, 'Pi models config');
57
+ providers.grunt = { baseUrl: `http://127.0.0.1:${port}/v1`, api: 'openai-completions', apiKey: 'local',
58
+ models: [{ id: 'grunt', name: 'grunt', reasoning: false, input: ['text'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 128000, maxTokens: 4096 }] };
59
+ return writeConfig(path, JSON.stringify({ ...saved, providers }, null, 2) + '\n');
60
+ }
61
+ // Codex layers $CODEX_HOME/<name>.config.toml over config.toml for `codex --profile <name>`,
62
+ // so grunt gets its own file and the user's config.toml is never edited.
63
+ export const codexProfilePath = () => join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'grunt.config.toml');
64
+ export async function configureCodex(port = 8788) {
65
+ return writeConfig(codexProfilePath(), `# Written by usegrunt setup for \`codex --profile grunt\`. Your config.toml is unchanged.
66
+ model = "grunt"
67
+ model_provider = "grunt"
68
+
69
+ [model_providers.grunt]
70
+ name = "grunt"
71
+ base_url = "http://127.0.0.1:${port}/v1"
72
+ wire_api = "responses"
73
+ `);
74
+ }
75
+ export const opencodeConfigDir = () => join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'opencode');
76
+ // Adds a grunt provider and leaves OpenCode's default model alone; pick it with /models.
77
+ export async function configureOpenCode(port = 8788) {
78
+ const directory = opencodeConfigDir(), path = join(directory, 'opencode.json');
79
+ try {
80
+ await access(path);
81
+ }
82
+ catch {
83
+ try {
84
+ await access(join(directory, 'opencode.jsonc'));
85
+ throw new Error(`OpenCode uses ${join(directory, 'opencode.jsonc')}, which setup does not edit. Add the grunt provider by hand: see the README`);
86
+ }
87
+ catch (error) {
88
+ if (error.code !== 'ENOENT')
89
+ throw error;
90
+ }
91
+ }
92
+ const saved = await readJson(path, 'OpenCode config');
93
+ const provider = objectOrEmpty(saved.provider, 'OpenCode config');
94
+ provider.grunt = { name: 'grunt', npm: '@ai-sdk/openai-compatible', options: { baseURL: `http://127.0.0.1:${port}/v1`, apiKey: 'local' }, models: { grunt: { name: 'grunt' } } };
95
+ return writeConfig(path, JSON.stringify({ $schema: 'https://opencode.ai/config.json', ...saved, provider }, null, 2) + '\n');
96
+ }
97
+ // Free services refuse a message repeated word for word as automated use, so each check differs.
98
+ const prompt = (tool) => `Reply only: grunt is ready for ${tool} (check ${randomInt(1000, 10000)}). Do not use tools or change files.`;
99
+ export const HARNESSES = [
100
+ { id: 'pi', name: 'Pi', binary: 'pi', configure: configurePi,
101
+ check: () => ({ args: ['-p', '--provider', 'grunt', '--model', 'grunt', '--no-session', prompt('Pi')] }),
102
+ launch: () => 'pi --provider grunt --model grunt (or open /model in pi and choose grunt)' },
103
+ { id: 'codex', name: 'Codex', binary: 'codex', configure: configureCodex,
104
+ check: () => ({ args: ['exec', '--profile', 'grunt', '--skip-git-repo-check', '--ephemeral', '--sandbox', 'read-only', prompt('Codex')] }),
105
+ launch: () => 'codex --profile grunt' },
106
+ { id: 'opencode', name: 'OpenCode', binary: 'opencode', configure: configureOpenCode,
107
+ // grunt's own OpenCode source sets OPENCODE_CONFIG; check the user's config without it.
108
+ check: () => ({ args: ['run', '-m', 'grunt/grunt', prompt('OpenCode')], env: { OPENCODE_CONFIG: undefined } }),
109
+ launch: () => 'opencode -m grunt/grunt (or pick grunt with /models)' },
110
+ { id: 'claude', name: 'Claude Code', binary: 'claude', configure: async () => undefined,
111
+ check: port => ({ args: ['-p', '--model', 'grunt', prompt('Claude Code')], env: { ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}`, ANTHROPIC_AUTH_TOKEN: 'local' } }),
112
+ launch: port => `ANTHROPIC_BASE_URL=http://127.0.0.1:${port} ANTHROPIC_AUTH_TOKEN=local claude --model grunt` }
113
+ ];
114
+ export async function onPath(binary, path = process.env.PATH ?? '') {
115
+ for (const directory of path.split(delimiter).filter(Boolean)) {
116
+ try {
117
+ await access(join(directory, binary), constants.X_OK);
118
+ return true;
119
+ }
120
+ catch { /* Try the next PATH entry. */ }
121
+ }
122
+ return false;
123
+ }
124
+ export async function detectHarnesses(harnesses = HARNESSES) {
125
+ const found = await Promise.all(harnesses.map(harness => onPath(harness.binary)));
126
+ return harnesses.filter((_, index) => found[index]);
127
+ }
128
+ export async function runHarness(binary, args, env = {}, timeoutMs = 240000) {
129
+ const cwd = await mkdtemp(join(tmpdir(), 'grunt-harness-check-'));
130
+ const merged = { ...process.env };
131
+ for (const [key, value] of Object.entries(env)) {
132
+ if (value === undefined)
133
+ delete merged[key];
134
+ else
135
+ merged[key] = value;
136
+ }
137
+ try {
138
+ return await new Promise((resolve, reject) => {
139
+ const child = spawn(binary, args, { cwd, env: merged, stdio: ['ignore', 'pipe', 'pipe'], signal: AbortSignal.timeout(timeoutMs) });
140
+ let stdout = '', stderr = '';
141
+ child.stdout.on('data', (chunk) => { stdout = (stdout + chunk.toString()).slice(-65536); });
142
+ child.stderr.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); });
143
+ child.once('error', error => reject(new Error(error.name === 'AbortError' ? `${binary} did not answer within ${Math.round(timeoutMs / 1000)} seconds` : `Could not run ${binary}`)));
144
+ child.once('close', code => {
145
+ const lastLine = (text) => text.trim().split('\n').at(-1)?.slice(0, 200);
146
+ if (code !== 0)
147
+ reject(new Error(`${binary} exited with code ${code}${lastLine(stderr) ? `: ${lastLine(stderr)}` : ''}`));
148
+ else if (!stdout.trim())
149
+ reject(new Error(`${binary} printed no answer`));
150
+ else
151
+ resolve(stdout.trim());
152
+ });
153
+ });
154
+ }
155
+ finally {
156
+ await rm(cwd, { recursive: true, force: true });
157
+ }
158
+ }
159
+ export async function connectHarness(harness, port, run = runHarness) {
160
+ const change = await harness.configure(port);
161
+ const check = harness.check(port);
162
+ const answer = await run(harness.binary, check.args, check.env);
163
+ return { change, answer };
164
+ }
@@ -31,7 +31,7 @@ export function configure(env = process.env, registry = () => bundledRegistry) {
31
31
  };
32
32
  const connection = { url, loadKey };
33
33
  const dots = new Dots({ env, timeout: positive(env.MILO_DOTS_TIMEOUT_MS, 300000) });
34
- const registered = [dots, new Codex(env.MILO_CODEX_MODEL ? { model: env.MILO_CODEX_MODEL } : {}), new FreeLLMAPI(connection), new FreeLLMAPI({ ...connection, id: 'kilo', model: 'kilo-auto/free' }), new OpenCode({ model: () => env.MILO_OPENCODE_MODEL ?? registry().adapters.find(a => a.id === 'opencode')?.model ?? 'big-pickle', ...(env.MILO_OPENCODE_URL ? { url: env.MILO_OPENCODE_URL } : {}) }), new Freebuff()];
34
+ const registered = [dots, new Codex(env.MILO_CODEX_MODEL ? { model: env.MILO_CODEX_MODEL } : {}), new FreeLLMAPI(connection), new FreeLLMAPI({ ...connection, id: 'kilo', model: 'kilo-auto/free' }), new OpenCode({ model: () => env.MILO_OPENCODE_MODEL ?? registry().adapters.find(a => a.id === 'opencode')?.model ?? 'big-pickle', ...(env.MILO_OPENCODE_URL ? { url: env.MILO_OPENCODE_URL } : {}) }), new Freebuff({ toolBridge: env.MILO_FREEBUFF_JSON_BRIDGE === '1' })];
35
35
  const ids = env.MILO_SOURCES?.split(',').map(id => id.trim()) ?? ['freebuff', 'opencode'];
36
36
  const routing = ids.every(id => ['freebuff', 'opencode'].includes(id)) ? { registry } : undefined;
37
37
  return new Sources(ids.map(id => { const source = registered.find(s => s.id === id); if (!source)
@@ -46,6 +46,7 @@ export function start(env = process.env) {
46
46
  ensure: async (adapter, signal) => {
47
47
  if (!sources.sources.some(source => source.id === adapter.id))
48
48
  return;
49
+ sources.preparing.add(adapter.id);
49
50
  const squire = new BrowserSquire({ background: true, signal });
50
51
  try {
51
52
  const result = await setupFallbacks({ directory, run: (binary, args) => command(binary, args, false, signal), notify: console.error, adapters: [adapter.id], squire, signal,
@@ -55,13 +56,17 @@ export function start(env = process.env) {
55
56
  sources.healthy(adapter.id);
56
57
  }
57
58
  finally {
59
+ sources.preparing.delete(adapter.id);
58
60
  await squire.close();
59
61
  }
60
62
  }
61
63
  });
62
64
  // Load the private cache before accepting tasks, without waiting for the network.
63
- const ready = sync.load();
64
- void ready.then(() => sync.start()).catch(() => console.error('Registry sync could not start; using the bundled list'));
65
+ // Mark adapters as preparing until their first background setup finishes.
66
+ const ready = sync.load().then(() => { for (const adapter of sync.enabled)
67
+ if (sources.sources.some(source => source.id === adapter.id))
68
+ sources.preparing.add(adapter.id); });
69
+ void ready.then(() => sync.start()).catch(() => console.error('Registry sync could not start; using the bundled list')).finally(() => sources.preparing.clear());
65
70
  // Warm the saved login without delaying the server; failed loads retry lazily.
66
71
  void sources.sources.find(source => source.id === 'freellmapi' || source.id === 'kilo')?.available();
67
72
  const port = positive(env.MILO_PORT, 8788);
@@ -70,7 +75,7 @@ export function start(env = process.env) {
70
75
  const app = createLocalApp(sources, { port, dotsEnv: env, log: cwd => console.error(`grunt working directory: ${cwd}`) });
71
76
  const server = serve({ fetch: async (request) => { await ready; return app.fetch(request); }, hostname: HOST, port }, () => console.error(`grunt model API: http://${HOST}:${port}/v1`));
72
77
  // A distinct source list prevents FreeLLMAPI -> grunt -> FreeLLMAPI recursion.
73
- const fallback = env.MILO_FREEBUFF_BRIDGE !== '0' && sources.sources.some(s => s.id === 'freellmapi' || s.id === 'kilo') ? new Sources([new Freebuff()]) : undefined;
78
+ const fallback = env.MILO_FREEBUFF_BRIDGE !== '0' && sources.sources.some(s => s.id === 'freellmapi' || s.id === 'kilo') ? new Sources([new Freebuff({ toolBridge: env.MILO_FREEBUFF_JSON_BRIDGE === '1' })]) : undefined;
74
79
  const bridge = fallback ? serve({ fetch: createLocalApp(fallback, { port: 8789 }).fetch, hostname: HOST, port: 8789 }) : undefined;
75
80
  let closing = false;
76
81
  const close = async () => { if (closing)
@@ -3,7 +3,7 @@ import { execFile } from 'node:child_process';
3
3
  import { promisify } from 'node:util';
4
4
  import { realpath } from 'node:fs/promises';
5
5
  import { userTurns } from './harness.js';
6
- import { SourceError } from './source.js';
6
+ import { SourceError, answeredBy } from './source.js';
7
7
  import { knownAdapters } from '../registry.js';
8
8
  const exec = promisify(execFile);
9
9
  export class StickyRouter {
@@ -99,6 +99,7 @@ export class StickyRouter {
99
99
  task.failures = 0;
100
100
  task.output = Buffer.from(result.text).subarray(-4096).toString('utf8');
101
101
  task.switched = false;
102
+ answeredBy.set(result, selected.source.id);
102
103
  return result;
103
104
  }
104
105
  catch (error) {
@@ -9,9 +9,13 @@ export class SourceError extends Error {
9
9
  this.output = output;
10
10
  }
11
11
  }
12
+ // Names the adapter that produced each completion; setup checks it against the requested adapter.
13
+ export const answeredBy = new WeakMap();
12
14
  export class Sources {
13
15
  sources;
14
16
  router;
17
+ // Adapters whose background setup has not finished yet.
18
+ preparing = new Set();
15
19
  constructor(sources, routing) {
16
20
  this.sources = sources;
17
21
  if (!sources.length || new Set(sources.map(s => s.id)).size !== sources.length)
@@ -58,6 +62,7 @@ export class Sources {
58
62
  continue;
59
63
  }
60
64
  console.error(`grunt source: ${source.id} answered model ${request.model}`);
65
+ answeredBy.set(completion, source.id);
61
66
  return completion;
62
67
  }
63
68
  throw last;
@@ -68,6 +73,7 @@ export class Gateway {
68
73
  key;
69
74
  fetcher;
70
75
  id = 'gateway';
76
+ supportsFunctionTools = true;
71
77
  url;
72
78
  constructor(url, key, fetcher = fetch) {
73
79
  this.key = key;