usegrunt 0.0.1 → 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,210 @@
1
+ import { pairDots } from './dots-link.js';
2
+ import { Hono } from 'hono';
3
+ import { streamSSE } from 'hono/streaming';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { mkdir } from 'node:fs/promises';
6
+ import { homedir } from 'node:os';
7
+ import { isAbsolute, join } from 'node:path';
8
+ import { housekeeping, userText } from './harness.js';
9
+ import { SourceError, answeredBy } from './source.js';
10
+ const object = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
11
+ const array = (v) => Array.isArray(v) ? v : [];
12
+ function text(v) {
13
+ if (typeof v === 'string')
14
+ return v;
15
+ return array(v).flatMap(b => {
16
+ const p = object(b);
17
+ if (p.type === 'text' || p.type === 'input_text' || p.type === 'output_text')
18
+ return String(p.text ?? '');
19
+ if (p.type === 'tool_result')
20
+ return text(p.content);
21
+ if (p.type === 'tool_use')
22
+ return `[tool ${p.name}] ${JSON.stringify(p.input)}`;
23
+ return [];
24
+ }).join('\n');
25
+ }
26
+ export function decode(body, api, fallback) {
27
+ let messages;
28
+ if (api === 'responses') {
29
+ messages = typeof body.input === 'string' ? [{ role: 'user', content: body.input }] : array(body.input).flatMap((v) => {
30
+ const m = object(v);
31
+ if (m.type === 'function_call_output')
32
+ return [{ role: 'tool', content: typeof m.output === 'string' ? m.output : JSON.stringify(m.output) ?? '', tool_call_id: String(m.call_id) }];
33
+ if (m.type === 'function_call')
34
+ return [{ role: 'assistant', content: '', tool_calls: [{ id: String(m.call_id), type: 'function', function: { name: String(m.name), arguments: String(m.arguments) } }] }];
35
+ if (m.type && m.type !== 'message')
36
+ return [];
37
+ return [{ role: String(m.role ?? 'user'), content: text(m.content) }];
38
+ });
39
+ if (body.instructions)
40
+ messages.unshift({ role: 'developer', content: text(body.instructions) });
41
+ }
42
+ else {
43
+ messages = array(body.messages).flatMap(v => {
44
+ const m = object(v);
45
+ if (api !== 'messages' || typeof m.content === 'string')
46
+ return [{ role: String(m.role), content: text(m.content), ...(m.tool_calls ? { tool_calls: m.tool_calls } : {}), ...(m.tool_call_id ? { tool_call_id: String(m.tool_call_id) } : {}) }];
47
+ const blocks = array(m.content).map(object);
48
+ const calls = blocks.filter(b => b.type === 'tool_use').map(b => ({ id: String(b.id), type: 'function', function: { name: String(b.name), arguments: JSON.stringify(b.input) } }));
49
+ const content = text(blocks.filter(b => b.type !== 'tool_use' && b.type !== 'tool_result'));
50
+ const turn = content || calls.length ? [{ role: String(m.role), content, ...(calls.length ? { tool_calls: calls } : {}) }] : [];
51
+ return [...turn, ...blocks.filter(b => b.type === 'tool_result').map(b => ({ role: 'tool', content: text(b.content), tool_call_id: String(b.tool_use_id) }))];
52
+ });
53
+ if (body.system)
54
+ messages.unshift({ role: 'system', content: text(body.system) });
55
+ }
56
+ if (!messages.length)
57
+ throw new Error('Provide messages or input');
58
+ const tools = array(body.tools).map(v => {
59
+ const t = object(v), f = object(t.function ?? t);
60
+ if (t.type && t.type !== 'function' && !t.input_schema)
61
+ return t;
62
+ return { type: 'function', function: { name: String(f.name), parameters: f.parameters ?? f.input_schema ?? {}, ...(typeof f.description === 'string' ? { description: f.description } : {}) } };
63
+ });
64
+ const context = messages.filter(m => ['system', 'developer'].includes(m.role) || /<environment_context>|# Environment/.test(m.content)).map(m => m.content).join('\n');
65
+ const matches = [...context.matchAll(/(?:<cwd>\s*([^<\n]+)\s*<\/cwd>|(?:Working directory|Current working directory|Primary working directory|cwd):\s*([^\n<]+))/gi)];
66
+ const absolute = matches.filter(m => isAbsolute((m[1] ?? m[2] ?? '').trim()));
67
+ const inferred = absolute.find(m => /^Primary working directory:/i.test(m[0])) ?? absolute[0];
68
+ const namedCwd = typeof body.cwd === 'string' ? body.cwd : (inferred?.[1] ?? inferred?.[2])?.trim();
69
+ const rawTurns = api === 'responses' ? (typeof body.input === 'string' ? [{ role: 'user', content: body.input }] : array(body.input)) : array(body.messages);
70
+ const userMessages = rawTurns.map(object).filter(m => (m.role === 'user' || (api === 'responses' && !m.role && !m.type))).map(m => typeof m.content === 'string' ? userText(m.content) : array(m.content).map(object).filter(b => b.type === 'text' || b.type === 'input_text').map(b => userText(String(b.text ?? ''))).filter(t => t.length > 0).join('\n')).filter(t => t.length > 0);
71
+ const cwdSource = namedCwd !== undefined ? 'request' : fallback !== undefined ? 'fallback' : 'scratch';
72
+ const cwd = namedCwd ?? fallback ?? join(process.env.XDG_STATE_HOME || join(homedir(), '.local/state'), 'grunt/scratch', createHash('sha256').update(userMessages[0] ?? '').digest('hex').slice(0, 24));
73
+ if (!isAbsolute(cwd))
74
+ throw new Error('Working directory must be an absolute path');
75
+ const tokens = body.max_tokens ?? body.max_output_tokens ?? body.max_completion_tokens;
76
+ const imageInput = /"type"\s*:\s*"(?:image|input_image|image_url)"/.test(JSON.stringify(body.input ?? body.messages));
77
+ return { model: String(body.model ?? 'milo'), messages, userMessages, tools, cwd, cwdSource, stream: body.stream === true, ...(imageInput ? { imageInput: true } : {}), ...(typeof tokens === 'number' ? { maxTokens: tokens } : {}) };
78
+ }
79
+ function toolInput(arguments_) {
80
+ try {
81
+ return JSON.parse(arguments_ || '{}');
82
+ }
83
+ catch {
84
+ return arguments_;
85
+ }
86
+ }
87
+ export function encode(result, model, api) {
88
+ const id = randomUUID(), input = result.inputTokens ?? 0, output = result.outputTokens ?? 0;
89
+ if (api === 'messages')
90
+ return { id: `msg_${id}`, type: 'message', role: 'assistant', model, content: [...(result.text ? [{ type: 'text', text: result.text }] : []), ...(result.calls ?? []).map(c => ({ type: 'tool_use', id: c.id, name: c.function.name, input: toolInput(c.function.arguments) }))], stop_reason: result.calls?.length ? 'tool_use' : 'end_turn', stop_sequence: null, usage: { input_tokens: input, output_tokens: output } };
91
+ if (api === 'responses')
92
+ return { id: `resp_${id}`, object: 'response', created_at: Math.floor(Date.now() / 1000), status: 'completed', error: null, incomplete_details: null, model, output: [...(result.text ? [{ id: `msg_${id}`, type: 'message', status: 'completed', role: 'assistant', content: [{ type: 'output_text', text: result.text, annotations: [] }] }] : []), ...(result.calls ?? []).map(c => ({ id: `fc_${c.id}`, type: 'function_call', status: 'completed', call_id: c.id, name: c.function.name, arguments: c.function.arguments }))], usage: { input_tokens: input, output_tokens: output, total_tokens: input + output, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 } }, parallel_tool_calls: true, tools: [], tool_choice: 'auto' };
93
+ return { id: `chatcmpl-${id}`, object: 'chat.completion', created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, message: { role: 'assistant', content: result.text || null, ...(result.calls?.length ? { tool_calls: result.calls } : {}) }, finish_reason: result.calls?.length ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: input, completion_tokens: output, total_tokens: input + output } };
94
+ }
95
+ export function events(value, api) {
96
+ const out = [];
97
+ let seq = 0;
98
+ const push = (event, data) => out.push({ ...(api !== 'chat' ? { event } : {}), data: JSON.stringify(api === 'responses' ? { ...data, sequence_number: seq++ } : data) });
99
+ if (api === 'chat') {
100
+ const choice = object(array(value.choices)[0]), message = object(choice.message);
101
+ const chunk = (delta, finish = null) => push('', { id: value.id, object: 'chat.completion.chunk', created: value.created, model: value.model, choices: [{ index: 0, delta, finish_reason: finish }] });
102
+ chunk({ role: 'assistant', content: '' });
103
+ if (message.content)
104
+ chunk({ content: message.content });
105
+ array(message.tool_calls).forEach((c, index) => chunk({ tool_calls: [{ ...object(c), index }] }));
106
+ chunk({}, choice.finish_reason);
107
+ out.push({ data: '[DONE]' });
108
+ }
109
+ else if (api === 'messages') {
110
+ push('message_start', { type: 'message_start', message: { ...value, content: [], stop_reason: null, usage: { ...object(value.usage), output_tokens: 0 } } });
111
+ array(value.content).forEach((v, index) => {
112
+ const b = object(v), tool = b.type === 'tool_use';
113
+ push('content_block_start', { type: 'content_block_start', index, content_block: tool ? { ...b, input: {} } : { type: 'text', text: '' } });
114
+ push('content_block_delta', { type: 'content_block_delta', index, delta: tool ? { type: 'input_json_delta', partial_json: JSON.stringify(b.input) } : { type: 'text_delta', text: b.text } });
115
+ push('content_block_stop', { type: 'content_block_stop', index });
116
+ });
117
+ push('message_delta', { type: 'message_delta', delta: { stop_reason: value.stop_reason, stop_sequence: null }, usage: { output_tokens: object(value.usage).output_tokens } });
118
+ push('message_stop', { type: 'message_stop' });
119
+ }
120
+ else {
121
+ for (const type of ['response.created', 'response.in_progress'])
122
+ push(type, { type, response: { ...value, status: 'in_progress', output: [], usage: null } });
123
+ array(value.output).forEach((v, output_index) => {
124
+ const item = object(v), tool = item.type === 'function_call';
125
+ push('response.output_item.added', { type: 'response.output_item.added', output_index, item: tool ? { ...item, status: 'in_progress', arguments: '' } : { ...item, status: 'in_progress', content: [] } });
126
+ const common = { item_id: item.id, output_index, content_index: 0 };
127
+ if (tool) {
128
+ push('response.function_call_arguments.delta', { type: 'response.function_call_arguments.delta', ...common, delta: item.arguments });
129
+ push('response.function_call_arguments.done', { type: 'response.function_call_arguments.done', ...common, arguments: item.arguments });
130
+ }
131
+ else {
132
+ const part = object(array(item.content)[0]);
133
+ push('response.content_part.added', { type: 'response.content_part.added', ...common, part: { ...part, text: '' } });
134
+ push('response.output_text.delta', { type: 'response.output_text.delta', ...common, delta: part.text, logprobs: [] });
135
+ push('response.output_text.done', { type: 'response.output_text.done', ...common, text: part.text, logprobs: [] });
136
+ push('response.content_part.done', { type: 'response.content_part.done', ...common, part });
137
+ }
138
+ push('response.output_item.done', { type: 'response.output_item.done', output_index, item });
139
+ });
140
+ push('response.completed', { type: 'response.completed', response: value });
141
+ }
142
+ return out;
143
+ }
144
+ export function createLocalApp(sources, options = {}) {
145
+ const app = new Hono();
146
+ app.use('*', async (c, next) => {
147
+ const port = options.port ?? 8788;
148
+ const host = c.req.header('host') ?? new URL(c.req.url).host;
149
+ if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(host) || (c.req.raw.headers.has('origin') && c.req.path !== '/dots/pair'))
150
+ return c.json({ error: { message: 'Forbidden local request' } }, 403);
151
+ if (c.req.method === 'POST' && c.req.header('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json')
152
+ return c.json({ error: { message: 'Content-Type must be application/json' } }, 415);
153
+ await next();
154
+ });
155
+ app.get('/dots/pair', c => pairDots(c.req.raw, options.dotsEnv ?? process.env));
156
+ app.get('/v1/models', async (c) => c.json({ object: 'list', data: (await sources.models()).map(id => ({ id, object: 'model', created: 0, owned_by: 'milo' })) }));
157
+ for (const [path, api] of [['chat/completions', 'chat'], ['messages', 'messages'], ['responses', 'responses']]) {
158
+ app.post(`/v1/${path}`, async (c) => {
159
+ let request;
160
+ try {
161
+ request = decode(object(await c.req.json()), api, options.cwd);
162
+ }
163
+ catch (e) {
164
+ return c.json({ ...(api === 'messages' ? { type: 'error' } : {}), error: { type: 'invalid_request_error', message: e instanceof Error ? e.message : 'Invalid request' } }, 400);
165
+ }
166
+ const local = housekeeping(request);
167
+ options.log?.(`${request.cwd}; cwd=${request.cwdSource}; classification=${local === undefined ? 'user' : 'housekeeping'}`);
168
+ const complete = (signal) => local === undefined ? sources.complete(request, signal) : Promise.resolve({ text: local });
169
+ const controller = new AbortController();
170
+ const abort = () => controller.abort();
171
+ c.req.raw.signal.addEventListener('abort', abort, { once: true });
172
+ const failure = (e) => {
173
+ const err = e instanceof SourceError ? e : new SourceError('upstream', 'grunt source failed');
174
+ return { err, body: { ...(api === 'messages' ? { type: 'error' } : {}), error: { type: api === 'messages' ? 'api_error' : 'server_error', code: err.code, message: err.message } } };
175
+ };
176
+ try {
177
+ // Agent adapters return final text, not incremental tokens. Resolve routing
178
+ // before committing SSE headers so exhausted routes still return HTTP 429.
179
+ if (request.cwdSource === 'scratch')
180
+ await mkdir(request.cwd, { recursive: true });
181
+ const completion = await complete(controller.signal);
182
+ const source = answeredBy.get(completion);
183
+ if (source)
184
+ c.header('X-Grunt-Source', source);
185
+ if (sources.preparing.size)
186
+ c.header('X-Grunt-Preparing', [...sources.preparing].join(','));
187
+ const result = encode(completion, request.model, api);
188
+ if (request.stream)
189
+ return streamSSE(c, async (stream) => {
190
+ stream.onAbort(abort);
191
+ for (const event of events(result, api))
192
+ await stream.writeSSE(event);
193
+ });
194
+ return c.json(result);
195
+ }
196
+ catch (e) {
197
+ const { err, body } = failure(e);
198
+ if (sources.preparing.size)
199
+ c.header('X-Grunt-Preparing', [...sources.preparing].join(','));
200
+ if (err.retryAfter !== undefined)
201
+ c.header('Retry-After', String(Math.max(1, Math.ceil(err.retryAfter))));
202
+ return c.json(body, err.code === 'quota' ? 429 : err.code === 'timeout' ? 504 : 503);
203
+ }
204
+ finally {
205
+ c.req.raw.signal.removeEventListener('abort', abort);
206
+ }
207
+ });
208
+ }
209
+ return app;
210
+ }
@@ -0,0 +1,71 @@
1
+ import { createServer, request as httpRequest } from 'node:http';
2
+ import { request as httpsRequest } from 'node:https';
3
+ import { randomBytes } from 'node:crypto';
4
+ // The Squire share URL is a bearer capability. Keep it on the server; expose
5
+ // only a temporary loopback link to the local user, using Squire's existing UI.
6
+ export async function proxyApproval(remote) {
7
+ const target = new URL(remote);
8
+ if (target.protocol !== 'https:' && !(target.protocol === 'http:' && target.hostname === '127.0.0.1'))
9
+ throw new Error('Invalid Squire browser handoff');
10
+ const path = `/approval/${randomBytes(24).toString('hex')}/`;
11
+ const upstream = target.protocol === 'https:' ? httpsRequest : httpRequest;
12
+ const sockets = new Set();
13
+ let origin = '';
14
+ const allowed = (host, from) => host === new URL(origin).host && (!from || from === origin);
15
+ const server = createServer((req, res) => {
16
+ res.setHeader('Cache-Control', 'no-store');
17
+ res.setHeader('Referrer-Policy', 'no-referrer');
18
+ if (!allowed(req.headers.host, req.headers.origin) || req.method !== 'GET' || req.url !== path) {
19
+ res.writeHead(403).end();
20
+ return;
21
+ }
22
+ const outgoing = upstream(target, { method: 'GET', timeout: 10000 }, reply => {
23
+ if (reply.statusCode !== 200) {
24
+ reply.resume();
25
+ res.writeHead(502).end('Squire browser handoff unavailable');
26
+ return;
27
+ }
28
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
29
+ reply.pipe(res);
30
+ });
31
+ outgoing.on('timeout', () => outgoing.destroy());
32
+ outgoing.on('error', () => { if (!res.headersSent)
33
+ res.writeHead(502); res.end('Squire browser handoff unavailable'); });
34
+ outgoing.end();
35
+ });
36
+ server.on('upgrade', (req, socket, head) => {
37
+ if (!allowed(req.headers.host, req.headers.origin) || req.url !== `${path}stream`) {
38
+ socket.destroy();
39
+ return;
40
+ }
41
+ const headers = Object.fromEntries(Object.entries(req.headers).filter(([name]) => name.startsWith('sec-websocket-')));
42
+ const outgoing = upstream(new URL('stream', target), { headers: { ...headers, Connection: 'Upgrade', Upgrade: 'websocket' } });
43
+ outgoing.on('upgrade', (response, peer, extra) => {
44
+ sockets.add(socket);
45
+ sockets.add(peer);
46
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\n${Object.entries(response.headers).map(([key, value]) => `${key}: ${value}`).join('\r\n')}\r\n\r\n`);
47
+ if (head.length)
48
+ peer.write(head);
49
+ if (extra.length)
50
+ socket.write(extra);
51
+ socket.pipe(peer).pipe(socket);
52
+ socket.on('close', () => { sockets.delete(socket); peer.destroy(); });
53
+ peer.on('close', () => { sockets.delete(peer); socket.destroy(); });
54
+ socket.on('error', () => peer.destroy());
55
+ peer.on('error', () => socket.destroy());
56
+ });
57
+ outgoing.on('error', () => socket.destroy());
58
+ outgoing.on('response', res => { res.resume(); socket.destroy(); });
59
+ outgoing.end();
60
+ });
61
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
62
+ const address = server.address();
63
+ if (!address || typeof address === 'string')
64
+ throw new Error('Could not open local Squire approval');
65
+ origin = `http://127.0.0.1:${address.port}`;
66
+ const close = () => { for (const socket of sockets)
67
+ socket.destroy(); server.closeAllConnections(); server.close(); };
68
+ const timer = setTimeout(close, 900000);
69
+ timer.unref();
70
+ return { url: `${origin}${path}`, close: () => { clearTimeout(timer); close(); } };
71
+ }
@@ -0,0 +1,136 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import chalk from 'chalk';
3
+ // An original pixel miner in the grunt.run palette: hard hat, cigar, overalls.
4
+ // Each terminal cell shows two vertical pixels with half-block characters.
5
+ const WIDTH = 48, HEIGHT = 16, PILE = 12, SPRITE = 10;
6
+ const COLORS = {
7
+ Y: '#f4b41a', B: '#c4860c', S: '#e0a878', E: '#1a1410', C: '#6b3f22', F: '#ff5a1f', O: '#4a6fa5', D: '#3b2a1e', G: '#5a4030'
8
+ };
9
+ const TOKENS = ['#f4b41a', '#5ad1e6', '#a78bfa', '#6ee7a0', '#ff8a3d', '#f472b6'];
10
+ // Rows 1-3 hold a carried block; rows 4-14 are the miner; row 15 is the ground.
11
+ const BODY = [
12
+ '..........', '..........', '..........', '..........',
13
+ '...YYYY...', '...YYYY...', '..BBBBBBB.', '...SSSE...', '...SSSSCCF', '....OOO...', '..SOOOOOS.', '...OOOOO..'
14
+ ];
15
+ const CARRY = [
16
+ '...TTTT...', '...TTTT...', '...TTTT...', '..S....S..',
17
+ '..SYYYYS..', '..SYYYYS..', '..BBBBBBB.', '...SSSE...', '...SSSSCCF', '..S.OOO.S.', '...OOOOO..', '...OOOOO..'
18
+ ];
19
+ const LEGS = [['...O...O..', '..DD..DD..'], ['....O.O...', '....DDD...']];
20
+ // Pile slots, bottom row first: x and top y of a 4x3 block inside a 12-pixel pile.
21
+ const SLOTS = [[0, 12], [4, 12], [8, 12], [2, 9], [6, 9], [4, 6]];
22
+ function draw(scene) {
23
+ const pixels = Array.from({ length: HEIGHT }, () => Array(WIDTH).fill(undefined));
24
+ const block = (x, y, color) => { for (let dy = 0; dy < 3; dy++)
25
+ for (let dx = 0; dx < 4; dx++)
26
+ pixels[y + dy][x + dx] = color; };
27
+ scene.left.forEach((color, slot) => block(SLOTS[slot][0], SLOTS[slot][1], color));
28
+ scene.right.forEach((color, slot) => block(WIDTH - PILE + SLOTS[slot][0], SLOTS[slot][1], color));
29
+ const rows = [...(scene.carrying ? CARRY : BODY), ...LEGS[scene.step % 2]];
30
+ rows.forEach((row, y) => [...row].forEach((code, column) => {
31
+ if (code === '.')
32
+ return;
33
+ const x = scene.x + (scene.facing === 1 ? column : SPRITE - 1 - column);
34
+ pixels[y + 1][x] = code === 'T' ? scene.carrying : COLORS[code];
35
+ }));
36
+ pixels[HEIGHT - 1].fill(COLORS.G);
37
+ const lines = [];
38
+ for (let y = 0; y < HEIGHT; y += 2) {
39
+ let line = '';
40
+ for (let x = 0; x < WIDTH; x++) {
41
+ const top = pixels[y][x], bottom = pixels[y + 1][x];
42
+ if (top && bottom)
43
+ line += top === bottom ? chalk.hex(top)('█') : chalk.hex(top).bgHex(bottom)('▀');
44
+ else if (top)
45
+ line += chalk.hex(top)('▀');
46
+ else if (bottom)
47
+ line += chalk.hex(bottom)('▄');
48
+ else
49
+ line += ' ';
50
+ }
51
+ lines.push(line);
52
+ }
53
+ lines.push(chalk.dim('free AI quota'.padEnd(WIDTH - 'one local agent'.length) + 'one local agent'));
54
+ return lines;
55
+ }
56
+ // Grunt carries two token blocks from the free-quota pile to his own pile.
57
+ export function bannerFrames() {
58
+ const start = PILE, end = WIDTH - PILE - SPRITE;
59
+ const scene = { x: start, facing: 1, step: 0, carrying: undefined, left: TOKENS.slice(0, 6), right: [TOKENS[1]] };
60
+ const frames = [];
61
+ const shoot = (count = 1) => { for (let i = 0; i < count; i++)
62
+ frames.push(draw(scene)); };
63
+ const walk = (to) => {
64
+ scene.facing = to > scene.x ? 1 : -1;
65
+ while (scene.x !== to) {
66
+ scene.x += scene.facing;
67
+ scene.step++;
68
+ shoot();
69
+ }
70
+ scene.step = 0;
71
+ };
72
+ for (let trip = 0; trip < 2; trip++) {
73
+ shoot(2);
74
+ scene.carrying = scene.left.pop();
75
+ shoot(2);
76
+ walk(end);
77
+ scene.right.push(scene.carrying);
78
+ scene.carrying = undefined;
79
+ shoot(2);
80
+ if (trip === 0)
81
+ walk(start);
82
+ }
83
+ shoot(3);
84
+ return frames;
85
+ }
86
+ export const BANNER_TITLE = `${chalk.hex('#f4b41a').bold('grunt')}${chalk.dim(' — free AI inference, pooled on your machine')}`;
87
+ export const BANNER_WIDTH = WIDTH;
88
+ export function shouldAnimate(output, env = process.env) {
89
+ return Boolean(output.isTTY) && !env.CI && env.TERM !== 'dumb' && (output.columns ?? 0) >= WIDTH + 4;
90
+ }
91
+ // Plays about three seconds of animation, or prints only the title when the
92
+ // terminal cannot show it. Any key skips; Ctrl+C still interrupts setup.
93
+ export async function banner(options = {}) {
94
+ const output = options.output ?? process.stdout, input = options.input ?? process.stdin;
95
+ if (!shouldAnimate(output, options.env)) {
96
+ output.write(BANNER_TITLE + '\n');
97
+ return false;
98
+ }
99
+ const frames = bannerFrames();
100
+ let skipped = false, raw = false;
101
+ const onKey = (data) => { skipped = true; if (data.includes(3)) {
102
+ restore();
103
+ process.kill(process.pid, 'SIGINT');
104
+ } };
105
+ const restore = () => {
106
+ input.off('data', onKey);
107
+ if (raw) {
108
+ input.setRawMode(false);
109
+ input.pause();
110
+ raw = false;
111
+ }
112
+ output.write('\x1b[?25h');
113
+ };
114
+ if (input.isTTY) {
115
+ input.setRawMode(true);
116
+ raw = true;
117
+ input.on('data', onKey);
118
+ input.resume();
119
+ }
120
+ output.write('\x1b[?25l');
121
+ try {
122
+ let shown = 0;
123
+ for (const frame of frames) {
124
+ output.write((shown ? `\x1b[${shown}A` : '') + frame.map(line => '\r\x1b[2K' + line).join('\n') + '\n');
125
+ shown = frame.length;
126
+ if (skipped)
127
+ break;
128
+ await delay(options.frameMs ?? 55);
129
+ }
130
+ }
131
+ finally {
132
+ restore();
133
+ }
134
+ output.write(BANNER_TITLE + '\n');
135
+ return true;
136
+ }
@@ -0,0 +1,115 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { realpath } from 'node:fs/promises';
4
+ import { userTurns } from './harness.js';
5
+ import { executable } from './multiplexer.js';
6
+ import { SourceError } from './source.js';
7
+ function failure(output) {
8
+ const code = /usage.limit|quota|rate.limit|limit.reached|too many requests|credits.*exhausted/i.test(output) ? 'quota'
9
+ : /not logged in|logged out|sign.in|log.in|authentication|unauthorized|token.*expired/i.test(output) ? 'logged_out' : 'upstream';
10
+ return new SourceError(code, `Codex request failed (${code})`);
11
+ }
12
+ export class Codex {
13
+ options;
14
+ id = 'codex';
15
+ sessions = new Map();
16
+ busy = new Set();
17
+ shutdown = new AbortController();
18
+ constructor(options = {}) {
19
+ this.options = options;
20
+ }
21
+ async run(args, cwd, signal, input) {
22
+ signal.throwIfAborted();
23
+ const binary = await executable('codex');
24
+ signal.throwIfAborted();
25
+ return await new Promise((resolve, reject) => {
26
+ const child = spawn(binary, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'] });
27
+ let stdout = '', stderr = '', oversized = false;
28
+ let force;
29
+ const abort = () => { child.kill(); force = setTimeout(() => child.kill('SIGKILL'), 1000); };
30
+ signal.addEventListener('abort', abort, { once: true });
31
+ if (signal.aborted)
32
+ abort();
33
+ child.stdout.on('data', (chunk) => {
34
+ stdout += chunk.toString();
35
+ if (stdout.length > 8 * 1024 * 1024) {
36
+ oversized = true;
37
+ stdout = '';
38
+ child.kill('SIGKILL');
39
+ }
40
+ });
41
+ child.stderr.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-65536); });
42
+ child.stdin.on('error', () => { });
43
+ child.stdin.end(input);
44
+ child.once('error', () => { });
45
+ child.once('close', code => {
46
+ signal.removeEventListener('abort', abort);
47
+ if (force)
48
+ clearTimeout(force);
49
+ if (signal.aborted)
50
+ reject(new SourceError('timeout', 'Codex request timed out or was cancelled'));
51
+ else if (code !== 0 || oversized)
52
+ reject(failure(stdout + stderr));
53
+ else
54
+ resolve(stdout + (args[0] === 'login' ? stderr : ''));
55
+ });
56
+ });
57
+ }
58
+ async available() {
59
+ try {
60
+ return /Logged in using ChatGPT/i.test(await this.run(['login', 'status'], undefined, AbortSignal.timeout(10000)));
61
+ }
62
+ catch {
63
+ return false;
64
+ }
65
+ }
66
+ async complete(request, caller) {
67
+ const signal = AbortSignal.any([caller, this.shutdown.signal, AbortSignal.timeout(this.options.timeout ?? 600000)]);
68
+ const login = await this.run(['login', 'status'], undefined, signal);
69
+ if (!/Logged in using ChatGPT/i.test(login))
70
+ throw new SourceError('logged_out', 'Codex requires an existing ChatGPT login');
71
+ const turns = userTurns(request), prompt = turns.at(-1);
72
+ if (!prompt)
73
+ throw new SourceError('upstream', 'No user text in this request');
74
+ const cwd = await realpath(request.cwd);
75
+ const key = (history) => createHash('sha256').update(JSON.stringify([cwd, history])).digest('hex');
76
+ const prior = turns.length > 1 ? this.sessions.get(key(turns.slice(0, -1))) : undefined;
77
+ const session = prior && !this.busy.has(prior) ? prior : undefined;
78
+ if (session)
79
+ this.busy.add(session);
80
+ try {
81
+ // Exec options precede resume so workspace-write applies to both commands.
82
+ const args = ['exec', '--json', '--sandbox', 'workspace-write', ...(this.options.model ? ['-m', this.options.model] : []), ...(session ? ['resume', session] : []), '-'];
83
+ const output = await this.run(args, cwd, signal, prompt);
84
+ let thread, text = '';
85
+ for (const line of output.split('\n')) {
86
+ if (!line.trim())
87
+ continue;
88
+ let event;
89
+ try {
90
+ event = JSON.parse(line);
91
+ }
92
+ catch {
93
+ continue;
94
+ }
95
+ if (event.type === 'thread.started')
96
+ thread = event.thread_id;
97
+ if (event.type === 'error' || event.type === 'turn.failed')
98
+ throw failure(JSON.stringify(event));
99
+ if (event.type === 'item.completed' && event.item?.type === 'agent_message' && typeof event.item.text === 'string')
100
+ text = event.item.text;
101
+ }
102
+ if (!text)
103
+ throw new SourceError('upstream', 'Codex returned no assistant text');
104
+ if (thread || session)
105
+ this.sessions.set(key(turns), thread ?? session);
106
+ console.error('grunt source: codex');
107
+ return { text };
108
+ }
109
+ finally {
110
+ if (session)
111
+ this.busy.delete(session);
112
+ }
113
+ }
114
+ async close() { this.shutdown.abort(); }
115
+ }
@@ -0,0 +1,110 @@
1
+ import { randomBytes, randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { SourceError } from './source.js';
6
+ export function dotsConfigDir(env = process.env) { return env.MILO_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'milo'); }
7
+ export function dotsGateway(env = process.env) {
8
+ const url = new URL(env.MILO_DOTS_URL ?? 'https://api.grunt.run');
9
+ if (url.username || url.password || url.search || url.hash || url.pathname !== '/' || (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))))
10
+ throw new SourceError('upstream', 'MILO_DOTS_URL must be an HTTPS origin or a loopback test origin');
11
+ return url.origin;
12
+ }
13
+ export async function readDotsLink(env = process.env) {
14
+ try {
15
+ const value = JSON.parse(await readFile(join(dotsConfigDir(env), 'dots.json'), 'utf8'));
16
+ if (typeof value.deviceSecret !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(value.deviceSecret) || typeof value.gateway !== 'string')
17
+ return;
18
+ const gateway = dotsGateway({ ...env, MILO_DOTS_URL: env.MILO_DOTS_URL ?? value.gateway });
19
+ if (gateway !== value.gateway)
20
+ return;
21
+ return { deviceSecret: value.deviceSecret, gateway };
22
+ }
23
+ catch {
24
+ return;
25
+ }
26
+ }
27
+ // Pairing operations share one device secret even when two browser windows approve concurrently.
28
+ const pairing = new Map();
29
+ export async function redeemDots(input, env = process.env, fetcher = fetch, expectedReturn) {
30
+ if ((input.ticket && !/^[A-Za-z0-9_-]{43}$/.test(input.ticket)) || (input.code && !/^[A-Z0-9_-]{16}$/.test(input.code)) || (!input.ticket && !input.code))
31
+ throw new SourceError('upstream', 'Invalid grunt pairing');
32
+ const config = dotsConfigDir(env), gateway = dotsGateway(env);
33
+ const prior = pairing.get(config) ?? Promise.resolve();
34
+ const result = prior.catch(() => { }).then(async () => {
35
+ const existing = await readDotsLink(env);
36
+ const deviceSecret = existing?.deviceSecret ?? randomBytes(32).toString('base64url');
37
+ let value;
38
+ try {
39
+ const response = await fetcher(gateway + '/dots/redeem', { method: 'POST', redirect: 'error', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...input, deviceSecret }), signal: AbortSignal.timeout(15000) });
40
+ if (!response.ok)
41
+ throw new Error();
42
+ value = await response.json();
43
+ if (!value.paired || !validPairReturn(value.return, gateway) || (expectedReturn !== undefined && value.return !== expectedReturn))
44
+ throw new Error();
45
+ }
46
+ catch {
47
+ throw new SourceError('upstream', 'grunt pairing was refused or expired. Return to the Allow page and try again.');
48
+ }
49
+ // A refused ticket never creates or replaces local configuration.
50
+ await mkdir(config, { recursive: true, mode: 0o700 });
51
+ const temporary = join(config, `.dots-${randomUUID()}.tmp`);
52
+ await writeFile(temporary, JSON.stringify({ gateway, deviceSecret }) + '\n', { mode: 0o600, flag: 'wx' });
53
+ await rename(temporary, join(config, 'dots.json'));
54
+ return value.return;
55
+ });
56
+ pairing.set(config, result);
57
+ try {
58
+ return await result;
59
+ }
60
+ finally {
61
+ if (pairing.get(config) === result)
62
+ pairing.delete(config);
63
+ }
64
+ }
65
+ export function validPairReturn(value, gateway) {
66
+ if (typeof value !== 'string')
67
+ return false;
68
+ try {
69
+ const url = new URL(value);
70
+ return url.origin === gateway && !url.username && !url.password && !url.hash && url.pathname === '/oauth/complete' && Array.from(url.searchParams.keys()).length === 1 && /^[A-Za-z0-9_-]{43}$/.test(url.searchParams.get('flow') ?? '');
71
+ }
72
+ catch {
73
+ return false;
74
+ }
75
+ }
76
+ export async function dotsLink(code, env = process.env, fetcher = fetch, print = console.log) {
77
+ if (!code)
78
+ throw new SourceError('upstream', 'Use usegrunt dots link <code> only with the fallback code from the Allow page');
79
+ const target = await redeemDots({ code: code.toUpperCase() }, env, fetcher);
80
+ print('grunt is paired. Return to the Allow page and choose Continue to ChatGPT.');
81
+ return target;
82
+ }
83
+ export async function pairDots(request, env = process.env, fetcher = fetch) {
84
+ const reject = () => new Response('grunt refused this pairing. Return to the Allow page and try again.', { status: 403, headers: { 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' } });
85
+ if (!env.MILO_SOURCES?.split(',').some(id => id.trim() === 'dots'))
86
+ return reject();
87
+ const gateway = dotsGateway(env), url = new URL(request.url);
88
+ let referrer;
89
+ try {
90
+ referrer = new URL(request.headers.get('referer') ?? '');
91
+ }
92
+ catch {
93
+ return reject();
94
+ }
95
+ // A hostile site cannot send our gateway's browser-controlled Referer or navigation headers.
96
+ if (referrer.origin !== gateway || (request.headers.has('origin') && request.headers.get('origin') !== gateway) || (request.headers.has('sec-fetch-mode') && request.headers.get('sec-fetch-mode') !== 'navigate') || (request.headers.has('sec-fetch-dest') && request.headers.get('sec-fetch-dest') !== 'document'))
97
+ return reject();
98
+ const ticket = url.searchParams.get('ticket'), target = url.searchParams.get('return');
99
+ if (!ticket || !validPairReturn(target, gateway))
100
+ return reject();
101
+ try {
102
+ const confirmed = await redeemDots({ ticket }, env, fetcher, target);
103
+ if (confirmed !== target)
104
+ return reject();
105
+ return new Response(null, { status: 303, headers: { Location: confirmed, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' } });
106
+ }
107
+ catch {
108
+ return reject();
109
+ }
110
+ }