ai-agentmanager 0.0.0-stage → 1.0.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.
Files changed (58) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +767 -2
  4. package/SECURITY.md +44 -0
  5. package/bin/agentmgr-hub.js +16 -0
  6. package/bin/agentmgr.js +4 -0
  7. package/docs/architecture.md +67 -0
  8. package/docs/distributed.md +147 -0
  9. package/docs/engines.md +177 -0
  10. package/docs/images/agents.jpg +0 -0
  11. package/docs/images/conflict-radar.jpg +0 -0
  12. package/docs/plugins.md +81 -0
  13. package/package.json +56 -4
  14. package/public/app.js +3083 -0
  15. package/public/hub/hub.css +230 -0
  16. package/public/hub/hub.js +766 -0
  17. package/public/hub/index.html +146 -0
  18. package/public/hub/term.js +147 -0
  19. package/public/index.html +342 -0
  20. package/public/share.html +34 -0
  21. package/public/share.js +41 -0
  22. package/public/style.css +541 -0
  23. package/public/touchscroll.js +73 -0
  24. package/public/transport.js +78 -0
  25. package/scripts/build-release.sh +58 -0
  26. package/scripts/fix-pty.js +15 -0
  27. package/src/backlog.js +413 -0
  28. package/src/brief.js +512 -0
  29. package/src/cli.js +1447 -0
  30. package/src/client.js +49 -0
  31. package/src/config.js +109 -0
  32. package/src/conflicts.js +105 -0
  33. package/src/engines/antigravity.js +296 -0
  34. package/src/engines/claude.js +98 -0
  35. package/src/engines/codex.js +331 -0
  36. package/src/engines/index.js +37 -0
  37. package/src/fleet.js +176 -0
  38. package/src/git.js +340 -0
  39. package/src/hub.js +857 -0
  40. package/src/hubactions.js +107 -0
  41. package/src/hubbacklog.js +373 -0
  42. package/src/hublink.js +437 -0
  43. package/src/inbox.js +94 -0
  44. package/src/judge.js +278 -0
  45. package/src/livebrowser.js +637 -0
  46. package/src/manager.js +2554 -0
  47. package/src/notify.js +284 -0
  48. package/src/plugins.js +119 -0
  49. package/src/preview.js +334 -0
  50. package/src/races.js +192 -0
  51. package/src/remote.js +284 -0
  52. package/src/server.js +759 -0
  53. package/src/service.js +150 -0
  54. package/src/sessions.js +160 -0
  55. package/src/store.js +104 -0
  56. package/src/stuck.js +160 -0
  57. package/src/tracker.js +311 -0
  58. package/src/trust.js +44 -0
