@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/LICENSE +45 -0
- package/README.md +33 -2
- package/config.example.json +44 -0
- package/dist/acp/connection.js +175 -0
- package/dist/acp/types.js +23 -0
- package/dist/acp-session.js +212 -0
- package/dist/agents.js +111 -0
- package/dist/approvals.js +70 -0
- package/dist/auth.js +71 -0
- package/dist/bridge.js +103 -0
- package/dist/cli.js +612 -0
- package/dist/config.js +171 -0
- package/dist/daemon.js +191 -0
- package/dist/devices.js +82 -0
- package/dist/dirs.js +107 -0
- package/dist/errors.js +8 -0
- package/dist/events.js +38 -0
- package/dist/github.js +244 -0
- package/dist/http.js +63 -0
- package/dist/linear.js +105 -0
- package/dist/mock-agent.js +242 -0
- package/dist/notify.js +32 -0
- package/dist/pairing.js +166 -0
- package/dist/pending.js +108 -0
- package/dist/pki.js +94 -0
- package/dist/push.js +287 -0
- package/dist/qr.js +304 -0
- package/dist/questions.js +117 -0
- package/dist/relay.js +80 -0
- package/dist/server.js +256 -0
- package/dist/servers.js +92 -0
- package/dist/sessions.js +691 -0
- package/dist/summaries.js +70 -0
- package/dist/tailscale.js +51 -0
- package/dist/thread-store.js +74 -0
- package/dist/transcript.js +167 -0
- package/dist/version.js +4 -0
- package/dist/worktrees.js +157 -0
- package/dist/x509.js +144 -0
- package/package.json +63 -3
package/dist/config.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir, hostname } from "node:os";
|
|
3
|
+
import { extname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
5
|
+
/** What kind of agent this is, from its command line; the watch shows a matching icon. */
|
|
6
|
+
export function agentKind(a) {
|
|
7
|
+
const cmd = [a.command, ...(a.args ?? [])].join(" ").toLowerCase();
|
|
8
|
+
if (cmd.includes("mock-agent"))
|
|
9
|
+
return "mock";
|
|
10
|
+
if (cmd.includes("claude"))
|
|
11
|
+
return "claude";
|
|
12
|
+
if (/\bdcode\b|deepagents/.test(cmd))
|
|
13
|
+
return "deepagents";
|
|
14
|
+
if (cmd.includes("codex"))
|
|
15
|
+
return "codex";
|
|
16
|
+
if (cmd.includes("gemini"))
|
|
17
|
+
return "gemini";
|
|
18
|
+
return "other";
|
|
19
|
+
}
|
|
20
|
+
/** What agents are told about where their replies are read. */
|
|
21
|
+
export const WATCH_PROMPT = "The user follows this session from an Apple Watch and reads your replies on its small screen. " +
|
|
22
|
+
"Keep replies to them short: lead with the result, or the question you need answered, then at most a few short bullets. " +
|
|
23
|
+
"Put details in files, commits or the pull request rather than in the reply. This is about your replies only, not about how thoroughly you work.";
|
|
24
|
+
export function overwatchHome() {
|
|
25
|
+
return process.env.OVERWATCH_HOME ?? join(homedir(), ".agent-overwatch");
|
|
26
|
+
}
|
|
27
|
+
export function configPath() {
|
|
28
|
+
return join(overwatchHome(), "config.json");
|
|
29
|
+
}
|
|
30
|
+
function defaultConfig() {
|
|
31
|
+
return {
|
|
32
|
+
hostName: hostname().replace(/\.local$/, ""),
|
|
33
|
+
listen: { hostname: "127.0.0.1", port: 7878 },
|
|
34
|
+
secure: { hostname: "127.0.0.1", port: 7879, pairPort: 7880 },
|
|
35
|
+
token: randomBytes(32).toString("base64url"),
|
|
36
|
+
agents: [
|
|
37
|
+
// Scripted fake agent: exercises every watch flow (permission, approve, reply) with no API key.
|
|
38
|
+
// Runs on the same Node binary as the bridge.
|
|
39
|
+
{
|
|
40
|
+
id: "mock",
|
|
41
|
+
name: "Mock agent (no API key)",
|
|
42
|
+
command: process.execPath,
|
|
43
|
+
// .ts when run from source, .js when installed (compiled to dist/)
|
|
44
|
+
args: [resolve(import.meta.dirname, `mock-agent${extname(import.meta.filename)}`)],
|
|
45
|
+
},
|
|
46
|
+
{ id: "claude-code", name: "Claude Code", command: "npx", args: ["-y", "@agentclientprotocol/claude-agent-acp"] },
|
|
47
|
+
],
|
|
48
|
+
directories: [{ id: "home", name: "Home", path: homedir() }],
|
|
49
|
+
notify: {},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const ID_RE = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
53
|
+
export function validateConfig(c) {
|
|
54
|
+
const errors = [];
|
|
55
|
+
if (!c.token || c.token.length < 24)
|
|
56
|
+
errors.push("token must be at least 24 characters");
|
|
57
|
+
const badPort = (p) => !Number.isInteger(p) || p <= 0 || p > 65535;
|
|
58
|
+
if (badPort(c.listen?.port))
|
|
59
|
+
errors.push("listen.port is invalid");
|
|
60
|
+
if (badPort(c.secure?.port))
|
|
61
|
+
errors.push("secure.port is invalid");
|
|
62
|
+
if (badPort(c.secure?.pairPort))
|
|
63
|
+
errors.push("secure.pairPort is invalid");
|
|
64
|
+
if (new Set([c.listen?.port, c.secure?.port, c.secure?.pairPort]).size !== 3)
|
|
65
|
+
errors.push("listen.port, secure.port and secure.pairPort must differ");
|
|
66
|
+
if (c.secure?.publicURL) {
|
|
67
|
+
try {
|
|
68
|
+
if (new URL(c.secure.publicURL).protocol !== "https:")
|
|
69
|
+
throw new Error();
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
errors.push("secure.publicURL must be an https:// URL");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const seen = new Set();
|
|
76
|
+
for (const a of c.agents ?? []) {
|
|
77
|
+
if (!ID_RE.test(a.id))
|
|
78
|
+
errors.push(`agent id "${a.id}" must match ${ID_RE}`);
|
|
79
|
+
if (seen.has(`a:${a.id}`))
|
|
80
|
+
errors.push(`duplicate agent id "${a.id}"`);
|
|
81
|
+
seen.add(`a:${a.id}`);
|
|
82
|
+
if (!a.command)
|
|
83
|
+
errors.push(`agent "${a.id}" is missing command`);
|
|
84
|
+
}
|
|
85
|
+
for (const w of c.directories ?? []) {
|
|
86
|
+
if (!ID_RE.test(w.id))
|
|
87
|
+
errors.push(`directory id "${w.id}" must match ${ID_RE}`);
|
|
88
|
+
if (seen.has(`w:${w.id}`))
|
|
89
|
+
errors.push(`duplicate directory id "${w.id}"`);
|
|
90
|
+
seen.add(`w:${w.id}`);
|
|
91
|
+
if (!isAbsolute(w.path))
|
|
92
|
+
errors.push(`directory "${w.id}" path must be absolute`);
|
|
93
|
+
}
|
|
94
|
+
return errors;
|
|
95
|
+
}
|
|
96
|
+
export function writeConfig(c) {
|
|
97
|
+
const dir = overwatchHome();
|
|
98
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
99
|
+
const tmp = configPath() + ".tmp";
|
|
100
|
+
writeFileSync(tmp, JSON.stringify(c, null, 2) + "\n", { mode: 0o600 });
|
|
101
|
+
renameSync(tmp, configPath());
|
|
102
|
+
chmodSync(configPath(), 0o600);
|
|
103
|
+
}
|
|
104
|
+
/** Load the config, creating a default one (with a fresh token) if absent. */
|
|
105
|
+
export function loadConfig() {
|
|
106
|
+
const path = configPath();
|
|
107
|
+
if (!existsSync(path)) {
|
|
108
|
+
const c = defaultConfig();
|
|
109
|
+
writeConfig(c);
|
|
110
|
+
return { config: c, created: true };
|
|
111
|
+
}
|
|
112
|
+
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
113
|
+
const base = defaultConfig();
|
|
114
|
+
const config = {
|
|
115
|
+
...base,
|
|
116
|
+
...raw,
|
|
117
|
+
listen: { ...base.listen, ...raw.listen },
|
|
118
|
+
secure: { ...base.secure, ...raw.secure },
|
|
119
|
+
agents: raw.agents ?? base.agents,
|
|
120
|
+
directories: raw.directories ?? base.directories,
|
|
121
|
+
};
|
|
122
|
+
if (!raw.token) {
|
|
123
|
+
// Persist a generated token so it stays stable across restarts.
|
|
124
|
+
writeConfig(config);
|
|
125
|
+
}
|
|
126
|
+
if (process.env.OVERWATCH_PORT)
|
|
127
|
+
config.listen.port = Number(process.env.OVERWATCH_PORT);
|
|
128
|
+
if (process.env.OVERWATCH_HOSTNAME)
|
|
129
|
+
config.listen.hostname = process.env.OVERWATCH_HOSTNAME;
|
|
130
|
+
if (process.env.OVERWATCH_SECURE_PORT)
|
|
131
|
+
config.secure.port = Number(process.env.OVERWATCH_SECURE_PORT);
|
|
132
|
+
if (process.env.OVERWATCH_PAIR_PORT)
|
|
133
|
+
config.secure.pairPort = Number(process.env.OVERWATCH_PAIR_PORT);
|
|
134
|
+
if (process.env.OVERWATCH_SECURE_HOSTNAME)
|
|
135
|
+
config.secure.hostname = process.env.OVERWATCH_SECURE_HOSTNAME;
|
|
136
|
+
const errors = validateConfig(config);
|
|
137
|
+
if (errors.length)
|
|
138
|
+
throw new Error(`Invalid config at ${path}:\n - ${errors.join("\n - ")}`);
|
|
139
|
+
return { config, created: false };
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Edit the config file as written on disk (not the loaded config, which has
|
|
143
|
+
* defaults and OVERWATCH_* overrides applied). Throws, leaving the file
|
|
144
|
+
* untouched, if the result is invalid.
|
|
145
|
+
*/
|
|
146
|
+
export function updateConfigFile(edit) {
|
|
147
|
+
loadConfig(); // creates the file if needed and validates the current one
|
|
148
|
+
const raw = JSON.parse(readFileSync(configPath(), "utf8"));
|
|
149
|
+
raw.directories ??= defaultConfig().directories;
|
|
150
|
+
edit(raw);
|
|
151
|
+
const errors = validateConfig({ ...defaultConfig(), ...raw });
|
|
152
|
+
if (errors.length)
|
|
153
|
+
throw new Error(errors.join("\n"));
|
|
154
|
+
writeConfig(raw);
|
|
155
|
+
return raw;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Where watches pair from outside (what `overwatch pair` puts in its QR code, and `overwatch doctor`
|
|
159
|
+
* checks): what Tailscale Funnel forwards to the pairing port (`funnelPair`), whichever of its ports
|
|
160
|
+
* that is; else next to `secure.publicURL`: port 8443 when the API is on 443 (the usual Funnel
|
|
161
|
+
* layout), otherwise the local pairing port (a machine with its ports open).
|
|
162
|
+
*/
|
|
163
|
+
export function publicPairingURL(config, funnelPair) {
|
|
164
|
+
if (funnelPair)
|
|
165
|
+
return funnelPair;
|
|
166
|
+
if (!config.secure.publicURL)
|
|
167
|
+
return undefined;
|
|
168
|
+
const api = new URL(config.secure.publicURL);
|
|
169
|
+
const port = Number(api.port || 443) === 443 ? 8443 : config.secure.pairPort;
|
|
170
|
+
return `https://${api.hostname}:${port}`;
|
|
171
|
+
}
|
package/dist/daemon.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `overwatch daemon …` — run the bridge in the background as a macOS
|
|
3
|
+
* LaunchAgent, so it survives closed terminals and starts at login.
|
|
4
|
+
* `overwatch start` stays the foreground mode.
|
|
5
|
+
*/
|
|
6
|
+
import { execFile, spawn } from "node:child_process";
|
|
7
|
+
import { chmodSync, existsSync, mkdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { homedir, userInfo } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { overwatchHome } from "./config.js";
|
|
11
|
+
const LABEL = process.env.OVERWATCH_DAEMON_LABEL ?? "dev.agentoverwatch.bridge";
|
|
12
|
+
const MAX_LOG_BYTES = 5 * 1024 * 1024;
|
|
13
|
+
export const daemonLogPath = () => join(overwatchHome(), "bridge.log");
|
|
14
|
+
const plistPath = () => join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
15
|
+
const domain = () => `gui/${userInfo().uid}`;
|
|
16
|
+
function launchctl(args) {
|
|
17
|
+
return new Promise((resolve) => execFile("launchctl", args, (err, stdout, stderr) => {
|
|
18
|
+
const code = !err ? 0 : typeof err.code === "number" ? err.code : 1;
|
|
19
|
+
resolve({ code, out: `${stdout}${stderr}`.trim() });
|
|
20
|
+
}));
|
|
21
|
+
}
|
|
22
|
+
const xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
23
|
+
/** Single-quote for POSIX shells. */
|
|
24
|
+
const sq = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
|
|
25
|
+
function plist() {
|
|
26
|
+
// Run through the user's login + interactive shell so agents get the same
|
|
27
|
+
// environment (API keys, PATH) as a terminal would.
|
|
28
|
+
const shell = process.env.SHELL && existsSync(process.env.SHELL) ? process.env.SHELL : "/bin/zsh";
|
|
29
|
+
const cli = realpathSync(process.argv[1]);
|
|
30
|
+
const command = `exec ${sq(process.execPath)} ${sq(cli)} start`;
|
|
31
|
+
const env = {};
|
|
32
|
+
for (const k of [
|
|
33
|
+
"OVERWATCH_HOME",
|
|
34
|
+
"OVERWATCH_PORT",
|
|
35
|
+
"OVERWATCH_SECURE_PORT",
|
|
36
|
+
"OVERWATCH_PAIR_PORT",
|
|
37
|
+
"OVERWATCH_HOSTNAME",
|
|
38
|
+
"OVERWATCH_SECURE_HOSTNAME",
|
|
39
|
+
]) {
|
|
40
|
+
if (process.env[k])
|
|
41
|
+
env[k] = process.env[k];
|
|
42
|
+
}
|
|
43
|
+
const envXml = Object.keys(env).length
|
|
44
|
+
? ` <key>EnvironmentVariables</key>\n <dict>\n${Object.entries(env)
|
|
45
|
+
.map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}</string>`)
|
|
46
|
+
.join("\n")}\n </dict>\n`
|
|
47
|
+
: "";
|
|
48
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
49
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
50
|
+
<plist version="1.0">
|
|
51
|
+
<dict>
|
|
52
|
+
<key>Label</key><string>${xml(LABEL)}</string>
|
|
53
|
+
<key>ProgramArguments</key>
|
|
54
|
+
<array>
|
|
55
|
+
<string>${xml(shell)}</string>
|
|
56
|
+
<string>-lic</string>
|
|
57
|
+
<string>${xml(command)}</string>
|
|
58
|
+
</array>
|
|
59
|
+
<key>WorkingDirectory</key><string>${xml(homedir())}</string>
|
|
60
|
+
${envXml} <key>RunAtLoad</key><true/>
|
|
61
|
+
<key>KeepAlive</key>
|
|
62
|
+
<dict><key>SuccessfulExit</key><false/></dict>
|
|
63
|
+
<key>ThrottleInterval</key><integer>10</integer>
|
|
64
|
+
<key>ProcessType</key><string>Background</string>
|
|
65
|
+
<key>StandardOutPath</key><string>${xml(daemonLogPath())}</string>
|
|
66
|
+
<key>StandardErrorPath</key><string>${xml(daemonLogPath())}</string>
|
|
67
|
+
</dict>
|
|
68
|
+
</plist>
|
|
69
|
+
`;
|
|
70
|
+
}
|
|
71
|
+
export async function daemonStatus() {
|
|
72
|
+
const installed = existsSync(plistPath());
|
|
73
|
+
const r = await launchctl(["print", `${domain()}/${LABEL}`]);
|
|
74
|
+
if (r.code !== 0)
|
|
75
|
+
return { installed, loaded: false };
|
|
76
|
+
const pid = /^\s*pid = (\d+)/m.exec(r.out)?.[1];
|
|
77
|
+
const lastExit = /last exit code = ([^\n]+)/.exec(r.out)?.[1]?.trim();
|
|
78
|
+
return { installed, loaded: true, pid: pid ? Number(pid) : undefined, lastExit };
|
|
79
|
+
}
|
|
80
|
+
async function bridgeAnswers(config) {
|
|
81
|
+
try {
|
|
82
|
+
return (await fetch(`http://${config.listen.hostname}:${config.listen.port}/api/health`, { signal: AbortSignal.timeout(2000) })).ok;
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function waitForBridge(config, ms) {
|
|
89
|
+
const end = Date.now() + ms;
|
|
90
|
+
while (Date.now() < end) {
|
|
91
|
+
if (await bridgeAnswers(config))
|
|
92
|
+
return true;
|
|
93
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
94
|
+
}
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
function rotateLog() {
|
|
98
|
+
const log = daemonLogPath();
|
|
99
|
+
if (existsSync(log) && statSync(log).size > MAX_LOG_BYTES)
|
|
100
|
+
renameSync(log, `${log}.1`);
|
|
101
|
+
if (!existsSync(log))
|
|
102
|
+
writeFileSync(log, "", { mode: 0o600 });
|
|
103
|
+
chmodSync(log, 0o600);
|
|
104
|
+
}
|
|
105
|
+
export async function daemon(sub, config) {
|
|
106
|
+
if (process.platform !== "darwin") {
|
|
107
|
+
console.log("`overwatch daemon` uses launchd and is macOS-only. Elsewhere, run `overwatch start` under systemd or similar.");
|
|
108
|
+
return 1;
|
|
109
|
+
}
|
|
110
|
+
switch (sub) {
|
|
111
|
+
case "start": {
|
|
112
|
+
const st = await daemonStatus();
|
|
113
|
+
if (st.loaded) {
|
|
114
|
+
console.log(`Already running in the background${st.pid ? ` (pid ${st.pid})` : ""}. Use \`overwatch daemon restart\` to restart it.`);
|
|
115
|
+
return 0;
|
|
116
|
+
}
|
|
117
|
+
if (await bridgeAnswers(config)) {
|
|
118
|
+
console.log(`A bridge is already running on port ${config.listen.port}, probably \`overwatch start\` in a terminal.`);
|
|
119
|
+
console.log("Stop it (Ctrl-C) and run `overwatch daemon start` again.");
|
|
120
|
+
return 1;
|
|
121
|
+
}
|
|
122
|
+
mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
|
|
123
|
+
rotateLog();
|
|
124
|
+
writeFileSync(plistPath(), plist(), { mode: 0o644 });
|
|
125
|
+
const r = await launchctl(["bootstrap", domain(), plistPath()]);
|
|
126
|
+
if (r.code !== 0) {
|
|
127
|
+
console.log(`launchctl bootstrap failed: ${r.out}`);
|
|
128
|
+
return 1;
|
|
129
|
+
}
|
|
130
|
+
if (await waitForBridge(config, 15_000)) {
|
|
131
|
+
console.log("Bridge running in the background. It starts at login and restarts if it crashes.");
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
console.log("Started, but the bridge isn't answering yet. Check: overwatch daemon logs");
|
|
135
|
+
}
|
|
136
|
+
console.log(` logs: overwatch daemon logs (${daemonLogPath()})`);
|
|
137
|
+
console.log(" stop: overwatch daemon stop");
|
|
138
|
+
return 0;
|
|
139
|
+
}
|
|
140
|
+
case "stop": {
|
|
141
|
+
const st = await daemonStatus();
|
|
142
|
+
if (st.loaded)
|
|
143
|
+
await launchctl(["bootout", `${domain()}/${LABEL}`]);
|
|
144
|
+
rmSync(plistPath(), { force: true });
|
|
145
|
+
console.log(st.loaded || st.installed ? "Stopped. It won't start at login anymore." : "The bridge isn't running as a daemon.");
|
|
146
|
+
return 0;
|
|
147
|
+
}
|
|
148
|
+
case "restart": {
|
|
149
|
+
const st = await daemonStatus();
|
|
150
|
+
if (!st.loaded) {
|
|
151
|
+
console.log("Not running as a daemon. Start it with: overwatch daemon start");
|
|
152
|
+
return 1;
|
|
153
|
+
}
|
|
154
|
+
rotateLog();
|
|
155
|
+
await launchctl(["kickstart", "-k", `${domain()}/${LABEL}`]);
|
|
156
|
+
console.log((await waitForBridge(config, 15_000))
|
|
157
|
+
? "Restarted."
|
|
158
|
+
: "Restarted, but the bridge isn't answering yet. Check: overwatch daemon logs");
|
|
159
|
+
return 0;
|
|
160
|
+
}
|
|
161
|
+
case "status": {
|
|
162
|
+
const st = await daemonStatus();
|
|
163
|
+
const up = await bridgeAnswers(config);
|
|
164
|
+
if (st.loaded)
|
|
165
|
+
console.log(`Daemon: running${st.pid ? ` (pid ${st.pid})` : " (no process right now; launchd will retry)"}`);
|
|
166
|
+
else
|
|
167
|
+
console.log(`Daemon: not running${up ? " (a bridge is running in the foreground)" : ""}`);
|
|
168
|
+
console.log(`Bridge answering on port ${config.listen.port}: ${up ? "yes" : "no"}`);
|
|
169
|
+
console.log(`Logs: ${daemonLogPath()}`);
|
|
170
|
+
return st.loaded && up ? 0 : 1;
|
|
171
|
+
}
|
|
172
|
+
case "logs": {
|
|
173
|
+
if (!existsSync(daemonLogPath())) {
|
|
174
|
+
console.log("No daemon log yet.");
|
|
175
|
+
return 1;
|
|
176
|
+
}
|
|
177
|
+
const tail = spawn("tail", ["-n", "50", "-f", daemonLogPath()], { stdio: "inherit" });
|
|
178
|
+
await new Promise((r) => tail.on("exit", r));
|
|
179
|
+
return 0;
|
|
180
|
+
}
|
|
181
|
+
default:
|
|
182
|
+
console.log(`usage: overwatch daemon <start|stop|restart|status|logs>
|
|
183
|
+
|
|
184
|
+
start Run the bridge in the background (launchd); starts at login, restarts on crash
|
|
185
|
+
stop Stop it and remove it from login
|
|
186
|
+
restart Restart it (e.g. after editing the config)
|
|
187
|
+
status Is it running, and is the bridge answering?
|
|
188
|
+
logs Follow the bridge log`);
|
|
189
|
+
return sub ? 1 : 0;
|
|
190
|
+
}
|
|
191
|
+
}
|
package/dist/devices.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
const hash = (s) => createHash("sha256").update(s, "utf8").digest();
|
|
5
|
+
export class DeviceRegistry {
|
|
6
|
+
cache = [];
|
|
7
|
+
mtime = -1;
|
|
8
|
+
/** Per device: when we last wrote its lastSeenAt (writes are throttled to one a minute). */
|
|
9
|
+
lastTouchWrite = new Map();
|
|
10
|
+
home;
|
|
11
|
+
constructor(home) {
|
|
12
|
+
this.home = home;
|
|
13
|
+
}
|
|
14
|
+
get path() {
|
|
15
|
+
return join(this.home, "devices.json");
|
|
16
|
+
}
|
|
17
|
+
list() {
|
|
18
|
+
const path = this.path;
|
|
19
|
+
if (!existsSync(path))
|
|
20
|
+
return (this.cache = []);
|
|
21
|
+
const m = statSync(path).mtimeMs;
|
|
22
|
+
if (m !== this.mtime) {
|
|
23
|
+
try {
|
|
24
|
+
this.cache = JSON.parse(readFileSync(path, "utf8"));
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
// Every paired watch is locked out until it's fixed: say so loudly.
|
|
28
|
+
console.error(`could not read ${path}, so no watch can connect: ${e.message}`);
|
|
29
|
+
this.cache = [];
|
|
30
|
+
}
|
|
31
|
+
this.mtime = m;
|
|
32
|
+
}
|
|
33
|
+
return this.cache;
|
|
34
|
+
}
|
|
35
|
+
save(devices) {
|
|
36
|
+
const tmp = this.path + ".tmp";
|
|
37
|
+
writeFileSync(tmp, JSON.stringify(devices, null, 2) + "\n", { mode: 0o600 });
|
|
38
|
+
renameSync(tmp, this.path);
|
|
39
|
+
this.cache = devices;
|
|
40
|
+
this.mtime = statSync(this.path).mtimeMs;
|
|
41
|
+
}
|
|
42
|
+
/** Register a device and return its new bearer token (shown exactly once). */
|
|
43
|
+
add(name, certFingerprint) {
|
|
44
|
+
const token = randomBytes(32).toString("base64url");
|
|
45
|
+
const device = {
|
|
46
|
+
id: randomUUID(),
|
|
47
|
+
name,
|
|
48
|
+
tokenHash: hash(token).toString("hex"),
|
|
49
|
+
certFingerprint,
|
|
50
|
+
createdAt: Date.now(),
|
|
51
|
+
};
|
|
52
|
+
this.save([...this.list(), device]);
|
|
53
|
+
return { device, token };
|
|
54
|
+
}
|
|
55
|
+
/** Constant-time lookup of the device that owns `token`. */
|
|
56
|
+
findByToken(token) {
|
|
57
|
+
if (!token)
|
|
58
|
+
return undefined;
|
|
59
|
+
const presented = hash(token);
|
|
60
|
+
let match;
|
|
61
|
+
for (const d of this.list()) {
|
|
62
|
+
const stored = Buffer.from(d.tokenHash, "hex");
|
|
63
|
+
if (stored.length === presented.length && timingSafeEqual(stored, presented))
|
|
64
|
+
match = d;
|
|
65
|
+
}
|
|
66
|
+
if (match && Date.now() - (this.lastTouchWrite.get(match.id) ?? 0) > 60_000) {
|
|
67
|
+
this.lastTouchWrite.set(match.id, Date.now());
|
|
68
|
+
match.lastSeenAt = Date.now();
|
|
69
|
+
this.save(this.list().map((d) => (d.id === match.id ? { ...d, lastSeenAt: match.lastSeenAt } : d)));
|
|
70
|
+
}
|
|
71
|
+
return match;
|
|
72
|
+
}
|
|
73
|
+
/** Revoke by full id or a unique id prefix. Returns the removed device. */
|
|
74
|
+
revoke(idOrPrefix) {
|
|
75
|
+
const all = this.list();
|
|
76
|
+
const hits = all.filter((d) => d.id === idOrPrefix || d.id.startsWith(idOrPrefix));
|
|
77
|
+
if (hits.length !== 1)
|
|
78
|
+
return undefined;
|
|
79
|
+
this.save(all.filter((d) => d.id !== hits[0].id));
|
|
80
|
+
return hits[0];
|
|
81
|
+
}
|
|
82
|
+
}
|
package/dist/dirs.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `overwatch dirs …` — manage the directories the watch can start threads in.
|
|
3
|
+
* Run `overwatch dirs add` inside a project to make it pickable on the watch.
|
|
4
|
+
* A running bridge picks up changes within a second (no restart).
|
|
5
|
+
*/
|
|
6
|
+
import { realpathSync, statSync } from "node:fs";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { basename, resolve } from "node:path";
|
|
9
|
+
import { configPath, loadConfig, updateConfigFile } from "./config.js";
|
|
10
|
+
const USAGE = `usage: overwatch dirs [list]
|
|
11
|
+
overwatch dirs add [path] [--name "Display name"] (path defaults to the current directory)
|
|
12
|
+
overwatch dirs remove <id | path>`;
|
|
13
|
+
const tilde = (p) => (p === homedir() || p.startsWith(homedir() + "/") ? `~${p.slice(homedir().length)}` : p);
|
|
14
|
+
function slug(s) {
|
|
15
|
+
return (s
|
|
16
|
+
.toLowerCase()
|
|
17
|
+
.replace(/[^a-z0-9_.-]+/g, "-")
|
|
18
|
+
.replace(/^-+|-+$/g, "")
|
|
19
|
+
.slice(0, 48) || "dir");
|
|
20
|
+
}
|
|
21
|
+
function list(config) {
|
|
22
|
+
if (!config.directories.length) {
|
|
23
|
+
console.log("No directories yet. Add one with: overwatch dirs add [path]");
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const w = Math.max(...config.directories.map((d) => d.name.length));
|
|
27
|
+
for (const d of config.directories)
|
|
28
|
+
console.log(`${d.name.padEnd(w)} ${tilde(d.path)} (id: ${d.id})`);
|
|
29
|
+
}
|
|
30
|
+
export function dirs(args) {
|
|
31
|
+
const [sub = "list", ...rest] = args;
|
|
32
|
+
switch (sub) {
|
|
33
|
+
case "list":
|
|
34
|
+
case "ls":
|
|
35
|
+
list(loadConfig().config);
|
|
36
|
+
return 0;
|
|
37
|
+
case "add": {
|
|
38
|
+
let name;
|
|
39
|
+
let pathArg;
|
|
40
|
+
for (let i = 0; i < rest.length; i++) {
|
|
41
|
+
if (rest[i] === "--name")
|
|
42
|
+
name = rest[++i];
|
|
43
|
+
else if (rest[i].startsWith("--name="))
|
|
44
|
+
name = rest[i].slice(7);
|
|
45
|
+
else if (!pathArg)
|
|
46
|
+
pathArg = rest[i];
|
|
47
|
+
else {
|
|
48
|
+
console.log(USAGE);
|
|
49
|
+
return 1;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
let path;
|
|
53
|
+
try {
|
|
54
|
+
path = realpathSync(resolve(pathArg ?? "."));
|
|
55
|
+
if (!statSync(path).isDirectory())
|
|
56
|
+
throw new Error("not a directory");
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
console.log(`Not a directory: ${pathArg ?? "."}`);
|
|
60
|
+
return 1;
|
|
61
|
+
}
|
|
62
|
+
name = (name ?? basename(path)).trim() || path;
|
|
63
|
+
const existing = loadConfig().config.directories.find((d) => d.path === path);
|
|
64
|
+
if (existing) {
|
|
65
|
+
console.log(`Already added as "${existing.name}" (id: ${existing.id}).`);
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
updateConfigFile((c) => {
|
|
69
|
+
const taken = new Set(c.directories.map((d) => d.id));
|
|
70
|
+
let id = slug(name);
|
|
71
|
+
for (let n = 2; taken.has(id); n++)
|
|
72
|
+
id = `${slug(name)}-${n}`;
|
|
73
|
+
c.directories.push({ id, name: name.slice(0, 64), path });
|
|
74
|
+
});
|
|
75
|
+
console.log(`Added "${name}" → ${tilde(path)}. It shows up in the watch's Directory picker.`);
|
|
76
|
+
return 0;
|
|
77
|
+
}
|
|
78
|
+
case "remove":
|
|
79
|
+
case "rm": {
|
|
80
|
+
const target = rest[0];
|
|
81
|
+
if (!target) {
|
|
82
|
+
console.log(USAGE);
|
|
83
|
+
return 1;
|
|
84
|
+
}
|
|
85
|
+
let asPath;
|
|
86
|
+
try {
|
|
87
|
+
asPath = realpathSync(resolve(target));
|
|
88
|
+
}
|
|
89
|
+
catch { }
|
|
90
|
+
let removed;
|
|
91
|
+
updateConfigFile((c) => {
|
|
92
|
+
const i = c.directories.findIndex((d) => d.id === target || d.path === asPath);
|
|
93
|
+
if (i >= 0)
|
|
94
|
+
removed = c.directories.splice(i, 1)[0].name;
|
|
95
|
+
});
|
|
96
|
+
if (!removed) {
|
|
97
|
+
console.log(`No directory "${target}". See: overwatch dirs`);
|
|
98
|
+
return 1;
|
|
99
|
+
}
|
|
100
|
+
console.log(`Removed "${removed}". Existing threads there keep running.`);
|
|
101
|
+
return 0;
|
|
102
|
+
}
|
|
103
|
+
default:
|
|
104
|
+
console.log(`${USAGE}\n\nConfig: ${configPath()}`);
|
|
105
|
+
return sub === "help" || sub === "--help" ? 0 : 1;
|
|
106
|
+
}
|
|
107
|
+
}
|
package/dist/errors.js
ADDED
package/dist/events.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A monotonically increasing version counter with long-poll support. Anything
|
|
3
|
+
* that changes state the watch cares about calls `bump()`; clients call
|
|
4
|
+
* `waitForChange(since, ms)` to block until there is something new.
|
|
5
|
+
*/
|
|
6
|
+
export class ChangeFeed {
|
|
7
|
+
version = 1;
|
|
8
|
+
waiters = new Set();
|
|
9
|
+
listeners = new Set();
|
|
10
|
+
get current() {
|
|
11
|
+
return this.version;
|
|
12
|
+
}
|
|
13
|
+
bump() {
|
|
14
|
+
this.version++;
|
|
15
|
+
for (const w of this.waiters)
|
|
16
|
+
w();
|
|
17
|
+
this.waiters.clear();
|
|
18
|
+
for (const l of this.listeners)
|
|
19
|
+
l(this.version);
|
|
20
|
+
}
|
|
21
|
+
subscribe(fn) {
|
|
22
|
+
this.listeners.add(fn);
|
|
23
|
+
return () => this.listeners.delete(fn);
|
|
24
|
+
}
|
|
25
|
+
waitForChange(since, timeoutMs) {
|
|
26
|
+
if (since !== this.version || timeoutMs <= 0)
|
|
27
|
+
return Promise.resolve();
|
|
28
|
+
return new Promise((resolve) => {
|
|
29
|
+
const done = () => {
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
this.waiters.delete(done);
|
|
32
|
+
resolve();
|
|
33
|
+
};
|
|
34
|
+
const timer = setTimeout(done, timeoutMs);
|
|
35
|
+
this.waiters.add(done);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|