usegrunt 0.0.0-stage → 0.5.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,196 @@
1
+ import { pairDots } from './dots-link.js';
2
+ import { Hono } from 'hono';
3
+ import { streamSSE } from 'hono/streaming';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { isAbsolute } from 'node:path';
6
+ import { housekeeping, userText } from './harness.js';
7
+ import { SourceError } from './source.js';
8
+ const object = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
9
+ const array = (v) => Array.isArray(v) ? v : [];
10
+ function text(v) {
11
+ if (typeof v === 'string')
12
+ return v;
13
+ return array(v).flatMap(b => {
14
+ const p = object(b);
15
+ if (p.type === 'text' || p.type === 'input_text' || p.type === 'output_text')
16
+ return String(p.text ?? '');
17
+ if (p.type === 'tool_result')
18
+ return text(p.content);
19
+ if (p.type === 'tool_use')
20
+ return `[tool ${p.name}] ${JSON.stringify(p.input)}`;
21
+ return [];
22
+ }).join('\n');
23
+ }
24
+ export function decode(body, api, fallback) {
25
+ let messages;
26
+ if (api === 'responses') {
27
+ messages = typeof body.input === 'string' ? [{ role: 'user', content: body.input }] : array(body.input).flatMap((v) => {
28
+ const m = object(v);
29
+ if (m.type === 'function_call_output')
30
+ return [{ role: 'tool', content: typeof m.output === 'string' ? m.output : JSON.stringify(m.output) ?? '', tool_call_id: String(m.call_id) }];
31
+ if (m.type === 'function_call')
32
+ return [{ role: 'assistant', content: '', tool_calls: [{ id: String(m.call_id), type: 'function', function: { name: String(m.name), arguments: String(m.arguments) } }] }];
33
+ if (m.type && m.type !== 'message')
34
+ return [];
35
+ return [{ role: String(m.role ?? 'user'), content: text(m.content) }];
36
+ });
37
+ if (body.instructions)
38
+ messages.unshift({ role: 'developer', content: text(body.instructions) });
39
+ }
40
+ else {
41
+ messages = array(body.messages).flatMap(v => {
42
+ const m = object(v);
43
+ if (api !== 'messages' || typeof m.content === 'string')
44
+ 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) } : {}) }];
45
+ const blocks = array(m.content).map(object);
46
+ 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) } }));
47
+ const content = text(blocks.filter(b => b.type !== 'tool_use' && b.type !== 'tool_result'));
48
+ const turn = content || calls.length ? [{ role: String(m.role), content, ...(calls.length ? { tool_calls: calls } : {}) }] : [];
49
+ 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) }))];
50
+ });
51
+ if (body.system)
52
+ messages.unshift({ role: 'system', content: text(body.system) });
53
+ }
54
+ if (!messages.length)
55
+ throw new Error('Provide messages or input');
56
+ const tools = array(body.tools).map(v => {
57
+ const t = object(v), f = object(t.function ?? t);
58
+ if (t.type && t.type !== 'function' && !t.input_schema)
59
+ return t;
60
+ return { type: 'function', function: { name: String(f.name), parameters: f.parameters ?? f.input_schema ?? {}, ...(typeof f.description === 'string' ? { description: f.description } : {}) } };
61
+ });
62
+ const context = messages.filter(m => ['system', 'developer'].includes(m.role) || /<environment_context>|# Environment/.test(m.content)).map(m => m.content).join('\n');
63
+ const matches = [...context.matchAll(/(?:<cwd>\s*([^<\n]+)\s*<\/cwd>|(?:Working directory|Current working directory|Primary working directory|cwd):\s*([^\n<]+))/gi)];
64
+ const absolute = matches.filter(m => isAbsolute((m[1] ?? m[2] ?? '').trim()));
65
+ const inferred = absolute.find(m => /^Primary working directory:/i.test(m[0])) ?? absolute[0];
66
+ const cwd = typeof body.cwd === 'string' ? body.cwd : (inferred?.[1] ?? inferred?.[2])?.trim() ?? fallback;
67
+ if (!isAbsolute(cwd))
68
+ throw new Error('Working directory must be an absolute path');
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 tokens = body.max_tokens ?? body.max_output_tokens ?? body.max_completion_tokens;
72
+ const imageInput = /"type"\s*:\s*"(?:image|input_image|image_url)"/.test(JSON.stringify(body.input ?? body.messages));
73
+ return { model: String(body.model ?? 'milo'), messages, userMessages, tools, cwd, stream: body.stream === true, ...(imageInput ? { imageInput: true } : {}), ...(typeof tokens === 'number' ? { maxTokens: tokens } : {}) };
74
+ }
75
+ function toolInput(arguments_) {
76
+ try {
77
+ return JSON.parse(arguments_ || '{}');
78
+ }
79
+ catch {
80
+ return arguments_;
81
+ }
82
+ }
83
+ export function encode(result, model, api) {
84
+ const id = randomUUID(), input = result.inputTokens ?? 0, output = result.outputTokens ?? 0;
85
+ if (api === 'messages')
86
+ 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 } };
87
+ if (api === 'responses')
88
+ 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' };
89
+ 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 } };
90
+ }
91
+ export function events(value, api) {
92
+ const out = [];
93
+ let seq = 0;
94
+ const push = (event, data) => out.push({ ...(api !== 'chat' ? { event } : {}), data: JSON.stringify(api === 'responses' ? { ...data, sequence_number: seq++ } : data) });
95
+ if (api === 'chat') {
96
+ const choice = object(array(value.choices)[0]), message = object(choice.message);
97
+ 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 }] });
98
+ chunk({ role: 'assistant', content: '' });
99
+ if (message.content)
100
+ chunk({ content: message.content });
101
+ array(message.tool_calls).forEach((c, index) => chunk({ tool_calls: [{ ...object(c), index }] }));
102
+ chunk({}, choice.finish_reason);
103
+ out.push({ data: '[DONE]' });
104
+ }
105
+ else if (api === 'messages') {
106
+ push('message_start', { type: 'message_start', message: { ...value, content: [], stop_reason: null, usage: { ...object(value.usage), output_tokens: 0 } } });
107
+ array(value.content).forEach((v, index) => {
108
+ const b = object(v), tool = b.type === 'tool_use';
109
+ push('content_block_start', { type: 'content_block_start', index, content_block: tool ? { ...b, input: {} } : { type: 'text', text: '' } });
110
+ 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 } });
111
+ push('content_block_stop', { type: 'content_block_stop', index });
112
+ });
113
+ push('message_delta', { type: 'message_delta', delta: { stop_reason: value.stop_reason, stop_sequence: null }, usage: { output_tokens: object(value.usage).output_tokens } });
114
+ push('message_stop', { type: 'message_stop' });
115
+ }
116
+ else {
117
+ for (const type of ['response.created', 'response.in_progress'])
118
+ push(type, { type, response: { ...value, status: 'in_progress', output: [], usage: null } });
119
+ array(value.output).forEach((v, output_index) => {
120
+ const item = object(v), tool = item.type === 'function_call';
121
+ push('response.output_item.added', { type: 'response.output_item.added', output_index, item: tool ? { ...item, status: 'in_progress', arguments: '' } : { ...item, status: 'in_progress', content: [] } });
122
+ const common = { item_id: item.id, output_index, content_index: 0 };
123
+ if (tool) {
124
+ push('response.function_call_arguments.delta', { type: 'response.function_call_arguments.delta', ...common, delta: item.arguments });
125
+ push('response.function_call_arguments.done', { type: 'response.function_call_arguments.done', ...common, arguments: item.arguments });
126
+ }
127
+ else {
128
+ const part = object(array(item.content)[0]);
129
+ push('response.content_part.added', { type: 'response.content_part.added', ...common, part: { ...part, text: '' } });
130
+ push('response.output_text.delta', { type: 'response.output_text.delta', ...common, delta: part.text, logprobs: [] });
131
+ push('response.output_text.done', { type: 'response.output_text.done', ...common, text: part.text, logprobs: [] });
132
+ push('response.content_part.done', { type: 'response.content_part.done', ...common, part });
133
+ }
134
+ push('response.output_item.done', { type: 'response.output_item.done', output_index, item });
135
+ });
136
+ push('response.completed', { type: 'response.completed', response: value });
137
+ }
138
+ return out;
139
+ }
140
+ export function createLocalApp(sources, options = {}) {
141
+ const app = new Hono();
142
+ app.use('*', async (c, next) => {
143
+ const port = options.port ?? 8788;
144
+ const host = c.req.header('host') ?? new URL(c.req.url).host;
145
+ if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(host) || (c.req.raw.headers.has('origin') && c.req.path !== '/dots/pair'))
146
+ return c.json({ error: { message: 'Forbidden local request' } }, 403);
147
+ if (c.req.method === 'POST' && c.req.header('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json')
148
+ return c.json({ error: { message: 'Content-Type must be application/json' } }, 415);
149
+ await next();
150
+ });
151
+ app.get('/dots/pair', c => pairDots(c.req.raw, options.dotsEnv ?? process.env));
152
+ app.get('/v1/models', async (c) => c.json({ object: 'list', data: (await sources.models()).map(id => ({ id, object: 'model', created: 0, owned_by: 'milo' })) }));
153
+ for (const [path, api] of [['chat/completions', 'chat'], ['messages', 'messages'], ['responses', 'responses']]) {
154
+ app.post(`/v1/${path}`, async (c) => {
155
+ let request;
156
+ try {
157
+ request = decode(object(await c.req.json()), api, options.cwd ?? process.cwd());
158
+ }
159
+ catch (e) {
160
+ return c.json({ ...(api === 'messages' ? { type: 'error' } : {}), error: { type: 'invalid_request_error', message: e instanceof Error ? e.message : 'Invalid request' } }, 400);
161
+ }
162
+ const local = housekeeping(request);
163
+ options.log?.(`${request.cwd}; cwd=${request.cwd === (options.cwd ?? process.cwd()) ? 'fallback-or-explicit' : 'request'}; classification=${local === undefined ? 'user' : 'housekeeping'}`);
164
+ const complete = (signal) => local === undefined ? sources.complete(request, signal) : Promise.resolve({ text: local });
165
+ const controller = new AbortController();
166
+ const abort = () => controller.abort();
167
+ c.req.raw.signal.addEventListener('abort', abort, { once: true });
168
+ const failure = (e) => {
169
+ const err = e instanceof SourceError ? e : new SourceError('upstream', 'grunt source failed');
170
+ return { err, body: { ...(api === 'messages' ? { type: 'error' } : {}), error: { type: api === 'messages' ? 'api_error' : 'server_error', code: err.code, message: err.message } } };
171
+ };
172
+ try {
173
+ // Agent adapters return final text, not incremental tokens. Resolve routing
174
+ // before committing SSE headers so exhausted routes still return HTTP 429.
175
+ const result = encode(await complete(controller.signal), request.model, api);
176
+ if (request.stream)
177
+ return streamSSE(c, async (stream) => {
178
+ stream.onAbort(abort);
179
+ for (const event of events(result, api))
180
+ await stream.writeSSE(event);
181
+ });
182
+ return c.json(result);
183
+ }
184
+ catch (e) {
185
+ const { err, body } = failure(e);
186
+ if (err.retryAfter !== undefined)
187
+ c.header('Retry-After', String(Math.max(1, Math.ceil(err.retryAfter))));
188
+ return c.json(body, err.code === 'quota' ? 429 : err.code === 'timeout' ? 504 : 503);
189
+ }
190
+ finally {
191
+ c.req.raw.signal.removeEventListener('abort', abort);
192
+ }
193
+ });
194
+ }
195
+ return app;
196
+ }
@@ -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,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
+ }
@@ -0,0 +1,87 @@
1
+ import { userTurns } from './harness.js';
2
+ import { readDotsLink } from './dots-link.js';
3
+ import { SourceError } from './source.js';
4
+ export const DOTS_INSTRUCTION = 'Answer here in this conversation. Do not start Codex or Work tasks.';
5
+ export class Dots {
6
+ options;
7
+ id = 'dots';
8
+ shutdown = new AbortController();
9
+ constructor(options = {}) {
10
+ this.options = options;
11
+ }
12
+ get enabled() { return (this.options.env ?? process.env).MILO_SOURCES?.split(',').some(id => id.trim() === 'dots') ?? false; }
13
+ async call(link, path, signal, method = 'GET', body) {
14
+ const response = await (this.options.fetcher ?? fetch)(link.gateway + path, { method, redirect: 'error', signal, headers: { Authorization: `Bearer ${link.deviceSecret}`, 'Content-Type': 'application/json' }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
15
+ if (response.status === 204)
16
+ return {};
17
+ if (response.status === 202)
18
+ return { pending: true };
19
+ const result = await response.json();
20
+ if (!response.ok || result.error) {
21
+ const code = response.status === 401 ? 'logged_out' : result.error === 'quota' ? 'quota' : response.status === 410 ? 'timeout' : response.status === 409 ? 'not_installed' : 'upstream';
22
+ throw new SourceError(code, `Dots relay request failed (${code})`);
23
+ }
24
+ return result;
25
+ }
26
+ async available() {
27
+ if (!this.enabled)
28
+ return false;
29
+ const link = await readDotsLink(this.options.env);
30
+ if (!link)
31
+ return false;
32
+ try {
33
+ const status = await this.call(link, '/dots/status', AbortSignal.any([this.shutdown.signal, AbortSignal.timeout(10000)]));
34
+ return !!(status.linked && status.subscribed);
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
40
+ async complete(request, caller) {
41
+ if (!this.enabled)
42
+ throw new SourceError('not_installed', 'Add dots to MILO_SOURCES to enable it');
43
+ const link = await readDotsLink(this.options.env);
44
+ if (!link)
45
+ throw new SourceError('not_installed', 'Run usegrunt dots link to configure your dot');
46
+ const prompt = userTurns(request).at(-1);
47
+ if (!prompt)
48
+ throw new SourceError('upstream', 'No user text in this request');
49
+ const timeout = this.options.timeout ?? 300000;
50
+ const signal = AbortSignal.any([caller, this.shutdown.signal, AbortSignal.timeout(timeout)]);
51
+ let id;
52
+ try {
53
+ const messages = request.messages.filter(m => ['user', 'assistant'].includes(m.role)).map(m => ({ role: m.role, content: m.content }));
54
+ // The harness may supply canonical user turns separately from wire messages.
55
+ const latest = messages.findLastIndex(m => m.role === 'user');
56
+ if (latest < 0)
57
+ messages.push({ role: 'user', content: prompt + '\n\n' + DOTS_INSTRUCTION });
58
+ else
59
+ messages[latest] = { role: 'user', content: prompt + '\n\n' + DOTS_INSTRUCTION };
60
+ const queued = await this.call(link, '/dots/requests', signal, 'POST', { messages, timeout });
61
+ id = queued.id;
62
+ if (typeof id !== 'string' || !/^[a-f0-9-]{36}$/.test(id))
63
+ throw new SourceError('upstream', 'Dots relay returned an invalid request');
64
+ while (true) {
65
+ signal.throwIfAborted();
66
+ const reply = await this.call(link, `/dots/requests/${id}`, signal);
67
+ if (reply.pending)
68
+ continue;
69
+ if (typeof reply.text !== 'string')
70
+ throw new SourceError('upstream', 'Dots relay returned no answer');
71
+ return { text: reply.text };
72
+ }
73
+ }
74
+ catch (error) {
75
+ if (signal.aborted)
76
+ throw new SourceError('timeout', 'Dots request timed out or was cancelled');
77
+ if (error instanceof SourceError)
78
+ throw error;
79
+ throw new SourceError('upstream', 'Dots relay is unavailable');
80
+ }
81
+ finally {
82
+ if (id)
83
+ await this.call(link, `/dots/requests/${id}`, AbortSignal.timeout(2000), 'DELETE').catch(() => { });
84
+ }
85
+ }
86
+ async close() { this.shutdown.abort(); }
87
+ }