package/src/remote.js ADDED
@@ -0,0 +1,284 @@
1
+ // Remote (phone) access: an opt-in HTTPS listener on the local network with
2
+ // token login. Everything here is local state under ~/.agentmanager/remote/.
3
+ import crypto from 'node:crypto';
4
+ import { execFile } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import QRCode from 'qrcode';
9
+ import { paths, PORT } from './config.js';
10
+
11
+ const DIR = path.join(paths.home, 'remote');
12
+ const STATE = path.join(DIR, 'state.json');
13
+ const KEY = path.join(DIR, 'key.pem');
14
+ const CERT = path.join(DIR, 'cert.pem');
15
+ export const SESSION_COOKIE = 'agentmgr_session';
16
+ const SESSION_DAYS = 30;
17
+
18
+ const sha256 = (s) => crypto.createHash('sha256').update(s).digest('hex');
19
+ const newSecret = () => crypto.randomBytes(32).toString('base64url');
20
+
21
+ function load() {
22
+ try {
23
+ return JSON.parse(fs.readFileSync(STATE, 'utf8'));
24
+ } catch {
25
+ return { token: null, sessions: {} };
26
+ }
27
+ }
28
+
29
+ function save(state) {
30
+ fs.mkdirSync(DIR, { recursive: true, mode: 0o700 });
31
+ const tmp = `${STATE}.${process.pid}.tmp`;
32
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { mode: 0o600 });
33
+ fs.renameSync(tmp, STATE);
34
+ }
35
+
36
+ // ------------------------------------------------------------- addresses
37
+
38
+ /**
39
+ * IPv4 addresses a phone could use. VPN/tunnel interfaces (utun, ppp, ipsec) are
40
+ * listed separately: a phone on the same Wi-Fi isn't on the corporate VPN.
41
+ */
42
+ export function lanAddresses() {
43
+ const out = [];
44
+ for (const [name, addrs] of Object.entries(os.networkInterfaces())) {
45
+ for (const a of addrs ?? []) {
46
+ if (a.family !== 'IPv4' || a.internal) continue;
47
+ out.push({ iface: name, address: a.address, vpn: /^(utun|ppp|ipsec|tun|tap|gif|stf)/.test(name) });
48
+ }
49
+ }
50
+ return out.sort((a, b) => a.vpn - b.vpn || a.iface.localeCompare(b.iface));
51
+ }
52
+
53
+ export function localHostname() {
54
+ const h = os.hostname().replace(/\.local$/i, '');
55
+ return `${h}.local`.toLowerCase();
56
+ }
57
+
58
+ /** Host headers the remote listener answers to: this machine's own addresses only (blocks DNS rebinding). */
59
+ export function allowedRemoteHosts(port) {
60
+ const names = [...lanAddresses().map((a) => a.address), localHostname(), ...(loadSettings().extraHosts ?? [])];
61
+ return new Set(names.map((n) => `${n.toLowerCase()}:${port}`));
62
+ }
63
+
64
+ // ------------------------------------------------------------- certificate
65
+
66
+ function openssl() {
67
+ // Prefer the one macOS ships, so nothing needs installing.
68
+ return fs.existsSync('/usr/bin/openssl') ? '/usr/bin/openssl' : 'openssl';
69
+ }
70
+
71
+ /** Self-signed certificate for the remote listener, created once with the system openssl. */
72
+ /**
73
+ * A usable certificate names its curve (P-256). LibreSSL otherwise writes explicit curve
74
+ * parameters, which Chrome, Safari and LibreSSL clients reject during the handshake.
75
+ */
76
+ const P256_OID = Buffer.from('06082a8648ce3d030107', 'hex');
77
+
78
+ function certificateUsable() {
79
+ try {
80
+ const x = new crypto.X509Certificate(fs.readFileSync(CERT));
81
+ // Node reports "prime256v1" even for explicit parameters, so look for the curve's OID
82
+ // (1.2.840.10045.3.1.7) in the certificate itself.
83
+ return x.raw.includes(P256_OID) && new Date(x.validTo) > new Date();
84
+ } catch {
85
+ return false;
86
+ }
87
+ }
88
+
89
+ export const certificatePaths = () => ({ key: KEY, cert: CERT });
90
+
91
+ export async function ensureCertificate() {
92
+ if (fs.existsSync(KEY) && fs.existsSync(CERT) && certificateUsable()) return { key: KEY, cert: CERT };
93
+ fs.mkdirSync(DIR, { recursive: true, mode: 0o700 });
94
+ const san = [
95
+ ...new Set([...lanAddresses().map((a) => `IP:${a.address}`), 'IP:127.0.0.1', `DNS:${localHostname()}`]),
96
+ ].join(',');
97
+ await new Promise((resolve, reject) =>
98
+ execFile(
99
+ openssl(),
100
+ [
101
+ 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1',
102
+ '-pkeyopt', 'ec_param_enc:named_curve', '-nodes',
103
+ '-keyout', KEY, '-out', CERT, '-days', '397', '-subj', '/CN=agentmgr',
104
+ '-addext', `subjectAltName=${san}`, '-addext', 'extendedKeyUsage=serverAuth',
105
+ ],
106
+ (err, _out, stderr) => (err ? reject(new Error(`openssl failed: ${stderr || err.message}`)) : resolve()),
107
+ ),
108
+ );
109
+ fs.chmodSync(KEY, 0o600);
110
+ return { key: KEY, cert: CERT };
111
+ }
112
+
113
+ export function certificateFingerprint() {
114
+ try {
115
+ const x = new crypto.X509Certificate(fs.readFileSync(CERT));
116
+ return x.fingerprint256;
117
+ } catch {
118
+ return null;
119
+ }
120
+ }
121
+
122
+ // ------------------------------------------------------------- settings, token, sessions
123
+
124
+ /**
125
+ * Remote access is off until you turn it on: it opens this machine's terminals to the network.
126
+ * Installs from before 1.0, where it was on by default (they have a token), keep it on.
127
+ * Its port defaults to the local port + 1 (4717 -> 4718), so several daemons (e.g. a test
128
+ * one) don't collide.
129
+ */
130
+ export function loadSettings() {
131
+ const s = load();
132
+ const envDefault = process.env.AGENTMGR_REMOTE === '0' ? false : process.env.AGENTMGR_REMOTE === '1' ? true : null;
133
+ if (s.enabled === undefined && envDefault === null && s.token) {
134
+ s.enabled = true;
135
+ save(s);
136
+ }
137
+ return {
138
+ enabled: s.enabled ?? envDefault ?? false,
139
+ port: s.port ?? PORT + 1,
140
+ extraHosts: s.extraHosts ?? [],
141
+ relayPorts: s.relayPorts ?? {},
142
+ };
143
+ }
144
+
145
+ export function saveSettings(patch) {
146
+ const s = load();
147
+ Object.assign(s, patch);
148
+ save(s);
149
+ return loadSettings();
150
+ }
151
+
152
+ /** The access token (created on first use). Kept like an SSH key: readable only by you. */
153
+ export function accessToken() {
154
+ const s = load();
155
+ if (!s.token) {
156
+ s.token = newSecret();
157
+ s.tokenCreatedAt = new Date().toISOString();
158
+ save(s);
159
+ }
160
+ return s.token;
161
+ }
162
+
163
+ /** New token, and every signed-in device is signed out. */
164
+ export function rotateToken() {
165
+ const s = load();
166
+ s.token = newSecret();
167
+ s.tokenCreatedAt = new Date().toISOString();
168
+ s.sessions = {};
169
+ save(s);
170
+ return s.token;
171
+ }
172
+
173
+ export function checkToken(candidate) {
174
+ const token = load().token;
175
+ if (!token || typeof candidate !== 'string') return false;
176
+ const a = Buffer.from(sha256(candidate));
177
+ const b = Buffer.from(sha256(token));
178
+ return crypto.timingSafeEqual(a, b);
179
+ }
180
+
181
+ export function createSession({ ua, ip, via }) {
182
+ const s = load();
183
+ const secret = newSecret();
184
+ const id = crypto.randomBytes(4).toString('hex');
185
+ s.sessions ??= {};
186
+ s.sessions[sha256(secret)] = { id, ua: String(ua ?? '').slice(0, 200), ip, ...(via ? { via } : {}), createdAt: new Date().toISOString(), lastSeen: new Date().toISOString() };
187
+ save(s);
188
+ return { secret, maxAgeSec: SESSION_DAYS * 86400 };
189
+ }
190
+
191
+ let lastSeenWrite = 0;
192
+ /** Validate a session cookie value; slides its expiry. */
193
+ export function checkSession(secret) {
194
+ if (!secret) return null;
195
+ const s = load();
196
+ const key = sha256(secret);
197
+ const sess = s.sessions?.[key];
198
+ if (!sess) return null;
199
+ const age = Date.now() - new Date(sess.lastSeen).getTime();
200
+ if (age > SESSION_DAYS * 86400 * 1000) {
201
+ delete s.sessions[key];
202
+ save(s);
203
+ return null;
204
+ }
205
+ if (Date.now() - lastSeenWrite > 60_000) {
206
+ lastSeenWrite = Date.now();
207
+ sess.lastSeen = new Date().toISOString();
208
+ save(s);
209
+ }
210
+ return sess;
211
+ }
212
+
213
+ export function endSession(secret) {
214
+ const s = load();
215
+ delete s.sessions?.[sha256(secret ?? '')];
216
+ save(s);
217
+ }
218
+
219
+ export function listSessions() {
220
+ return Object.values(load().sessions ?? {}).sort((a, b) => b.lastSeen.localeCompare(a.lastSeen));
221
+ }
222
+
223
+ export function revokeSession(id) {
224
+ const s = load();
225
+ for (const [k, v] of Object.entries(s.sessions ?? {})) if (v.id === id) delete s.sessions[k];
226
+ save(s);
227
+ }
228
+
229
+ // ------------------------------------------------------------- one-time tickets
230
+
231
+ // A hub that this machine allows "signin" can ask for a ticket: one use, a minute, kept in
232
+ // memory only. It signs a browser in like the access token, so the hub page can open this
233
+ // machine's own page without the token being at hand.
234
+ const TICKET_MS = 60_000;
235
+ const tickets = new Map(); // sha256(ticket) -> expiry
236
+
237
+ export function createTicket() {
238
+ const t = newSecret();
239
+ for (const [k, exp] of tickets) if (exp < Date.now()) tickets.delete(k);
240
+ tickets.set(sha256(t), Date.now() + TICKET_MS);
241
+ return t;
242
+ }
243
+
244
+ export function useTicket(candidate) {
245
+ if (typeof candidate !== 'string' || !candidate) return false;
246
+ const key = sha256(candidate);
247
+ const exp = tickets.get(key);
248
+ tickets.delete(key);
249
+ return Boolean(exp && exp >= Date.now());
250
+ }
251
+
252
+ // ------------------------------------------------------------- login throttling
253
+
254
+ const failures = new Map(); // ip -> [timestamps]
255
+ /** At most 10 failed logins per address per 15 minutes. */
256
+ export function loginAllowed(ip) {
257
+ const recent = (failures.get(ip) ?? []).filter((t) => Date.now() - t < 15 * 60_000);
258
+ failures.set(ip, recent);
259
+ return recent.length < 10;
260
+ }
261
+ export function loginFailed(ip) {
262
+ failures.set(ip, [...(failures.get(ip) ?? []), Date.now()]);
263
+ }
264
+
265
+ // ------------------------------------------------------------- links
266
+
267
+ export function remoteUrls(port) {
268
+ return lanAddresses().map((a) => ({ ...a, url: `https://${a.address}:${port}/` }));
269
+ }
270
+
271
+ /** Sign-in link: the token rides in the #fragment, which browsers never send to servers or logs. */
272
+ export const loginLink = (url) => `${url}#login=${accessToken()}`;
273
+
274
+ export const qrSvg = (text) => QRCode.toString(text, { type: 'svg', margin: 1, errorCorrectionLevel: 'M' });
275
+ export const qrTerminal = (text) => QRCode.toString(text, { type: 'terminal', small: true });
276
+
277
+ export function parseCookies(header = '') {
278
+ const out = {};
279
+ for (const part of header.split(';')) {
280
+ const i = part.indexOf('=');
281
+ if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
282
+ }
283
+ return out;
284
+ }