@jacoblee93/agent-overwatch 0.0.0-stage → 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,612 @@
1
+ #!/usr/bin/env node
2
+ import { execFile, spawn } from "node:child_process";
3
+ import { createHash, randomInt, X509Certificate } from "node:crypto";
4
+ import { chmodSync, copyFileSync, existsSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import { isIP } from "node:net";
6
+ import { join } from "node:path";
7
+ import { createInterface } from "node:readline/promises";
8
+ import { connect } from "node:tls";
9
+ import { activePairingCode, MAX_PAIRING_ATTEMPTS, PAIRING_CODE_DIGITS, PAIRING_TTL_MS, parsePairingCode, setPairingCode } from "./auth.js";
10
+ import { qrSvg, qrTerminal } from "./qr.js";
11
+ import { runBridge } from "./bridge.js";
12
+ import { configPath, loadConfig, overwatchHome, publicPairingURL, updateConfigFile } from "./config.js";
13
+ import { daemon, daemonStatus } from "./daemon.js";
14
+ import { DeviceRegistry } from "./devices.js";
15
+ import { funnelURLs } from "./tailscale.js";
16
+ import { agents } from "./agents.js";
17
+ import { GitHubSource } from "./github.js";
18
+ import { KEYCHAIN_ACCOUNT, KEYCHAIN_SERVICE, LinearSource, readLinearKey } from "./linear.js";
19
+ import { dirs } from "./dirs.js";
20
+ import { ApnsClient, checkPushConfig, expandHome, PushRegistry } from "./push.js";
21
+ import { loadRelayIdentity, RelayClient, relayURL } from "./relay.js";
22
+ import { pairingAddress } from "./pairing.js";
23
+ import { VERSION } from "./version.js";
24
+ import { listWorktrees, removeWorktree, worktreeRoot } from "./worktrees.js";
25
+ const HELP = `overwatch — bridge between Agent Overwatch on your Apple Watch and your coding agents
26
+
27
+ Usage: overwatch <command>
28
+
29
+ start Run the bridge in the foreground (Ctrl-C to stop)
30
+ daemon <cmd> Run it in the background instead: start | stop | restart | status | logs
31
+ agents [add|remove] The ACP agents the watch can start (any ACP program)
32
+ dirs [add|remove] List the directories the watch can start threads in;
33
+ \`overwatch dirs add\` adds the current directory
34
+ push [status|test] Apple push notifications: show setup, or send a test
35
+ push setup <AuthKey_XXXXXXXXXX.p8> [--team TEAMID]
36
+ Turn push on with an APNs key from developer.apple.com
37
+ worktrees [clean] List thread worktrees, or remove the ones with nothing to lose
38
+ linear [login|logout] Show your assigned Linear issues on the watch
39
+ github Show your open GitHub PRs on the watch (uses \`gh\`)
40
+ pair Pair a watch: scan the QR code with your iPhone's camera
41
+ pair [code] Or type the 12-digit code the watch shows (--type to be asked)
42
+ devices List paired watches
43
+ revoke <id> Revoke a paired watch (takes effect immediately)
44
+ doctor Check the setup and explain how to fix problems
45
+ init Create the config if it doesn't exist
46
+ token Print the admin token (for curl / simulator token mode)
47
+ --version Print the version
48
+ help Show this help
49
+
50
+ Config: ${configPath()}`;
51
+ const [cmd, arg] = process.argv.slice(2);
52
+ let failures = 0; // doctor's problem count (declared before the command switch below runs)
53
+ switch (cmd) {
54
+ case "start":
55
+ await runBridge();
56
+ break;
57
+ case "init": {
58
+ const { created } = loadConfig();
59
+ console.log(created ? `Created ${configPath()}` : `Config already exists at ${configPath()}`);
60
+ break;
61
+ }
62
+ case "pair":
63
+ process.exitCode = await pairCommand(arg);
64
+ break;
65
+ case "devices": {
66
+ const list = new DeviceRegistry(overwatchHome()).list();
67
+ if (!list.length)
68
+ console.log("No paired devices. Pair one with: overwatch pair");
69
+ for (const d of list) {
70
+ const seen = d.lastSeenAt ? new Date(d.lastSeenAt).toLocaleString() : "never";
71
+ console.log(`${d.id.slice(0, 8)} ${d.name.padEnd(28)} paired ${new Date(d.createdAt).toLocaleDateString()} last seen ${seen}`);
72
+ }
73
+ break;
74
+ }
75
+ case "revoke": {
76
+ if (!arg) {
77
+ console.log("usage: overwatch revoke <device-id> (see `overwatch devices`)");
78
+ process.exit(1);
79
+ }
80
+ const removed = new DeviceRegistry(overwatchHome()).revoke(arg);
81
+ if (!removed) {
82
+ console.log(`No single device matches "${arg}". See \`overwatch devices\`.`);
83
+ process.exit(1);
84
+ }
85
+ console.log(`Revoked "${removed.name}" (${removed.id}).`);
86
+ console.log("Its certificate and token stop working immediately (no restart needed).");
87
+ break;
88
+ }
89
+ case "token": {
90
+ const { config } = loadConfig();
91
+ console.log(config.token);
92
+ break;
93
+ }
94
+ case "linear":
95
+ process.exitCode = await linearCommand(arg ?? "status");
96
+ break;
97
+ case "github":
98
+ process.exitCode = await githubCommand(arg);
99
+ break;
100
+ case "agents":
101
+ case "agent":
102
+ process.exitCode = agents(process.argv.slice(3));
103
+ break;
104
+ case "dirs":
105
+ case "dir":
106
+ process.exitCode = dirs(process.argv.slice(3));
107
+ break;
108
+ case "worktrees":
109
+ process.exitCode = await worktreesCommand(arg);
110
+ break;
111
+ case "push":
112
+ process.exitCode = arg === "setup" ? await pushSetup(process.argv.slice(4)) : await pushCommand(arg ?? "status");
113
+ break;
114
+ case "daemon":
115
+ process.exitCode = await daemon(arg, loadConfig().config);
116
+ break;
117
+ case "doctor":
118
+ process.exitCode = (await doctor()) ? 0 : 1;
119
+ break;
120
+ case "--version":
121
+ case "-v":
122
+ console.log(VERSION);
123
+ break;
124
+ case undefined:
125
+ case "help":
126
+ case "--help":
127
+ case "-h":
128
+ console.log(HELP);
129
+ break;
130
+ default:
131
+ console.log(`Unknown command "${cmd}".\n\n${HELP}`);
132
+ process.exit(1);
133
+ }
134
+ /**
135
+ * `overwatch linear login` stores a Linear personal API key in the macOS Keychain. You type it
136
+ * into macOS's own \`security\` prompt, so it never passes through this program or its arguments.
137
+ */
138
+ async function linearCommand(sub) {
139
+ const keychain = (args, interactive = false) => new Promise((resolve) => {
140
+ const p = spawn("security", args, { stdio: interactive ? "inherit" : "ignore" });
141
+ p.on("exit", (code) => resolve(code ?? 1));
142
+ p.on("error", () => resolve(1));
143
+ });
144
+ const whoami = async () => {
145
+ try {
146
+ const d = await new LinearSource().query("query { viewer { name } }");
147
+ return d.viewer.name;
148
+ }
149
+ catch (e) {
150
+ return `error: ${e.message}`;
151
+ }
152
+ };
153
+ switch (sub) {
154
+ case "login": {
155
+ if (process.platform !== "darwin") {
156
+ console.log("On this OS, set LINEAR_API_KEY in the bridge's environment instead.");
157
+ return 1;
158
+ }
159
+ const page = "https://linear.app/settings/account/security";
160
+ console.log(`1. Create a personal API key in Linear (Settings → Account → Security & access → Personal API keys):\n ${page}`);
161
+ spawn("open", [page], { stdio: "ignore" }).on("error", () => { });
162
+ console.log("2. Paste it below (macOS asks twice; it's stored in your Keychain, not in any file).\n");
163
+ const code = await keychain(["add-generic-password", "-U", "-s", KEYCHAIN_SERVICE, "-a", KEYCHAIN_ACCOUNT, "-l", "Agent Overwatch: Linear API key", "-w"], true);
164
+ if (code !== 0) {
165
+ console.log("\nNothing saved.");
166
+ return 1;
167
+ }
168
+ const who = await whoami();
169
+ console.log(who.startsWith("error:")
170
+ ? `\nSaved, but Linear didn't accept it (${who.slice(7)}).`
171
+ : `\n✓ Logged in to Linear as ${who}. The watch shows your assigned issues within a minute.`);
172
+ return who.startsWith("error:") ? 1 : 0;
173
+ }
174
+ case "logout": {
175
+ const code = await keychain(["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", KEYCHAIN_ACCOUNT]);
176
+ console.log(code === 0 ? "Removed the Linear API key from your Keychain." : "No Linear API key was stored.");
177
+ return 0;
178
+ }
179
+ case "status": {
180
+ if (!readLinearKey()) {
181
+ console.log("Linear: not set up. Run: overwatch linear login");
182
+ return 1;
183
+ }
184
+ const who = await whoami();
185
+ console.log(who.startsWith("error:")
186
+ ? `Linear: ${who}`
187
+ : `Linear: logged in as ${who}${process.env.LINEAR_API_KEY ? " (LINEAR_API_KEY)" : " (Keychain)"}`);
188
+ if (!who.startsWith("error:")) {
189
+ const issues = await new LinearSource().issues().catch(() => []);
190
+ for (const i of issues.slice(0, 10))
191
+ console.log(` ${i.identifier.padEnd(10)} ${i.state.padEnd(12)} ${i.title}`);
192
+ }
193
+ return who.startsWith("error:") ? 1 : 0;
194
+ }
195
+ default:
196
+ console.log("usage: overwatch linear [status|login|logout]");
197
+ return 1;
198
+ }
199
+ }
200
+ async function githubCommand(directoryId) {
201
+ const { config } = loadConfig();
202
+ const gh = new GitHubSource(() => config.directories);
203
+ if (!(await gh.checkAuth())) {
204
+ console.log("GitHub: the GitHub CLI isn't installed or logged in.\n Install: https://cli.github.com Then: gh auth login");
205
+ return 1;
206
+ }
207
+ try {
208
+ const prs = await gh.pullRequests(directoryId);
209
+ console.log(`GitHub: ${prs.length} open PR(s)${directoryId ? ` in ${directoryId}` : ""} via gh`);
210
+ for (const p of prs.slice(0, 15))
211
+ console.log(` ${p.id.padEnd(40)} ${p.draft ? "(draft) " : ""}${p.title}${p.directoryId ? ` → directory ${p.directoryId}` : ""}`);
212
+ if (prs.some((p) => !p.directoryId))
213
+ console.log("\nPRs without a directory start in whichever you pick; `overwatch dirs add` a checkout of the repo to match it automatically.");
214
+ return 0;
215
+ }
216
+ catch (e) {
217
+ console.log(`GitHub: ${e.message}`);
218
+ return 1;
219
+ }
220
+ }
221
+ async function worktreesCommand(sub) {
222
+ const all = await listWorktrees();
223
+ if (!all.length) {
224
+ console.log(`No thread worktrees (${worktreeRoot()}).`);
225
+ return 0;
226
+ }
227
+ if (sub === "clean") {
228
+ let removed = 0;
229
+ for (const wt of all) {
230
+ const r = await removeWorktree(wt);
231
+ if (r.removed)
232
+ removed++;
233
+ else
234
+ console.log(` ${r.kept}`);
235
+ }
236
+ console.log(`Removed ${removed} of ${all.length} worktree(s). The rest have work in them; commit, push or merge it, then run this again.`);
237
+ return 0;
238
+ }
239
+ if (sub) {
240
+ console.log("usage: overwatch worktrees [clean]");
241
+ return 1;
242
+ }
243
+ for (const wt of all) {
244
+ const state = wt.dirty || wt.unique ? `${wt.dirty} uncommitted, ${wt.unique} unmerged commit(s)` : "clean";
245
+ console.log(`${wt.branch.padEnd(44)} ${state}\n ${wt.path}`);
246
+ }
247
+ console.log("\nThreads remove their worktree when deleted, unless it has work in it. `overwatch worktrees clean` removes the clean ones.");
248
+ return 0;
249
+ }
250
+ /**
251
+ * `overwatch push setup <AuthKey_KEYID.p8> [--team TEAMID]`: copy the APNs key into the
252
+ * overwatch home (0600) and turn push on. The key ID comes from the file name Apple gives it.
253
+ * The key's contents are never printed.
254
+ */
255
+ async function pushSetup(args) {
256
+ const file = args.find((a) => !a.startsWith("--"));
257
+ const teamFlag = args.indexOf("--team");
258
+ let teamId = teamFlag >= 0 ? args[teamFlag + 1] : loadConfig().config.push?.teamId;
259
+ if (!file) {
260
+ console.log("usage: overwatch push setup <AuthKey_XXXXXXXXXX.p8> [--team TEAMID]");
261
+ console.log("Create the key at https://developer.apple.com/account/resources/authkeys/add (enable Apple Push Notifications service).");
262
+ return 1;
263
+ }
264
+ const src = expandHome(file);
265
+ const keyId = /AuthKey_([A-Z0-9]{10})\.p8$/.exec(src)?.[1];
266
+ if (!existsSync(src))
267
+ return (console.log(`Not found: ${file}`), 1);
268
+ if (!keyId)
269
+ return (console.log("Expected Apple's file name, AuthKey_<KEYID>.p8 (the key ID is in it)."), 1);
270
+ if (!teamId) {
271
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
272
+ teamId = (await rl.question("Your Apple developer team ID (developer.apple.com → Membership): ")).trim().toUpperCase();
273
+ rl.close();
274
+ }
275
+ if (!/^[A-Z0-9]{10}$/.test(teamId ?? ""))
276
+ return (console.log("The team ID is 10 letters/digits, e.g. AB12CD34EF."), 1);
277
+ const dest = join(overwatchHome(), `AuthKey_${keyId}.p8`);
278
+ copyFileSync(src, dest);
279
+ chmodSync(dest, 0o600);
280
+ const push = { keyPath: dest, keyId, teamId: teamId };
281
+ const problems = checkPushConfig(push);
282
+ if (problems.length)
283
+ return (problems.forEach((p) => console.log(`✗ ${p}`)), 1);
284
+ updateConfigFile((c) => {
285
+ c.push = { ...c.push, ...push };
286
+ });
287
+ console.log(`✓ Push is on (key ${keyId}). Copied the key to ${dest} (only you can read it); you can delete the download.`);
288
+ console.log("Restart the bridge to use it (overwatch daemon restart), then: overwatch push test");
289
+ return 0;
290
+ }
291
+ async function pushCommand(sub) {
292
+ const { config } = loadConfig();
293
+ const registry = new DeviceRegistry(overwatchHome());
294
+ const regs = new PushRegistry(overwatchHome()).list();
295
+ if (!config.push && relayURL(config)) {
296
+ const id = loadRelayIdentity(overwatchHome());
297
+ const viaRelay = regs.filter((r) => r.relayHandle).length;
298
+ console.log(`Push: via the Agent Overwatch relay (${relayURL(config)}), relay ID ${id.bridgeId}`);
299
+ console.log(viaRelay
300
+ ? `${viaRelay} watch registration(s) through the relay.`
301
+ : "No watches registered through the relay yet. Open the app on the watch (an up-to-date build).");
302
+ console.log("Your own APNs key takes over if you set one: overwatch push setup <AuthKey_….p8>");
303
+ if (sub !== "test")
304
+ return 0;
305
+ const relay = new RelayClient(relayURL(config), id);
306
+ let sent = 0;
307
+ for (const r of regs.filter((x) => x.relayHandle)) {
308
+ const res = await relay.push(r.relayHandle, {
309
+ aps: { alert: { title: "Agent Overwatch", body: "Test notification through the relay" } },
310
+ hostID: r.hostId,
311
+ });
312
+ console.log(` …${r.token.slice(-8)}: ${res.status === 200 ? "sent" : `failed (${res.status} ${res.reason ?? ""})`}`);
313
+ if (res.status === 200)
314
+ sent++;
315
+ }
316
+ return sent > 0 ? 0 : 1;
317
+ }
318
+ if (!config.push) {
319
+ console.log("Push is off. To turn it on:");
320
+ console.log(" 1. Create an APNs key: https://developer.apple.com/account/resources/authkeys/add (enable Apple Push Notifications service), and download it.");
321
+ console.log(" 2. overwatch push setup ~/Downloads/AuthKey_XXXXXXXXXX.p8");
322
+ return sub === "status" ? 0 : 1;
323
+ }
324
+ const problems = checkPushConfig(config.push);
325
+ if (problems.length) {
326
+ problems.forEach((p) => console.log(`✗ ${p}`));
327
+ return 1;
328
+ }
329
+ console.log(`Push: on (key ${config.push.keyId}, topic ${config.push.topic ?? "dev.agentoverwatch.watchkitapp"})`);
330
+ console.log(regs.length ? `${regs.length} watch registration(s):` : "No watches registered yet. Open the app on the watch once it's paired.");
331
+ const names = new Map(registry.list().map((d) => [d.id, d.name]));
332
+ for (const r of regs)
333
+ console.log(` …${r.token.slice(-8)} ${r.environment.padEnd(11)} ${r.deviceId ? (names.get(r.deviceId) ?? "revoked device") : "token-mode host"}`);
334
+ if (sub !== "test")
335
+ return 0;
336
+ const apns = new ApnsClient(config.push);
337
+ let ok = 0;
338
+ for (const r of regs) {
339
+ const res = await apns.send(r.token, r.environment, {
340
+ aps: { alert: { title: "Agent Overwatch", body: "Test notification from your bridge" }, sound: "default" },
341
+ });
342
+ console.log(` …${r.token.slice(-8)}: ${res.status === 200 ? "sent" : `failed (${res.status} ${res.reason ?? ""})`}`);
343
+ if (res.status === 200)
344
+ ok++;
345
+ }
346
+ apns.close();
347
+ return ok === regs.length && regs.length > 0 ? 0 : 1;
348
+ }
349
+ /**
350
+ * `overwatch pair [code]`: the watch shows a 12-digit code; type it here. The
351
+ * running bridge picks it up and the watch, which keeps asking, finishes on its own.
352
+ */
353
+ async function pairCommand(given) {
354
+ const { config } = loadConfig();
355
+ if (!(await bridgeAnswers(config))) {
356
+ console.log("The bridge isn't running. Start it first: overwatch daemon start (or overwatch start)\n");
357
+ return 1;
358
+ }
359
+ const url = pairingURL(config);
360
+ const address = url ? pairingAddress(url) : undefined;
361
+ console.log(`\n Pair a watch with "${config.hostName}"\n`);
362
+ let code;
363
+ let imageFallback;
364
+ if (given && given !== "--type") {
365
+ // Typed flow, code from the watch: overwatch pair 1234 5678 9012
366
+ code = parsePairingCode(given);
367
+ if (!code)
368
+ return (console.log("That isn't a 12-digit code."), 1);
369
+ }
370
+ else if (given === "--type") {
371
+ printTypedSteps(address);
372
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
373
+ for (let tries = 0; !code && tries < 3; tries++) {
374
+ code = parsePairingCode(await rl.question(" 3. Type the code from the watch: "));
375
+ if (!code)
376
+ console.log(" That's not 12 digits; try again.");
377
+ }
378
+ rl.close();
379
+ if (!code)
380
+ return 1;
381
+ }
382
+ else {
383
+ // QR flow: the code comes from here, and the iPhone app hands it (with the address) to the watch.
384
+ code = Array.from({ length: PAIRING_CODE_DIGITS }, () => randomInt(10)).join("");
385
+ // Kept short so the QR code stays small: the watch learns the host's name while pairing.
386
+ const link = `agentoverwatch://pair?${new URLSearchParams({ h: address ?? "localhost", c: code })}`;
387
+ if (!address)
388
+ console.log(" No public address found (set up Tailscale Funnel, see `overwatch doctor`); this only works in the simulator.\n");
389
+ console.log(" Scan this with your iPhone's camera, then tap to open it in Overwatch:\n");
390
+ console.log(qrTerminal(link, { quiet: 3, ecc: "L" }).replace(/^/gm, " "));
391
+ console.log(`\n The iPhone hands it to your watch, which pairs on its own (keep the watch app open).`);
392
+ console.log(` Won't scan? Press Enter to show it as an image. No iPhone app? \`overwatch pair --type\`.\n`);
393
+ imageFallback = showQrImageOnEnter(link);
394
+ }
395
+ try {
396
+ return await waitForWatch(code);
397
+ }
398
+ finally {
399
+ imageFallback?.close();
400
+ }
401
+ }
402
+ /** Waits for a watch to pair with the armed code. */
403
+ async function waitForWatch(code) {
404
+ const before = new DeviceRegistry(overwatchHome()).list().length;
405
+ const { expiresAt } = setPairingCode(code);
406
+ console.log(" Waiting for the watch…");
407
+ while (Date.now() < expiresAt.getTime()) {
408
+ await new Promise((r) => setTimeout(r, 1000));
409
+ if (activePairingCode().ok)
410
+ continue;
411
+ const devices = new DeviceRegistry(overwatchHome()).list();
412
+ if (devices.length > before) {
413
+ console.log(` ✓ Paired "${devices.at(-1).name}". It can now reach this bridge from any network.\n`);
414
+ return 0;
415
+ }
416
+ console.log(` ✗ The watch's code didn't match after ${MAX_PAIRING_ATTEMPTS} tries. Run \`overwatch pair\` again.\n`);
417
+ return 1;
418
+ }
419
+ console.log(` ✗ Timed out after ${PAIRING_TTL_MS / 60000} minutes. Run \`overwatch pair\` again.\n`);
420
+ return 1;
421
+ }
422
+ /**
423
+ * Enter opens the QR code as an image (some terminals' line spacing breaks the text one).
424
+ * The file holds the one-time code, so it's readable only by you and deleted when pairing ends.
425
+ */
426
+ function showQrImageOnEnter(link) {
427
+ const path = join(overwatchHome(), "pairing-qr.svg");
428
+ const rl = createInterface({ input: process.stdin });
429
+ rl.on("line", () => {
430
+ writeFileSync(path, qrSvg(link, { ecc: "L" }), { mode: 0o600 });
431
+ execFile("open", [path], (err) => {
432
+ if (err)
433
+ console.log(` Couldn't open it; it's at ${path}`);
434
+ });
435
+ });
436
+ return {
437
+ close() {
438
+ rl.close();
439
+ rmSync(path, { force: true });
440
+ },
441
+ };
442
+ }
443
+ function printTypedSteps(address) {
444
+ console.log(` 1. On the watch: Hosts → Add host, and enter${address ? "" : " this host's pairing address"}:`);
445
+ console.log(address ? ` ${address}` : " nothing found: set up Tailscale Funnel or secure.publicURL (see `overwatch doctor`)");
446
+ console.log(" In the simulator: localhost");
447
+ console.log(" 2. Tap Pair. The watch shows a 12-digit code.\n");
448
+ }
449
+ /** Where watches pair from outside (see publicPairingURL in config.ts). */
450
+ function pairingURL(config) {
451
+ return publicPairingURL(config, funnelURLs(config.secure.port, config.secure.pairPort).pair);
452
+ }
453
+ async function bridgeAnswers(config) {
454
+ try {
455
+ return (await fetch(`http://${config.listen.hostname}:${config.listen.port}/api/health`, { signal: AbortSignal.timeout(2000) })).ok;
456
+ }
457
+ catch {
458
+ return false;
459
+ }
460
+ }
461
+ function report(status, what, fix) {
462
+ if (status === "warn" && !fix) {
463
+ console.log(` - ${what}`);
464
+ return;
465
+ }
466
+ const icon = status === "ok" ? "✓" : status === "warn" ? "!" : "✗";
467
+ if (status === "fail")
468
+ failures++;
469
+ console.log(` ${icon} ${what}`);
470
+ if (fix && status !== "ok")
471
+ for (const line of fix.split("\n"))
472
+ console.log(` → ${line}`);
473
+ }
474
+ function mode(path) {
475
+ return statSync(path).mode & 0o777;
476
+ }
477
+ /** TLS-connect and return the SHA-256 of the certificate the server presents. */
478
+ function serverFingerprint(host, port) {
479
+ return new Promise((resolve) => {
480
+ const sock = connect({ host, port, servername: isIP(host) ? undefined : host, rejectUnauthorized: false, timeout: 4000 });
481
+ sock.once("secureConnect", () => {
482
+ const raw = sock.getPeerCertificate()?.raw;
483
+ resolve(raw?.length ? { fp: createHash("sha256").update(raw).digest("hex") } : { error: "no certificate presented" });
484
+ sock.destroy();
485
+ });
486
+ sock.once("timeout", () => {
487
+ resolve({ error: "timed out" });
488
+ sock.destroy();
489
+ });
490
+ sock.once("error", (e) => resolve({ error: e.message }));
491
+ });
492
+ }
493
+ async function httpOk(url) {
494
+ try {
495
+ return (await fetch(url, { signal: AbortSignal.timeout(3000) })).ok;
496
+ }
497
+ catch {
498
+ return false;
499
+ }
500
+ }
501
+ function run(cmd, args) {
502
+ return new Promise((resolve) => execFile(cmd, args, { timeout: 5000 }, (err, stdout, stderr) => resolve({ ok: !err, out: (stdout || stderr).trim() })));
503
+ }
504
+ async function doctor() {
505
+ console.log("\nAgent Overwatch doctor\n");
506
+ const [maj = 0, min = 0] = process.versions.node.split(".").map(Number);
507
+ report(maj > 22 || (maj === 22 && min >= 18) ? "ok" : "fail", `Node.js ${process.versions.node}`, "Install Node.js 22.18 or newer.");
508
+ let config;
509
+ try {
510
+ config = loadConfig().config;
511
+ report("ok", `Config ${configPath()}`);
512
+ report(mode(configPath()) === 0o600 ? "ok" : "warn", "Config is private (0600)", `chmod 600 ${configPath()}`);
513
+ }
514
+ catch (e) {
515
+ report("fail", `Config ${configPath()}`, String(e.message));
516
+ return false;
517
+ }
518
+ report(config.agents.length ? "ok" : "warn", `${config.agents.length} agent(s), ${config.directories.length} director${config.directories.length === 1 ? "y" : "ies"}`, "Add agents to the config, and directories with `overwatch dirs add`.");
519
+ if (config.push) {
520
+ const problems = checkPushConfig(config.push);
521
+ report(problems.length ? "fail" : "ok", "Apple push", problems.join("; ") || undefined);
522
+ }
523
+ else {
524
+ report("warn", "Apple push is off; notifications wait for background refresh (~15 min)", "See README → Instant notifications, or set notify.ntfyUrl.");
525
+ }
526
+ const pki = join(overwatchHome(), "pki");
527
+ if (existsSync(join(pki, "ca.key"))) {
528
+ const priv = mode(pki) === 0o700 && mode(join(pki, "ca.key")) === 0o600 && mode(join(pki, "server.key")) === 0o600;
529
+ report(priv ? "ok" : "warn", "Bridge CA and keys are private", `chmod 700 ${pki} && chmod 600 ${pki}/*.key`);
530
+ }
531
+ else {
532
+ report("warn", "Bridge CA not created yet", "It's created the first time you run: overwatch start");
533
+ }
534
+ const serverCrt = join(pki, "server.crt");
535
+ const ourFp = existsSync(serverCrt)
536
+ ? createHash("sha256")
537
+ .update(new X509Certificate(readFileSync(serverCrt)).raw)
538
+ .digest("hex")
539
+ : undefined;
540
+ const localUp = await httpOk(`http://${config.listen.hostname}:${config.listen.port}/api/health`);
541
+ const d = process.platform === "darwin" ? await daemonStatus() : undefined;
542
+ const how = d?.loaded ? `as a daemon${d.pid ? `, pid ${d.pid}` : ""}` : "in the foreground";
543
+ report(localUp ? "ok" : "fail", localUp
544
+ ? `Bridge is running ${how} (local API on port ${config.listen.port})`
545
+ : `Bridge is running (local API on port ${config.listen.port})`, d?.loaded
546
+ ? "The daemon is loaded but the bridge isn't answering. Check: overwatch daemon logs"
547
+ : "Start it in the background: overwatch daemon start\n(or in the foreground: overwatch start)");
548
+ if (localUp) {
549
+ const host = config.secure.hostname === "0.0.0.0" ? "127.0.0.1" : config.secure.hostname;
550
+ for (const [label, port] of [
551
+ ["mTLS API", config.secure.port],
552
+ ["Pairing", config.secure.pairPort],
553
+ ]) {
554
+ const r = await serverFingerprint(host, port);
555
+ report(!!r.fp && r.fp === ourFp ? "ok" : "fail", `${label} listening on port ${port}`, r.error ?? "It's serving an unexpected certificate. Restart the bridge.");
556
+ }
557
+ }
558
+ const devices = new DeviceRegistry(overwatchHome()).list();
559
+ report(devices.length ? "ok" : "warn", `${devices.length} paired device(s)`, "Pair your watch: overwatch pair");
560
+ // Without secure.publicURL, the bridge uses whatever Tailscale Funnel forwards to it; check that.
561
+ const funnel = funnelURLs(config.secure.port, config.secure.pairPort);
562
+ if (!config.secure.publicURL && funnel.api) {
563
+ config.secure.publicURL = funnel.api;
564
+ report("ok", `Public URL from Tailscale Funnel: ${funnel.api}`);
565
+ }
566
+ if (!localUp) {
567
+ report("warn", "Skipped the public URL checks because the bridge isn't running");
568
+ }
569
+ else if (!config.secure.publicURL) {
570
+ report("warn", "No public URL: set up Tailscale Funnel, or set secure.publicURL (needed to reach the bridge away from this machine)", 'Set "secure": { "publicURL": "https://<your-public-name>" } in the config.\nSee README → "Make it reachable".');
571
+ }
572
+ else {
573
+ const api = new URL(config.secure.publicURL);
574
+ const pair = new URL(publicPairingURL(config, funnel.pair));
575
+ const checks = [
576
+ ["Public mTLS URL", api, config.secure.port],
577
+ ["Public pairing URL", pair, config.secure.pairPort],
578
+ ];
579
+ for (const [label, u, localPort] of checks) {
580
+ const p = Number(u.port || 443);
581
+ const r = await serverFingerprint(u.hostname, p);
582
+ const forward = `tailscale funnel --bg --tcp=${p} tcp://localhost:${localPort}`;
583
+ if (r.error)
584
+ report("fail", `${label} https://${u.hostname}:${p} is unreachable (${r.error})`, `Check your ingress, e.g.\n${forward}`);
585
+ else if (r.fp !== ourFp)
586
+ report("fail", `${label} https://${u.hostname}:${p} shows a different certificate`, `Your ingress is handling TLS itself. Forward raw TCP instead:\n${forward} (not plain \`tailscale funnel ${p}\`)`);
587
+ else
588
+ report("ok", `${label} https://${u.hostname}:${p} reaches this bridge`);
589
+ }
590
+ }
591
+ report(readLinearKey() ? "ok" : "warn", readLinearKey() ? "Linear: logged in" : "Linear isn't set up (optional)", "overwatch linear login");
592
+ const ghOk = await new GitHubSource(() => config.directories).checkAuth();
593
+ report(ghOk ? "ok" : "warn", ghOk ? "GitHub: gh is logged in" : "GitHub isn't set up (optional)", "Install the GitHub CLI (https://cli.github.com), then: gh auth login");
594
+ // Funnel settings persist, but only work while Tailscale runs: after a reboot that means "Launch at login".
595
+ if (process.platform === "darwin" && config.secure.publicURL?.includes(".ts.net")) {
596
+ for (const domain of ["io.tailscale.ipn.macsys", "io.tailscale.ipn.macos"]) {
597
+ const pref = await run("defaults", ["read", domain, "TailscaleStartOnLogin"]);
598
+ if (!pref.ok)
599
+ continue;
600
+ report(pref.out.trim() === "1" ? "ok" : "warn", "Tailscale launches at login", "Without it, Funnel (and your watch's connection) is down after a reboot until you open Tailscale.\nTailscale menu bar icon → Settings → Launch at login.");
601
+ break;
602
+ }
603
+ }
604
+ const ts = await run("tailscale", ["funnel", "status"]);
605
+ if (ts.ok && ts.out) {
606
+ console.log("\n Tailscale funnel status:");
607
+ for (const line of ts.out.split("\n").slice(0, 12))
608
+ console.log(` ${line}`);
609
+ }
610
+ console.log(failures ? `\n${failures} problem(s) found.\n` : "\nAll good.\n");
611
+ return failures === 0;
612
+ }