@dreamteamer/code 0.1.0 → 0.2.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.
package/src/gateway.mjs DELETED
@@ -1,57 +0,0 @@
1
- import http from 'node:http';
2
- import { randomBytes, timingSafeEqual } from 'node:crypto';
3
-
4
- const equals = (a, b) => typeof a === 'string' && Buffer.byteLength(a) === Buffer.byteLength(b) && timingSafeEqual(Buffer.from(a), Buffer.from(b));
5
- export async function gateway({ socketPath, workspace, port = 0, token = randomBytes(32).toString('base64url') }) {
6
- const cookieName = `dt_editor_${randomBytes(8).toString('hex')}`;
7
- let origin;
8
- const sockets = new Set();
9
- const cookies = (req) => (req.headers.cookie ?? '').split(';').map(v => v.trim()).find(v => v.startsWith(cookieName + '='))?.slice(cookieName.length + 1);
10
- const authenticated = (req) => equals(cookies(req), token) || equals(req.headers.authorization, `Bearer ${token}`);
11
- const allowed = (req) => req.headers.host === new URL(origin).host && (!req.headers.origin || req.headers.origin === origin);
12
- const headers = (req) => {
13
- const h = { ...req.headers, host: new URL(origin).host };
14
- delete h.authorization;
15
- for (const k of Object.keys(h)) if (k.startsWith('x-forwarded-') || k === 'forwarded') delete h[k];
16
- h.cookie = (h.cookie ?? '').split(';').filter(v => !v.trim().startsWith(cookieName + '=')).join(';');
17
- return h;
18
- };
19
- const server = http.createServer(async (req, res) => {
20
- const end = (status, text) => { res.writeHead(status, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' }); res.end(text); };
21
- if (!allowed(req)) return end(403, 'Forbidden origin');
22
- const url = new URL(req.url, origin);
23
- // A login URL exchanges the secret for a session cookie and immediately removes it from the URL.
24
- if (url.pathname === '/_dt/open') {
25
- if (req.method !== 'GET') return end(405, 'GET required');
26
- if (!authenticated(req) && !equals(url.searchParams.get('token'), token)) return end(401, 'Authentication required');
27
- res.writeHead(303, { Location: '/?' + new URLSearchParams({ folder: workspace }), 'Set-Cookie': `${cookieName}=${token}; HttpOnly; SameSite=Strict; Path=/`, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' });
28
- return res.end();
29
- }
30
- if (!authenticated(req)) return end(401, 'Open the authenticated URL printed by dt-editor.');
31
- if (url.pathname.startsWith('/_dt/')) return end(404, 'Not found');
32
- const upstream = http.request({ socketPath, method: req.method, path: req.url, headers: headers(req) }, response => {
33
- res.writeHead(response.statusCode, { ...response.headers, 'Referrer-Policy': 'no-referrer' }); response.pipe(res);
34
- });
35
- upstream.on('error', () => { if (!res.headersSent) end(502, 'Editor unavailable'); else res.destroy(); });
36
- req.on('aborted', () => upstream.destroy());
37
- req.pipe(upstream);
38
- });
39
- server.on('connection', socket => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); });
40
- server.on('upgrade', (req, socket, head) => {
41
- if (!allowed(req) || !authenticated(req) || req.url.startsWith('/_dt/')) { socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return; }
42
- const upstream = http.request({ socketPath, path: req.url, headers: headers(req) });
43
- upstream.on('upgrade', (response, peer, peerHead) => {
44
- socket.write(`HTTP/1.1 ${response.statusCode} Switching Protocols\r\n` + Object.entries(response.headers).map(([k,v]) => `${k}: ${v}\r\n`).join('') + '\r\n');
45
- if (peerHead.length) socket.write(peerHead);
46
- if (head.length) peer.write(head);
47
- peer.pipe(socket); socket.pipe(peer);
48
- peer.on('error', () => socket.destroy()); socket.on('error', () => peer.destroy());
49
- socket.on('close', () => peer.destroy()); peer.on('close', () => socket.destroy());
50
- });
51
- upstream.on('response', () => socket.destroy());
52
- upstream.on('error', () => socket.destroy()); upstream.end();
53
- });
54
- await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); });
55
- origin = `http://127.0.0.1:${server.address().port}`;
56
- return { origin, token, link: () => `${origin}/_dt/open?${new URLSearchParams({ token })}`, close: () => new Promise(resolve => { for (const socket of sockets) socket.destroy(); server.close(resolve); }) };
57
- }
package/src/install.mjs DELETED
@@ -1,39 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
- import { createHash } from 'node:crypto';
4
- import { spawn } from 'node:child_process';
5
-
6
- export const CODE_SERVER_VERSION = '4.138.0';
7
- export function run(file, args, opts = {}) {
8
- return new Promise((resolve, reject) => {
9
- const child = spawn(file, args, { stdio: ['ignore', 'inherit', 'inherit'], ...opts });
10
- child.once('error', reject);
11
- child.once('exit', (code, signal) => code === 0 ? resolve() : reject(new Error(`${path.basename(file)} failed (${code ?? signal})`)));
12
- });
13
- }
14
- export async function ensureRuntime(home, explicit) {
15
- if (explicit) return path.resolve(explicit);
16
- if (!['darwin', 'linux'].includes(process.platform) || !['arm64', 'x64'].includes(process.arch)) throw new Error('Supported hosts: macOS and Linux, arm64 or x64.');
17
- const platform = process.platform === 'darwin' ? 'macos' : 'linux';
18
- const arch = process.arch === 'x64' ? 'amd64' : 'arm64';
19
- const name = `code-server-${CODE_SERVER_VERSION}-${platform}-${arch}`;
20
- const executable = path.join(home, name, 'bin/code-server');
21
- try { await fs.access(executable); return executable; } catch {}
22
- console.error(`Installing code-server ${CODE_SERVER_VERSION} for ${platform}/${arch}…`);
23
- const response = await fetch(`https://api.github.com/repos/coder/code-server/releases/tags/v${CODE_SERVER_VERSION}`, { signal: AbortSignal.timeout(30000) });
24
- if (!response.ok) throw new Error(`Release lookup failed: ${response.status}`);
25
- const release = await response.json();
26
- const asset = release.assets?.find(a => a.name === name + '.tar.gz');
27
- if (!asset || !/^sha256:[a-f0-9]{64}$/.test(asset.digest ?? '')) throw new Error('Release has no SHA-256 verified archive for this host. Use --code-server with an installed executable.');
28
- const archive = await fetch(asset.browser_download_url, { signal: AbortSignal.timeout(180000) });
29
- if (!archive.ok) throw new Error(`Download failed: ${archive.status}`);
30
- const bytes = Buffer.from(await archive.arrayBuffer());
31
- if ('sha256:' + createHash('sha256').update(bytes).digest('hex') !== asset.digest) throw new Error('code-server archive checksum mismatch');
32
- const staging = await fs.mkdtemp(path.join(home, '.install-'));
33
- try {
34
- const file = path.join(staging, 'runtime.tgz'); await fs.writeFile(file, bytes, { mode: 0o600 });
35
- await run('tar', ['-xzf', file, '-C', staging]);
36
- await fs.rename(path.join(staging, name), path.join(home, name));
37
- } finally { await fs.rm(staging, { recursive: true, force: true }); }
38
- return executable;
39
- }
package/src/message.mjs DELETED
@@ -1,33 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import { randomUUID } from 'node:crypto';
3
- import readline from 'node:readline';
4
-
5
- // Keep stdin open after the sender's first turn, so its inbox remains available for the reply.
6
- export async function messageCoordinator({ coordinator, text, workspace, timeout = 90000, executable = 'claude' }) {
7
- const requestId = randomUUID();
8
- const child = spawn(executable, ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--tools', 'ListAgents,SendMessage', '--allowedTools', 'ListAgents,SendMessage'], { cwd: workspace, stdio: ['pipe', 'pipe', 'inherit'] });
9
- const instruction = `You relay this user-authorized UI request to the single live session named ${coordinator}. Use ListAgents and SendMessage only. Do not perform the task yourself or message anyone else. Refuse missing or ambiguous targets. Include request ID ${requestId} and ask it to send its completion or failure back to your reply address. Request: ${JSON.stringify(text)}. After successful delivery, end this turn with exactly DELIVERY_PENDING. Do not poll. When the coordinator replies about ${requestId}, report its actual outcome to the user and end with REPLY_RECEIVED. If sending fails, report the failure and end without DELIVERY_PENDING.`;
10
- child.stdin.write(JSON.stringify({ type: 'user', message: { role: 'user', content: instruction } }) + '\n');
11
- let pending = false, replied = false, resultError, exitCode;
12
- const exited = new Promise(resolve => { child.once('error', error => { resultError = error; resolve(); }); child.once('exit', code => { exitCode = code; resolve(); }); });
13
- const timer = setTimeout(() => { resultError = new Error(pending ? 'Delivered, but no coordinator reply arrived before the timeout. Inspect its chat or dt-editor state.' : 'Sender timed out before confirming delivery.'); child.kill('SIGTERM'); }, timeout);
14
- try {
15
- for await (const line of readline.createInterface({ input: child.stdout })) {
16
- let event; try { event = JSON.parse(line); } catch { continue; }
17
- if (event.type !== 'result') continue;
18
- const result = event.result ?? '';
19
- if (result.trim() === 'DELIVERY_PENDING' || (result.includes('DELIVERY_PENDING') && !result.includes('REPLY_RECEIVED'))) {
20
- pending = true; console.error('Delivered; waiting for the coordinator reply…'); continue;
21
- }
22
- console.log(result.replace(/REPLY_RECEIVED\s*$/, '').trim());
23
- replied = result.includes('REPLY_RECEIVED');
24
- if (!replied) resultError = new Error(event.is_error ? 'Sender failed.' : 'No confirmed coordinator reply.');
25
- child.stdin.end();
26
- break;
27
- }
28
- if (replied || resultError) child.kill('SIGTERM');
29
- await exited;
30
- if (resultError) throw resultError;
31
- if (!replied) throw new Error(`Sender exited before a coordinator reply (${exitCode}).`);
32
- } finally { clearTimeout(timer); if (child.exitCode === null) child.kill('SIGTERM'); }
33
- }