slopstream 0.0.0-stage → 0.2.1

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/bridge/cli.js ADDED
@@ -0,0 +1,433 @@
1
+ #!/usr/bin/env node
2
+ // slopstream CLI: setup, pairing (human-approved on BOTH sides), links, unlink, init.
3
+ // Deliberately NOT available to the agent.
4
+
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import readline from 'node:readline';
9
+ import { execSync } from 'node:child_process';
10
+ import { loadConfig, saveConfig, configFile, DEFAULT_RELAY, codexThreadFile, pausedFile, defaultHome } from './config.js';
11
+ import { admin, nextMsg, normCode } from './net.js';
12
+ import { runInit } from './init.js';
13
+ import { runLogin } from './login.js';
14
+ import { httpBase, getJson } from './http.js';
15
+ import { runStatus } from './status.js';
16
+ import { runSimulate } from './simulate.js';
17
+ import { demoUp, demoStatus, demoPeer, demoDown } from './demo.js';
18
+
19
+ const args = process.argv.slice(2);
20
+ const yes = args.includes('--yes');
21
+ const opt = (name) => { const i = args.indexOf(`--${name}`); return i >= 0 && i + 1 < args.length ? args[i + 1] : undefined; };
22
+ const optVals = new Set(['relay', 'agent', 'chat', 'home', 'a', 'b', 'c', 'port', 'dir', 'side', 'linger', 'to', 'relay-data'].map(n => args.indexOf(`--${n}`)).filter(i => i >= 0).map(i => i + 1));
23
+ const pos = args.filter((a, i) => !a.startsWith('--') && !optVals.has(i));
24
+ const [cmd, ...rest] = pos;
25
+ const die = (m) => { console.error(m); process.exit(1); };
26
+
27
+ const ask = (q) => new Promise((res) => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question(q, a => { rl.close(); res(a); }); });
28
+
29
+ // Stops a prompt-injected agent from linking chats on its own: an agent's shell tool has no TTY, a person's terminal does.
30
+ function requireHuman(action) {
31
+ if (process.stdin.isTTY && process.stdout.isTTY) return;
32
+ if (process.env.SLOPSTREAM_ALLOW_NONINTERACTIVE === '1') return; // tests only
33
+ die(`"slopstream ${action}" must be typed by a person in a terminal, not run by an agent or a script.`);
34
+ }
35
+
36
+ // Folder name -> a valid chat label.
37
+ function defaultChat(cwd) {
38
+ return path.basename(cwd).toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '') || 'chat';
39
+ }
40
+
41
+ // Wire this folder up and say what to do next. Called BEFORE waiting, so the folder is ready even if the terminal closes.
42
+ function initFolder(chat) {
43
+ const r = runInit({ chat, agent: opt('agent') || 'claude', cwd: process.cwd(), home: opt('home') });
44
+ console.log(`Set up ${r.agent} in ${process.cwd()}: wrote ${r.written.join(' and ')}`);
45
+ for (const w of r.warnings || []) console.log(`WARNING: ${w}`);
46
+ return r;
47
+ }
48
+ function printStart(r) {
49
+ if (r && r.agent !== 'claude') console.log(r.next.join('\n'));
50
+ else console.log('Start the linked session with:\n claude --dangerously-load-development-channels server:slopstream');
51
+ }
52
+ const peersOf = (members) => members.map(p => `${p.user}/${p.chat}`).join(', ');
53
+ const who = (u) => `@${u.user}${u.github ? ` (github.com/${u.github})` : ''}`;
54
+
55
+ async function ensureLoggedIn(relay) {
56
+ return loadConfig() || await runLogin({ relay });
57
+ }
58
+
59
+ const needCfg = () => loadConfig() || die('Not set up. Run: slopstream login');
60
+
61
+ // The relay writes a pidfile on start (relay/server.js). That is the primary lookup and works on
62
+ // every OS. `pgrep` stays as a Unix-only fallback so a relay started before pidfiles existed, or
63
+ // wrapped in `caffeinate ... node relay/server.js`, is still found.
64
+ function relayPidFiles(relayData) {
65
+ const files = [path.join(os.homedir(), '.slopstream-relay.pid')];
66
+ if (relayData) files.unshift(path.join(relayData, 'relay.pid'));
67
+ if (process.env.DATA_DIR) files.push(path.join(path.resolve(process.env.DATA_DIR), 'relay.pid'));
68
+ return files;
69
+ }
70
+
71
+ function readPidFile(f) {
72
+ try {
73
+ const pid = Number(JSON.parse(fs.readFileSync(f, 'utf8')).pid);
74
+ if (!pid || pid === process.pid) return 0;
75
+ process.kill(pid, 0); // throws if the process is gone, i.e. a stale pidfile
76
+ return pid;
77
+ } catch { return 0; }
78
+ }
79
+
80
+ function findRelayPids(relayData) {
81
+ const pids = new Set();
82
+ for (const f of relayPidFiles(relayData)) { const pid = readPidFile(f); if (pid) pids.add(pid); }
83
+ if (process.platform !== 'win32') {
84
+ try {
85
+ execSync("pgrep -f 'relay/server\\.js'", { encoding: 'utf8' })
86
+ .split('\n').map((s) => Number(s.trim()))
87
+ .filter((pid) => pid && pid !== process.pid)
88
+ .forEach((pid) => pids.add(pid));
89
+ } catch { /* pgrep exits non-zero when nothing matches */ }
90
+ }
91
+ return [...pids];
92
+ }
93
+
94
+ async function stopRunningRelays(relayData) {
95
+ const pids = findRelayPids(relayData);
96
+ if (!pids.length) { console.log('No running relay process found on this machine.'); return; }
97
+ console.log(`Stopping running relay process(es): ${pids.join(', ')}`);
98
+ for (const pid of pids) { try { process.kill(pid, 'SIGTERM'); } catch { /* already gone */ } }
99
+ await new Promise((r) => setTimeout(r, 1500));
100
+ for (const pid of findRelayPids(relayData)) { try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } }
101
+ }
102
+
103
+ function wipeEverything({ home, relayData }) {
104
+ fs.rmSync(home, { recursive: true, force: true });
105
+ fs.rmSync(relayData, { recursive: true, force: true });
106
+ console.log('Done. Everything reset to zero.\nStart fresh with: node relay/admin.js add-user <name>, then slopstream setup ...');
107
+ }
108
+
109
+ async function main() {
110
+ switch (cmd) {
111
+ case 'setup': {
112
+ const [relay, user, token] = rest;
113
+ if (!relay || !user || !token) die('usage: slopstream setup <relay-url e.g. wss://host or ws://127.0.0.1:8787> <user> <token>');
114
+ const cfg = { relay, user, token };
115
+ const ws = await admin(cfg); ws.close();
116
+ saveConfig(cfg);
117
+ console.log(`OK. Authenticated as "${user}". Saved to ${configFile()}`);
118
+ break;
119
+ }
120
+ case 'link': {
121
+ requireHuman('link');
122
+ const cfg = await ensureLoggedIn(DEFAULT_RELAY);
123
+ const chat = rest[0] || defaultChat(process.cwd());
124
+ console.log(`Chat label: ${chat}`);
125
+ const ws = await admin(cfg);
126
+ ws.send(JSON.stringify({ t: 'list_links' }));
127
+ const { links } = await nextMsg(ws, ['links'], 5000);
128
+ const mineLink = links.find(l => l.members.some(m => m.user === cfg.user && m.chat === chat));
129
+ const add = args.includes('--add');
130
+ if (mineLink && !add) {
131
+ const peers = peersOf(mineLink.members.filter(m => !(m.user === cfg.user && m.chat === chat)));
132
+ die(`"${chat}" is already linked with ${peers}. To add another person to that group, run: slopstream link --add`);
133
+ }
134
+ const init = args.includes('--no-init') ? null : initFolder(chat);
135
+ ws.send(JSON.stringify({ t: add ? 'invite_create' : 'pair_create', chat }));
136
+ const c = await nextMsg(ws, ['pair_code']);
137
+ const mine = (m) => normCode(m.code) === normCode(c.code);
138
+ const until = new Date(Date.now() + c.expiresInSec * 1000).toLocaleString();
139
+ console.log(`\nSend this to your teammate:\n\n Link our agents: ${c.url || c.code}\n\n(valid for ${Math.round(c.expiresInSec / 3600)} hours, works once). Waiting for them to join... (Ctrl+C is fine; approve later with: slopstream requests)`);
140
+ const stays = () => { console.log(`\nThe invite stays valid until ${until}. When someone uses it, approve with: slopstream requests`); process.exit(0); };
141
+ process.on('SIGINT', stays); ws.on('close', stays);
142
+ const req = await nextMsg(ws, ['pair_request'], 0, mine);
143
+ console.log(`\n${who(req.from)} wants to link their chat "${req.from.chat}" with your chat "${chat}".`);
144
+ const ok = yes || /^y(es)?$/i.test((await ask('Approve? [y/N] ')).trim());
145
+ ws.send(JSON.stringify({ t: 'pair_decision', code: req.code, ok }));
146
+ const r = await nextMsg(ws, ['paired', 'pair_denied'], 0, mine);
147
+ ws.off('close', stays); process.off('SIGINT', stays);
148
+ if (r.t === 'paired') { console.log(`Linked! ${chat} <-> ${peersOf(r.members)}`); printStart(init); } else console.log('Denied.');
149
+ ws.close(); break;
150
+ }
151
+ case 'join': {
152
+ requireHuman('join');
153
+ const input = rest[0]; if (!input) die('usage: slopstream join <code-or-link> [chat-label]');
154
+ let relayFromUrl = null; let code;
155
+ if (/^https?:\/\//.test(input)) {
156
+ const u = new URL(input);
157
+ relayFromUrl = (u.protocol === 'https:' ? 'wss://' : 'ws://') + u.host;
158
+ code = normCode(u.pathname.split('/j/')[1] || '');
159
+ } else code = normCode(input);
160
+ if (!code) die('That does not look like an invite code or link.');
161
+ let cfg = loadConfig();
162
+ if (cfg && relayFromUrl && httpBase(cfg.relay) !== httpBase(relayFromUrl)) {
163
+ die(`This invite is for ${relayFromUrl} but you're logged in to ${cfg.relay}. Run: slopstream logout, then try again.`);
164
+ }
165
+ cfg = cfg || await runLogin({ relay: relayFromUrl || DEFAULT_RELAY });
166
+ const inv = await getJson(`${httpBase(cfg.relay)}/v1/invite/${code}`);
167
+ if (inv.status === 'used') die('That invite was already used. Ask for a new one.');
168
+ if (inv.status !== 'open') die('That invite is unknown or has expired. Ask for a new one.');
169
+ const chat = rest[1] || defaultChat(process.cwd());
170
+ console.log(`Link this folder (chat "${chat}") with @${inv.inviter}'s chat "${inv.chat}"?\nTheir agent will be able to send messages here; you approve each one.`);
171
+ if (!yes && !/^y(es)?$/i.test((await ask('[y/N] ')).trim())) die('Cancelled.');
172
+ const init = args.includes('--no-init') ? null : initFolder(chat);
173
+ const ws = await admin(cfg);
174
+ ws.send(JSON.stringify({ t: 'pair_accept', code, chat }));
175
+ await nextMsg(ws, ['pair_waiting'], 5000);
176
+ console.log(`Waiting for @${inv.inviter} to approve... (you can close this; check later with: slopstream links)`);
177
+ const r = await nextMsg(ws, ['paired', 'pair_denied'], 0, (m) => normCode(m.code) === code);
178
+ if (r.t === 'paired') { console.log(`Linked! ${chat} <-> ${peersOf(r.members)}`); printStart(init); } else console.log('Denied by the other side.');
179
+ ws.close(); break;
180
+ }
181
+ case 'login': {
182
+ await runLogin({ relay: opt('relay') });
183
+ break;
184
+ }
185
+ case 'whoami': {
186
+ const cfg = needCfg();
187
+ console.log(`${cfg.user} on ${cfg.relay}`);
188
+ try { (await admin(cfg)).close(); console.log('✓ login works'); }
189
+ catch (e) { console.error(`✗ ${e.message}`); process.exit(1); }
190
+ break;
191
+ }
192
+ case 'devices': {
193
+ const cfg = needCfg(); const ws = await admin(cfg);
194
+ if (rest[0] === 'revoke') {
195
+ if (!rest[1]) die('usage: slopstream devices revoke <id-prefix>');
196
+ ws.send(JSON.stringify({ t: 'device_list' }));
197
+ const { devices } = await nextMsg(ws, ['devices'], 5000);
198
+ const hits = devices.filter(d => d.id.startsWith(rest[1]));
199
+ if (hits.length !== 1) die(hits.length ? 'that prefix matches more than one device; use more characters' : 'no device with that id');
200
+ ws.send(JSON.stringify({ t: 'device_revoke', id: hits[0].id }));
201
+ await nextMsg(ws, ['device_revoked'], 5000);
202
+ console.log(`Revoked ${hits[0].label} (${hits[0].id.slice(0, 8)}).`);
203
+ } else {
204
+ ws.send(JSON.stringify({ t: 'device_list' }));
205
+ const { devices } = await nextMsg(ws, ['devices'], 5000);
206
+ if (!devices.length) console.log('(no devices; this login uses a legacy token)');
207
+ for (const d of devices) console.log(`${d.id.slice(0, 8)} ${d.label.padEnd(30)} last seen ${new Date(d.lastSeenAt).toLocaleString()}${d.current ? ' (this device)' : ''}`);
208
+ }
209
+ ws.close(); break;
210
+ }
211
+ case 'logout': {
212
+ const cfg = loadConfig();
213
+ if (cfg && cfg.auth === 'github' && cfg.deviceId) {
214
+ try { const ws = await admin(cfg); ws.send(JSON.stringify({ t: 'device_revoke', id: cfg.deviceId })); await nextMsg(ws, ['device_revoked'], 3000).catch(() => {}); ws.close(); } catch { /* relay unreachable: still log out locally */ }
215
+ }
216
+ fs.rmSync(configFile(), { force: true });
217
+ console.log('Logged out.');
218
+ break;
219
+ }
220
+ case 'pair-create':
221
+ case 'invite': {
222
+ requireHuman(cmd);
223
+ // pair-create makes a NEW link; invite adds a person to a chat that is ALREADY linked (up to the relay's group limit).
224
+ const isInvite = cmd === 'invite';
225
+ const chat = rest[0];
226
+ if (!chat) die(isInvite ? 'usage: slopstream invite <chat-label> [--yes] (that chat must already be linked)' : 'usage: slopstream pair-create <chat-label> [--yes]');
227
+ const ws = await admin(needCfg());
228
+ ws.send(JSON.stringify({ t: isInvite ? 'invite_create' : 'pair_create', chat }));
229
+ const c = await nextMsg(ws, ['pair_code']);
230
+ const mine = (m) => normCode(m.code) === normCode(c.code);
231
+ const until = new Date(Date.now() + c.expiresInSec * 1000).toLocaleString();
232
+ console.log(`\n${isInvite ? 'Invite' : 'Pairing'} code for chat "${chat}": ${c.code} (valid until ${until})`);
233
+ if (c.url) console.log(`Link to send: ${c.url}`);
234
+ console.log(`They run: slopstream pair-accept ${c.code} <their-chat-label>\nWaiting...`);
235
+ const stays = () => { console.log(`\nThe invite stays valid until ${until}. When someone uses it, approve with: slopstream requests`); process.exit(0); };
236
+ process.on('SIGINT', stays);
237
+ ws.on('close', stays);
238
+ const req = await nextMsg(ws, ['pair_request'], 0, mine);
239
+ console.log(`\n${req.from.user}${req.from.github ? ` (github.com/${req.from.github})` : ''} wants to ${isInvite ? `join "${chat}"` : `link their chat "${req.from.chat}" to your chat "${chat}"`}${isInvite ? ` (their chat label: "${req.from.chat}")` : ''}.`);
240
+ const ok = yes || /^y(es)?$/i.test((await ask('Approve? [y/N] ')).trim());
241
+ ws.send(JSON.stringify({ t: 'pair_decision', code: req.code, ok }));
242
+ const r = await nextMsg(ws, ['paired', 'pair_denied'], 0, mine);
243
+ console.log(r.t === 'paired' ? `Linked: ${chat} <-> ${r.members.map(p => `${p.user}/${p.chat}`).join(', ')}` : 'Denied.');
244
+ ws.off('close', stays); process.off('SIGINT', stays);
245
+ ws.close(); break;
246
+ }
247
+ case 'pair-accept': {
248
+ requireHuman(cmd);
249
+ const [code, chat] = rest; if (!code || !chat) die('usage: slopstream pair-accept <code> <chat-label>');
250
+ const ws = await admin(needCfg());
251
+ ws.send(JSON.stringify({ t: 'pair_accept', code, chat }));
252
+ const w = await nextMsg(ws, ['pair_waiting']);
253
+ console.log(`${w.message.charAt(0).toUpperCase()}${w.message.slice(1)}. You can close this; once approved the link appears in: slopstream links`);
254
+ const r = await nextMsg(ws, ['paired', 'pair_denied'], 0, (m) => normCode(m.code) === normCode(code));
255
+ console.log(r.t === 'paired' ? `Linked: ${chat} <-> ${r.members.map(p => `${p.user}/${p.chat}`).join(', ')}` : 'Denied by the other side.');
256
+ ws.close(); break;
257
+ }
258
+ case 'requests': {
259
+ const ws = await admin(needCfg());
260
+ ws.send(JSON.stringify({ t: 'list_requests' }));
261
+ const { invites } = await nextMsg(ws, ['requests'], 5000);
262
+ if (!invites.length) console.log('No open invites.');
263
+ for (const v of invites) {
264
+ const r = v.requester;
265
+ console.log(`${v.code} ${v.kind} chat "${v.chat}" expires ${new Date(v.expiresAt).toLocaleString()} ` +
266
+ (r ? `REQUEST from ${r.user}${r.github ? ` (github.com/${r.github})` : ''} (chat "${r.chat}") -> slopstream approve ${v.code}` : 'unused'));
267
+ }
268
+ ws.close(); break;
269
+ }
270
+ case 'approve':
271
+ case 'deny': {
272
+ if (cmd === 'approve') requireHuman(cmd);
273
+ const code = rest[0]; if (!code) die(`usage: slopstream ${cmd} <code>${cmd === 'approve' ? ' [--yes]' : ''}`);
274
+ const ws = await admin(needCfg());
275
+ ws.send(JSON.stringify({ t: 'list_requests' }));
276
+ const { invites } = await nextMsg(ws, ['requests'], 5000);
277
+ const v = invites.find(x => normCode(x.code) === normCode(code));
278
+ if (!v || !v.requester) die(v ? `Nobody has used invite ${v.code} yet.` : `No open invite ${code}.`);
279
+ let ok = false;
280
+ if (cmd === 'approve') {
281
+ const r = v.requester;
282
+ console.log(`${r.user}${r.github ? ` (github.com/${r.github})` : ''} wants to link their chat "${r.chat}" with your chat "${v.chat}".`);
283
+ ok = yes || /^y(es)?$/i.test((await ask('Approve? [y/N] ')).trim());
284
+ }
285
+ const mine = (m) => normCode(m.code) === normCode(v.code);
286
+ const done = nextMsg(ws, ['paired', 'pair_denied'], 5000, mine);
287
+ ws.send(JSON.stringify({ t: 'pair_decision', code: v.code, ok }));
288
+ const r = await done;
289
+ console.log(r.t === 'paired' ? `Linked: ${v.chat} <-> ${r.members.map(p => `${p.user}/${p.chat}`).join(', ')}` : 'Denied.');
290
+ ws.close(); break;
291
+ }
292
+ case 'cancel': {
293
+ const code = rest[0]; if (!code) die('usage: slopstream cancel <code>');
294
+ const ws = await admin(needCfg());
295
+ ws.send(JSON.stringify({ t: 'invite_cancel', code }));
296
+ const r = await nextMsg(ws, ['invite_cancelled'], 5000);
297
+ console.log(`Cancelled invite ${r.code}.`);
298
+ ws.close(); break;
299
+ }
300
+ case 'links': {
301
+ const cfg = needCfg(); const ws = await admin(cfg);
302
+ ws.send(JSON.stringify({ t: 'list_links' }));
303
+ const r = await nextMsg(ws, ['links']);
304
+ if (!r.links.length) console.log('(no links)');
305
+ for (const l of r.links) {
306
+ const mine = l.members.find(m => m.user === cfg.user);
307
+ const others = l.members.filter(m => m !== mine);
308
+ const peers = others.map(o => `${o.user}/${o.chat}${o.online ? ' (online)' : ''}`).join(', ');
309
+ console.log(`${mine.chat} <-> ${peers} (since ${l.createdAt})`);
310
+ }
311
+ ws.close(); break;
312
+ }
313
+ case 'unlink': {
314
+ const chat = rest[0]; if (!chat) die('usage: slopstream unlink <chat-label>');
315
+ const ws = await admin(needCfg());
316
+ ws.send(JSON.stringify({ t: 'unlink', chat }));
317
+ await nextMsg(ws, ['unlinked_ok']); console.log(`Unlinked "${chat}".`); ws.close(); break;
318
+ }
319
+ case 'pause': {
320
+ // Local-only: makes the bridge refuse to connect to the relay for this chat, so nobody can reach it,
321
+ // without touching the link itself. Takes effect the next time a session for this chat starts.
322
+ const chat = rest[0]; if (!chat) die('usage: slopstream pause <chat-label>');
323
+ const f = pausedFile(chat); fs.mkdirSync(path.dirname(f), { recursive: true, mode: 0o700 });
324
+ fs.writeFileSync(f, JSON.stringify({ pausedAt: new Date().toISOString() }), { mode: 0o600 });
325
+ console.log(`Paused "${chat}". Restart any Claude/Codex session using it for this to take effect.\nNobody can reach it until you run: slopstream resume ${chat}`);
326
+ break;
327
+ }
328
+ case 'resume': {
329
+ const chat = rest[0]; if (!chat) die('usage: slopstream resume <chat-label>');
330
+ fs.rmSync(pausedFile(chat), { force: true });
331
+ console.log(`Resumed "${chat}". Restart any Claude/Codex session using it to reconnect.`);
332
+ break;
333
+ }
334
+ case 'init': {
335
+ const chat = rest[0]; if (!chat) die('usage: slopstream init <chat-label> [--agent claude|codex] (run inside the project folder)');
336
+ const r = runInit({ chat, agent: opt('agent') || 'claude', cwd: process.cwd(), home: opt('home') });
337
+ console.log(`Set up ${r.agent} in ${process.cwd()}: wrote ${r.written.join(' and ')}`);
338
+ for (const w of r.warnings || []) console.log(`WARNING: ${w}`);
339
+ if (r.agent === 'claude') console.log('Start the linked session with:\n claude --dangerously-load-development-channels server:slopstream');
340
+ else console.log(r.next.join('\n'));
341
+ break;
342
+ }
343
+ case 'codex-hook': {
344
+ // Called BY CODEX (SessionStart hook), never by a person. Records which Codex chat this folder is.
345
+ // Must never fail loudly or print anything: a broken hook should not disturb the chat.
346
+ try {
347
+ const chat = opt('chat'); const home = opt('home');
348
+ let raw = ''; for await (const c of process.stdin) raw += c;
349
+ const j = JSON.parse(raw);
350
+ const id = String(j.session_id || j.thread_id || '');
351
+ if (chat && /^[0-9a-zA-Z-]{8,64}$/.test(id)) {
352
+ const f = codexThreadFile(chat, home || undefined);
353
+ fs.mkdirSync(path.dirname(f), { recursive: true, mode: 0o700 });
354
+ fs.writeFileSync(f, JSON.stringify({ thread: id, ts: Date.now() }), { mode: 0o600 });
355
+ }
356
+ } catch { /* silent */ }
357
+ break;
358
+ }
359
+ case 'force-clean':
360
+ case 'force-stop-clean': {
361
+ // Nukes everything back to zero: this machine's saved login/pauses/logs, AND the relay's
362
+ // users/links/audit log. Does NOT touch the npm link (the `slopstream` command stays installed).
363
+ // force-stop-clean additionally finds and kills any running relay/server.js process first.
364
+ const stopFirst = cmd === 'force-stop-clean';
365
+ const home = opt('home') ? path.resolve(opt('home')) : defaultHome();
366
+ const relayData = opt('relay-data')
367
+ ? path.resolve(opt('relay-data'))
368
+ : (process.env.DATA_DIR ? path.resolve(process.env.DATA_DIR) : path.join(os.homedir(), '.slopstream-relay'));
369
+ console.log(`This will PERMANENTLY delete:
370
+ - this machine's saved login, pauses and logs: ${home}
371
+ - the relay's data (ALL users, ALL links, audit log): ${relayData}
372
+
373
+ The "slopstream" command itself (the npm link) is NOT removed.`);
374
+ console.log(stopFirst
375
+ ? 'Any running relay process on this machine will be stopped first.'
376
+ : "If the relay is running, stop it first (Ctrl+C) -- deleting its data while it's running can corrupt it.\n(Or run slopstream force-stop-clean to have this done for you.)");
377
+ const ok = yes || /^yes$/i.test((await ask('Type "yes" to continue: ')).trim());
378
+ if (!ok) { console.log('Aborted. Nothing was deleted.'); break; }
379
+ if (stopFirst) await stopRunningRelays(relayData);
380
+ wipeEverything({ home, relayData });
381
+ break;
382
+ }
383
+ case 'status': process.exitCode = await runStatus(); break;
384
+ case 'simulate': {
385
+ const chat = opt('chat'); if (!chat) die('usage: slopstream simulate --chat <chat-label> [--agent claude|codex]');
386
+ if (opt('home')) process.env.SLOPSTREAM_HOME = path.resolve(opt('home'));
387
+ await runSimulate({ chat, agent: opt('agent') || 'claude', linger: opt('linger') !== undefined ? Number(opt('linger')) : undefined });
388
+ return new Promise(() => {}); // runSimulate exits the process itself
389
+ }
390
+ case 'demo': {
391
+ const sub = rest[0];
392
+ if (sub === 'up') await demoUp({ dir: opt('dir'), a: opt('a') || 'claude', b: opt('b') || 'claude', c: opt('c'), port: opt('port') ? Number(opt('port')) : 18787 });
393
+ else if (sub === 'status') process.exitCode = await demoStatus();
394
+ else if (sub === 'down') demoDown();
395
+ else if (sub === 'peer') { await demoPeer({ side: opt('side'), agent: opt('agent'), linger: opt('linger') !== undefined ? Number(opt('linger')) : undefined }); return new Promise(() => {}); }
396
+ else die('usage: slopstream demo up [--a claude|codex] [--b claude|codex] [--c claude|codex] [--port N]\n slopstream demo status | down\n slopstream demo peer --side a|b|c');
397
+ break;
398
+ }
399
+ default:
400
+ console.log(`slopstream: your agent can ask mine.
401
+
402
+ usage: slopstream <command>
403
+ link [chat] [--agent claude|codex] [--add] make an invite link for this folder and wait for your teammate
404
+ join <code-or-link> [chat] link this folder to a teammate's invite
405
+ login [--relay <url>] log in with GitHub (once per machine)
406
+ whoami show who you are logged in as and check it works
407
+ devices [revoke <id>] list (or revoke) the devices logged in as you
408
+ logout revoke this device and forget the login
409
+ setup <relay-url> <user> <token> save credentials of a self-hosted relay (once per machine)
410
+ pair-create <chat> [--yes] make a pairing code for a chat, wait for teammate, approve
411
+ pair-accept <code> <chat> accept a teammate's code for one of your chats
412
+ invite <chat> [--yes] add another person to a chat that is ALREADY linked (up to the relay's group limit)
413
+ requests list your open invites and who has used them
414
+ approve <code> [--yes] approve someone who used your invite (also works later, after you closed pair-create)
415
+ deny <code> refuse such a request
416
+ cancel <code> cancel an open invite
417
+ links list your links (and who else is in each group)
418
+ unlink <chat> leave a link; dissolves it if fewer than 2 chats would remain
419
+ pause <chat> stop a chat connecting to the relay, without unlinking it
420
+ resume <chat> undo pause
421
+ force-clean [--yes] [--relay-data <dir>] [--home <dir>]
422
+ DANGER: wipe this machine's login/pauses/logs AND the relay's
423
+ users/links/audit log back to zero. Keeps the npm link.
424
+ force-stop-clean [--yes] [--relay-data <dir>] [--home <dir>]
425
+ same as force-clean, but first finds and kills any running
426
+ relay/server.js process on this machine.
427
+ init <chat> [--agent claude|codex] (in a project folder) wire this folder up for Claude Code or Codex
428
+ status is this machine ready? who is online?
429
+ demo up|status|peer|down test everything on THIS machine alone (see docs/testing.md)
430
+ simulate --chat <chat> [--agent] stand-in agent with no AI, for testing the plumbing`);
431
+ }
432
+ }
433
+ main().then(() => process.exit(process.exitCode || 0)).catch((e) => die(`error: ${e.message}`));
@@ -0,0 +1,28 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+
5
+ // Every function takes an optional `home` so one machine can host several independent
6
+ // identities (that is how the solo `slopstream demo` works). Default: $SLOPSTREAM_HOME or ~/.slopstream.
7
+ export const defaultHome = () => process.env.SLOPSTREAM_HOME || path.join(os.homedir(), '.slopstream');
8
+ export const configFile = (home = defaultHome()) => path.join(home, 'config.json');
9
+ export const logFile = (home = defaultHome()) => path.join(home, 'log.jsonl');
10
+ export const codexThreadFile = (chat, home = defaultHome()) => path.join(home, 'codex-threads', `${chat}.json`);
11
+ export const pausedFile = (chat, home = defaultHome()) => path.join(home, 'paused', `${chat}.json`);
12
+
13
+ export function loadConfig(home = defaultHome()) {
14
+ try { return JSON.parse(fs.readFileSync(configFile(home), 'utf8')); } catch { return null; }
15
+ }
16
+ export function saveConfig(cfg, home = defaultHome()) {
17
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
18
+ fs.writeFileSync(configFile(home), JSON.stringify(cfg, null, 2), { mode: 0o600 });
19
+ }
20
+ export function logLine(obj, home = defaultHome()) {
21
+ try {
22
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
23
+ fs.appendFileSync(logFile(home), JSON.stringify({ ts: new Date().toISOString(), ...obj }) + '\n', { mode: 0o600 });
24
+ } catch { /* logging must never break the bridge */ }
25
+ }
26
+
27
+ // Where `slopstream login` goes when nothing else says otherwise. (The hosted relay.)
28
+ export const DEFAULT_RELAY = process.env.SLOPSTREAM_RELAY || 'wss://slopstream-relay.slopstream.workers.dev';
package/bridge/demo.js ADDED
@@ -0,0 +1,146 @@
1
+ // `slopstream demo up|status|peer|down`: a complete two-person test on THIS laptop.
2
+ // - a private relay on 127.0.0.1 running in the background (no network setup, no second person)
3
+ // - two fake people, "demo-a" and "demo-b", each with their own settings folder
4
+ // - one link between them (chat label "demo")
5
+ // - two project folders, each wired up for an agent (claude or codex)
6
+ import { spawn, spawnSync } from 'node:child_process';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import WebSocket from 'ws';
12
+ import { saveConfig, loadConfig } from './config.js';
13
+ import { pairBoth, inviteAndAccept, listLinks } from './net.js';
14
+ import { runInit } from './init.js';
15
+ import { runSimulate } from './simulate.js';
16
+
17
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
18
+ const ROOT = path.resolve(HERE, '..');
19
+ const RELAY = path.join(ROOT, 'relay', 'server.js');
20
+ const ADMIN = path.join(ROOT, 'relay', 'admin.js');
21
+ const MARK = '.slopstream-demo';
22
+ const CHAT = 'demo';
23
+ const AGENTS = ['claude', 'codex'];
24
+ const defaultDir = () => path.join(os.homedir(), '.slopstream-demo');
25
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } };
26
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
27
+
28
+ const paths = (dir) => ({
29
+ dir, state: path.join(dir, 'demo.json'), relayData: path.join(dir, 'relay-data'), relayLog: path.join(dir, 'relay.log'),
30
+ homeA: path.join(dir, 'home-a'), homeB: path.join(dir, 'home-b'), homeC: path.join(dir, 'home-c'),
31
+ a: path.join(dir, 'folder-a'), b: path.join(dir, 'folder-b'), c: path.join(dir, 'folder-c'),
32
+ });
33
+ const readState = (P) => { try { return JSON.parse(fs.readFileSync(P.state, 'utf8')); } catch { return null; } };
34
+
35
+ async function waitForRelay(url, ms = 8000) {
36
+ const t0 = Date.now();
37
+ while (Date.now() - t0 < ms) {
38
+ const ok = await new Promise((res) => { const ws = new WebSocket(url); ws.once('open', () => { ws.close(); res(true); }); ws.once('error', () => res(false)); });
39
+ if (ok) return true;
40
+ await sleep(150);
41
+ }
42
+ return false;
43
+ }
44
+
45
+ const launchLine = (agent, folder) => agent === 'claude'
46
+ ? `cd ${folder} && claude --dangerously-load-development-channels server:slopstream`
47
+ : `cd ${folder} && codex`;
48
+
49
+ export async function demoUp({ dir, a = 'claude', b = 'claude', c, port = 18787, bin = 'slopstream' }) {
50
+ const group = [a, b, ...(c ? [c] : [])];
51
+ for (const x of group) if (!AGENTS.includes(x)) throw new Error(`agent must be "claude" or "codex" (got "${x}")`);
52
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error('--port must be a number between 1024 and 65535');
53
+ const P = paths(path.resolve(dir || defaultDir()));
54
+ const old = readState(P);
55
+ if (old && alive(old.pid)) throw new Error(`a demo relay is already running (pid ${old.pid}). Run \`${bin} demo down\` first.`);
56
+ if (fs.existsSync(P.dir)) {
57
+ if (fs.existsSync(path.join(P.dir, MARK))) fs.rmSync(P.dir, { recursive: true, force: true });
58
+ else if (fs.readdirSync(P.dir).length) throw new Error(`${P.dir} already exists and is not a slopstream demo folder. Pick another with --dir.`);
59
+ }
60
+ const dirs = [P.relayData, P.homeA, P.homeB, P.a, P.b, ...(c ? [P.homeC, P.c] : [])];
61
+ for (const p of dirs) fs.mkdirSync(p, { recursive: true });
62
+ fs.writeFileSync(path.join(P.dir, MARK), 'created by `slopstream demo`; safe to delete\n');
63
+
64
+ const log = fs.openSync(P.relayLog, 'a');
65
+ const relay = spawn(process.execPath, [RELAY], {
66
+ env: { ...process.env, HOST: '127.0.0.1', PORT: String(port), DATA_DIR: P.relayData },
67
+ detached: true, stdio: ['ignore', log, log],
68
+ });
69
+ relay.unref();
70
+ const url = `ws://127.0.0.1:${port}`;
71
+ if (!(await waitForRelay(url))) {
72
+ try { process.kill(relay.pid); } catch {}
73
+ const txt = fs.readFileSync(P.relayLog, 'utf8');
74
+ throw new Error(`the demo relay did not start. ${/EADDRINUSE/.test(txt) ? `Port ${port} is busy: try --port ${port + 1}` : txt.trim().slice(-300)}`);
75
+ }
76
+ try {
77
+ const token = (name) => {
78
+ const r = spawnSync(process.execPath, [ADMIN, 'add-user', name], { encoding: 'utf8', env: { ...process.env, DATA_DIR: P.relayData } });
79
+ const m = (r.stdout || '').match(/token: (\S+)/); if (!m) throw new Error(`could not create user ${name}: ${r.stderr}`);
80
+ return m[1];
81
+ };
82
+ const cfgA = { relay: url, user: 'demo-a', token: token('demo-a') };
83
+ const cfgB = { relay: url, user: 'demo-b', token: token('demo-b') };
84
+ saveConfig(cfgA, P.homeA); saveConfig(cfgB, P.homeB);
85
+ await pairBoth(cfgA, CHAT, cfgB, CHAT);
86
+ runInit({ chat: CHAT, agent: a, cwd: P.a, home: P.homeA });
87
+ runInit({ chat: CHAT, agent: b, cwd: P.b, home: P.homeB });
88
+ if (c) {
89
+ const cfgC = { relay: url, user: 'demo-c', token: token('demo-c') };
90
+ saveConfig(cfgC, P.homeC);
91
+ await inviteAndAccept(cfgA, CHAT, cfgC, CHAT);
92
+ runInit({ chat: CHAT, agent: c, cwd: P.c, home: P.homeC });
93
+ }
94
+ fs.writeFileSync(P.state, JSON.stringify({ pid: relay.pid, port, a, b, c: c || null }, null, 2));
95
+ } catch (e) { try { process.kill(relay.pid); } catch {} throw e; }
96
+
97
+ console.log(`
98
+ DEMO READY. ${c ? 'Three' : 'Two'} fake people now share this laptop, linked chat-to-chat:
99
+ person A ${a.padEnd(6)} folder ${P.a}
100
+ person B ${b.padEnd(6)} folder ${P.b}${c ? `\n person C ${c.padEnd(6)} folder ${P.c}` : ''}
101
+ The relay runs in the background (pid ${relay.pid}, port ${port}). Stop it with: ${bin} demo down
102
+
103
+ Test with no AI at all (free, tests the plumbing). ${c ? 'Three' : 'Two'} new terminals:
104
+ ${bin} demo peer --side a
105
+ ${bin} demo peer --side b${c ? `\n ${bin} demo peer --side c` : ''}
106
+ Type a line in one and press Enter; it arrives in the other(s).${c ? ' In a 3-way group, use "@demo-b message" / "@demo-c message" to pick a target.' : ''}
107
+
108
+ Test with the real agents. ${c ? 'Three' : 'Two'} new terminals:
109
+ ${launchLine(a, P.a)}
110
+ ${launchLine(b, P.b)}${c ? `\n ${launchLine(c, P.c)}` : ''}
111
+ Check who is online any time: ${bin} demo status`);
112
+ }
113
+
114
+ export async function demoStatus() {
115
+ const P = paths(defaultDir()); const st = readState(P);
116
+ if (!st) { console.log('no demo. Start one with: slopstream demo up'); return 0; }
117
+ const up = alive(st.pid);
118
+ console.log(`demo relay: ${up ? `running (pid ${st.pid}, port ${st.port})` : 'NOT running. Run `slopstream demo up` again'}`);
119
+ if (!up) return 1;
120
+ const cfg = loadConfig(P.homeA);
121
+ let links;
122
+ try { links = await listLinks(cfg); } catch { console.log(' the relay is not answering. Run `slopstream demo down` then `slopstream demo up`.'); return 1; }
123
+ const label = { 'demo-a': 'person A', 'demo-b': 'person B', 'demo-c': 'person C' };
124
+ for (const l of links) {
125
+ const names = l.members.map(m => `${label[m.user] || m.user} (${m.user === 'demo-a' ? st.a : m.user === 'demo-b' ? st.b : st.c}) ${m.online ? 'ONLINE' : 'offline'}`);
126
+ console.log(` chat "${l.members[0].chat}": ${names.join(' <-> ')}`);
127
+ }
128
+ return 0;
129
+ }
130
+
131
+ export async function demoPeer({ side, agent, linger }) {
132
+ const P = paths(defaultDir()); const st = readState(P);
133
+ if (!st || !alive(st.pid)) throw new Error('no demo relay is running. Run: slopstream demo up');
134
+ const sides = st.c ? ['a', 'b', 'c'] : ['a', 'b'];
135
+ if (!sides.includes(side)) throw new Error(`--side must be ${sides.join(' or ')}`);
136
+ process.env.SLOPSTREAM_HOME = side === 'a' ? P.homeA : side === 'b' ? P.homeB : P.homeC;
137
+ return runSimulate({ chat: CHAT, agent: agent || st[side], linger });
138
+ }
139
+
140
+ export function demoDown() {
141
+ const P = paths(defaultDir()); const st = readState(P);
142
+ if (!st) { console.log('no demo to stop.'); return; }
143
+ if (alive(st.pid)) { try { process.kill(st.pid, 'SIGTERM'); } catch {} console.log(`stopped the demo relay (pid ${st.pid}).`); fs.rmSync(P.state, { force: true }); }
144
+ else console.log('the demo relay was already stopped.');
145
+ console.log(`Files are kept in ${P.dir} (delete that folder when you're finished).`);
146
+ }