@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.
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Short, watch-sized summaries of what an agent did: "+12 −3" per edit, and
3
+ * per turn "Edited 2 files (+12 −3) · ran 3 commands · read 4 files".
4
+ */
5
+ /**
6
+ * Lines added and removed between two versions of a file. A multiset
7
+ * comparison rather than a real diff: exact for pure additions/removals and
8
+ * close enough for edits, at O(n) cost.
9
+ */
10
+ export function diffStats(oldText, newText) {
11
+ const oldLines = oldText ? oldText.split("\n") : [];
12
+ const newLines = newText ? newText.split("\n") : [];
13
+ const counts = new Map();
14
+ for (const l of oldLines)
15
+ counts.set(l, (counts.get(l) ?? 0) + 1);
16
+ let added = 0;
17
+ for (const l of newLines) {
18
+ const n = counts.get(l) ?? 0;
19
+ if (n > 0)
20
+ counts.set(l, n - 1);
21
+ else
22
+ added++;
23
+ }
24
+ let removed = 0;
25
+ for (const n of counts.values())
26
+ removed += n;
27
+ return { added, removed };
28
+ }
29
+ export const formatStats = (s) => `+${s.added} −${s.removed}`;
30
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
31
+ /** "Edited 2 files (+12 −3) · ran 3 commands · read 4 files", or undefined if nothing happened. */
32
+ export function summarizeTurn(tools) {
33
+ const done = tools.filter((t) => t.status !== "failed" && t.status !== "cancelled");
34
+ const edited = new Set();
35
+ const total = { added: 0, removed: 0 };
36
+ let commands = 0;
37
+ const read = new Set();
38
+ let searches = 0;
39
+ for (const t of done) {
40
+ if (t.kind === "edit" || t.kind === "delete" || t.kind === "move" || t.stats) {
41
+ t.paths.forEach((p) => edited.add(p));
42
+ if (t.stats) {
43
+ total.added += t.stats.added;
44
+ total.removed += t.stats.removed;
45
+ }
46
+ }
47
+ else if (t.kind === "execute")
48
+ commands++;
49
+ else if (t.kind === "read")
50
+ t.paths.forEach((p) => read.add(p));
51
+ else if (t.kind === "search")
52
+ searches++;
53
+ }
54
+ const failed = tools.length - done.length;
55
+ const parts = [];
56
+ if (edited.size)
57
+ parts.push(`Edited ${plural(edited.size, "file")} (${formatStats(total)})`);
58
+ if (commands)
59
+ parts.push(`ran ${plural(commands, "command")}`);
60
+ if (read.size)
61
+ parts.push(`read ${plural(read.size, "file")}`);
62
+ if (searches)
63
+ parts.push(plural(searches, "search", "searches"));
64
+ if (failed)
65
+ parts.push(`${failed} failed`);
66
+ if (!parts.length)
67
+ return undefined;
68
+ const s = parts.join(" · ");
69
+ return s[0].toUpperCase() + s.slice(1);
70
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Finds the bridge's public URLs from Tailscale Funnel, so `secure.publicURL`
3
+ * doesn't have to be configured: if Funnel forwards raw TCP to the bridge's
4
+ * mTLS and pairing ports, those are the addresses the watch should use.
5
+ */
6
+ import { execFileSync } from "node:child_process";
7
+ import { existsSync } from "node:fs";
8
+ const CANDIDATES = [
9
+ "tailscale",
10
+ "/usr/local/bin/tailscale",
11
+ "/opt/homebrew/bin/tailscale",
12
+ "/Applications/Tailscale.app/Contents/MacOS/Tailscale",
13
+ ];
14
+ function funnelStatus() {
15
+ for (const bin of CANDIDATES) {
16
+ if (bin.includes("/") && !existsSync(bin))
17
+ continue;
18
+ try {
19
+ const out = execFileSync(bin, ["funnel", "status", "--json"], {
20
+ encoding: "utf8",
21
+ timeout: 3000,
22
+ stdio: ["ignore", "pipe", "ignore"],
23
+ });
24
+ return JSON.parse(out);
25
+ }
26
+ catch {
27
+ // not installed / not logged in / no Funnel: try the next location
28
+ }
29
+ }
30
+ return undefined;
31
+ }
32
+ /** Public URLs Funnel exposes for the given local ports, if any. */
33
+ export function funnelURLs(securePort, pairPort, status = funnelStatus()) {
34
+ const out = {};
35
+ if (!status?.TCP)
36
+ return out;
37
+ for (const [hostPort, allowed] of Object.entries(status.AllowFunnel ?? {})) {
38
+ if (!allowed)
39
+ continue;
40
+ const i = hostPort.lastIndexOf(":");
41
+ const host = hostPort.slice(0, i);
42
+ const port = hostPort.slice(i + 1);
43
+ const target = status.TCP[port]?.TCPForward ?? "";
44
+ const url = `https://${host}${port === "443" ? "" : `:${port}`}`;
45
+ if (target.endsWith(`:${securePort}`))
46
+ out.api ??= url;
47
+ if (target.endsWith(`:${pairPort}`))
48
+ out.pair ??= url;
49
+ }
50
+ return out;
51
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Threads and each agent's default settings on disk (threads.json and
3
+ * agent-settings.json in the overwatch home, 0600), written atomically.
4
+ * With no path (tests), nothing is read or written.
5
+ */
6
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ const MAX_THREADS_PERSISTED = 200;
9
+ const SAVE_DELAY_MS = 1000;
10
+ export class ThreadStore {
11
+ path;
12
+ log;
13
+ timer = null;
14
+ pending = null;
15
+ constructor(path, log) {
16
+ this.path = path;
17
+ this.log = log;
18
+ }
19
+ loadThreads() {
20
+ return this.read(this.path, "threads") ?? [];
21
+ }
22
+ /** Save soon (changes come in bursts while an agent streams). */
23
+ scheduleSave(threads) {
24
+ this.pending = threads;
25
+ if (!this.path || this.timer)
26
+ return;
27
+ this.timer = setTimeout(() => {
28
+ this.timer = null;
29
+ this.flush();
30
+ }, SAVE_DELAY_MS);
31
+ }
32
+ /** Save now (e.g. on shutdown). The most recently updated threads are kept. */
33
+ flush(threads) {
34
+ const source = threads ?? this.pending;
35
+ if (!this.path || !source)
36
+ return;
37
+ const keep = [...source()]
38
+ .filter((t) => t.status !== "closed")
39
+ .sort((a, b) => b.updatedAt - a.updatedAt)
40
+ .slice(0, MAX_THREADS_PERSISTED);
41
+ this.write(this.path, keep, "threads");
42
+ }
43
+ loadAgentDefaults() {
44
+ return this.read(this.agentSettingsPath(), "agent settings") ?? {};
45
+ }
46
+ saveAgentDefaults(defaults) {
47
+ const path = this.agentSettingsPath();
48
+ if (path)
49
+ this.write(path, defaults, "agent settings");
50
+ }
51
+ agentSettingsPath() {
52
+ return this.path ? join(dirname(this.path), "agent-settings.json") : null;
53
+ }
54
+ read(path, what) {
55
+ if (!path || !existsSync(path))
56
+ return undefined;
57
+ try {
58
+ return JSON.parse(readFileSync(path, "utf8"));
59
+ }
60
+ catch (e) {
61
+ this.log(`could not read ${what} (${path}): ${e.message}`);
62
+ return undefined;
63
+ }
64
+ }
65
+ write(path, data, what) {
66
+ try {
67
+ writeFileSync(path + ".tmp", JSON.stringify(data), { mode: 0o600 });
68
+ renameSync(path + ".tmp", path);
69
+ }
70
+ catch (e) {
71
+ this.log(`failed to save ${what} (${path}): ${e.message}`);
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * A thread's transcript: what the watch shows, built from the agent's updates.
3
+ * Plain functions over the persisted array, so threads.json stays plain data.
4
+ */
5
+ import { randomUUID } from "node:crypto";
6
+ import { contentToText } from "./acp/types.js";
7
+ import { diffStats, formatStats, summarizeTurn } from "./summaries.js";
8
+ export const MAX_TRANSCRIPT_ITEMS = 400;
9
+ const MAX_ITEM_TEXT = 20_000;
10
+ export function clip(s, n) {
11
+ return s.length > n ? s.slice(0, n - 1) + "…" : s;
12
+ }
13
+ export function push(t, item) {
14
+ t.transcript.push({ ...item, text: clip(item.text, MAX_ITEM_TEXT), id: randomUUID(), at: Date.now() });
15
+ trim(t);
16
+ }
17
+ function trim(t) {
18
+ if (t.transcript.length > MAX_TRANSCRIPT_ITEMS)
19
+ t.transcript.splice(0, t.transcript.length - MAX_TRANSCRIPT_ITEMS);
20
+ }
21
+ /** Streamed text: extends the last item of the same kind, or starts a new one. */
22
+ export function appendChunk(t, kind, text) {
23
+ if (!text)
24
+ return;
25
+ const last = t.transcript.at(-1);
26
+ if (last && last.kind === kind) {
27
+ last.text = clip(last.text + text, MAX_ITEM_TEXT);
28
+ last.at = Date.now();
29
+ }
30
+ else {
31
+ push(t, { kind, text });
32
+ }
33
+ }
34
+ /** The plan replaces the previous one if nothing came in between. */
35
+ export function setPlan(t, entries) {
36
+ const text = entries.map((e) => `${e.status === "completed" ? "✓" : e.status === "in_progress" ? "▸" : "○"} ${e.content}`).join("\n");
37
+ const last = t.transcript.at(-1);
38
+ if (last?.kind === "plan") {
39
+ last.text = text;
40
+ last.at = Date.now();
41
+ }
42
+ else {
43
+ push(t, { kind: "plan", text, title: "Plan" });
44
+ }
45
+ }
46
+ /** A tool call or an update to one. Returns its transcript item. */
47
+ export function upsertTool(t, tc) {
48
+ const id = `tool:${tc.toolCallId}`;
49
+ let item = t.transcript.find((i) => i.id === id);
50
+ if (!item) {
51
+ item = { id, kind: "tool", text: "", title: tc.title ?? "Tool call", status: tc.status ?? "pending", at: Date.now() };
52
+ t.transcript.push(item);
53
+ trim(t);
54
+ }
55
+ if (t.turnToolIds && !t.turnToolIds.includes(id))
56
+ t.turnToolIds.push(id);
57
+ const diffs = (tc.content ?? []).filter((c) => c.type === "diff");
58
+ if (diffs.length) {
59
+ const stats = { added: 0, removed: 0 };
60
+ for (const d of diffs) {
61
+ const s = diffStats(d.oldText, d.newText);
62
+ stats.added += s.added;
63
+ stats.removed += s.removed;
64
+ }
65
+ item.stats = stats;
66
+ item.paths = [...new Set(diffs.map((d) => d.path))];
67
+ }
68
+ else if (tc.locations?.length) {
69
+ item.paths = [...new Set(tc.locations.map((l) => l.path))];
70
+ }
71
+ if (tc.title)
72
+ item.title = clip(tc.title, 200);
73
+ if (tc.status)
74
+ item.status = tc.status;
75
+ if (tc.kind)
76
+ item.toolKind = tc.kind;
77
+ const detail = describeToolCall(tc);
78
+ if (detail)
79
+ item.text = clip(detail, 2000);
80
+ item.at = Date.now();
81
+ return item;
82
+ }
83
+ export function toolItem(t, toolCallId) {
84
+ return t.transcript.find((i) => i.id === `tool:${toolCallId}`);
85
+ }
86
+ /** Tool calls still running are marked cancelled (the turn was stopped). */
87
+ export function cancelRunningTools(t) {
88
+ for (const item of t.transcript) {
89
+ if (item.kind === "tool" && (item.status === "pending" || item.status === "in_progress"))
90
+ item.status = "cancelled";
91
+ }
92
+ }
93
+ /** "Edited 2 files (+12 −3) · ran 3 commands" for the turn that just ended; starts the next one empty. */
94
+ export function endTurn(t) {
95
+ const ids = new Set(t.turnToolIds ?? []);
96
+ t.turnToolIds = [];
97
+ const tools = t.transcript.filter((i) => i.kind === "tool" && ids.has(i.id));
98
+ return summarizeTurn(tools.map((i) => ({ kind: i.toolKind, status: i.status, paths: i.paths ?? [], stats: i.stats })));
99
+ }
100
+ export function lastAgentText(t) {
101
+ for (let i = t.transcript.length - 1; i >= 0; i--) {
102
+ const item = t.transcript[i];
103
+ if (item.kind === "agent" && item.text.trim())
104
+ return item.text.trim();
105
+ }
106
+ return "";
107
+ }
108
+ /** The last turn's summary, if no newer message from you has started another turn. */
109
+ export function latestTurnSummary(t) {
110
+ for (let i = t.transcript.length - 1; i >= 0; i--) {
111
+ const item = t.transcript[i];
112
+ if (item.kind === "summary")
113
+ return item.text;
114
+ if (item.kind === "user")
115
+ return undefined;
116
+ }
117
+ return undefined;
118
+ }
119
+ /** The one-line preview in thread lists: the last message, or the last tool call. */
120
+ export function preview(t) {
121
+ const last = [...t.transcript].reverse().find((i) => i.kind === "agent" || i.kind === "user" || i.kind === "tool");
122
+ const text = last ? (last.kind === "tool" ? `⚙︎ ${last.title ?? ""}` : last.text) : "";
123
+ return clip(text.replace(/\s+/g, " ").trim(), 160);
124
+ }
125
+ /** The transcript as text (no thoughts), e.g. for finding links. */
126
+ export function plainText(t) {
127
+ return t.transcript
128
+ .filter((i) => i.kind !== "thought")
129
+ .map((i) => i.text)
130
+ .join("\n");
131
+ }
132
+ /** Human-readable one-liner for what a tool call is about to do / did. */
133
+ export function describeToolCall(tc) {
134
+ const parts = [];
135
+ for (const c of tc.content ?? []) {
136
+ if (c.type === "diff") {
137
+ parts.push(`${c.path.split("/").pop()} ${formatStats(diffStats(c.oldText, c.newText))}`);
138
+ }
139
+ else if (c.type === "content") {
140
+ const text = contentToText(c.content).trim();
141
+ if (text)
142
+ parts.push(text);
143
+ }
144
+ else if (c.type === "terminal") {
145
+ parts.push("[terminal output]");
146
+ }
147
+ }
148
+ if (!parts.length && tc.rawInput !== undefined && tc.rawInput !== null) {
149
+ const ri = tc.rawInput;
150
+ const cmd = typeof ri?.command === "string" ? ri.command : undefined;
151
+ parts.push(cmd ?? clip(JSON.stringify(tc.rawInput), 600));
152
+ }
153
+ if (!parts.length && tc.locations?.length)
154
+ parts.push(tc.locations.map((l) => l.path).join(", "));
155
+ return parts.length ? clip(parts.join("\n"), 2000) : undefined;
156
+ }
157
+ const PR_URL = /https:\/\/github\.com\/([A-Za-z0-9-]{1,39})\/([A-Za-z0-9_.-]{1,100})\/pull\/(\d{1,9})/g;
158
+ const LINEAR_URL = /https:\/\/linear\.app\/[A-Za-z0-9_-]{1,64}\/issue\/([A-Z][A-Z0-9]{0,9}-\d{1,7})(?:\/[A-Za-z0-9-]*)?/g;
159
+ /** GitHub PR and Linear issue links mentioned in some text. */
160
+ export function findLinks(text) {
161
+ const out = [];
162
+ for (const m of text.matchAll(PR_URL))
163
+ out.push({ kind: "github_pr", id: `${m[1]}/${m[2]}#${m[3]}`, url: `https://github.com/${m[1]}/${m[2]}/pull/${m[3]}` });
164
+ for (const m of text.matchAll(LINEAR_URL))
165
+ out.push({ kind: "linear_issue", id: m[1], url: m[0] });
166
+ return out;
167
+ }
@@ -0,0 +1,4 @@
1
+ import { readFileSync } from "node:fs";
2
+ /** This package's version (from package.json, which sits one level up from both src/ and dist/). */
3
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"))
4
+ .version;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Optional git worktree per thread: the agent works on its own branch in its
3
+ * own checkout, so several agents can run in one repo without stepping on each
4
+ * other. Worktrees share the repo's object store, so each costs only its
5
+ * checked-out files (plus whatever the agent installs, e.g. node_modules).
6
+ *
7
+ * Layout: ~/.agent-overwatch/worktrees/<repo>-<hash>/<slug>, on branch overwatch/<slug>.
8
+ *
9
+ * Cleanup never loses work: a worktree is only removed when it has no
10
+ * uncommitted changes and no commits that aren't on another branch or remote.
11
+ * Otherwise it's kept and reported (`overwatch worktrees`). Branches with
12
+ * commits are always kept.
13
+ */
14
+ import { execFile } from "node:child_process";
15
+ import { createHash, randomBytes } from "node:crypto";
16
+ import { existsSync, mkdirSync, readdirSync } from "node:fs";
17
+ import { basename, dirname, join, relative } from "node:path";
18
+ import { overwatchHome } from "./config.js";
19
+ /** A branch name we'll pass to git (also checked with `git check-ref-format`). */
20
+ const BRANCH_RE = /^(?!-)(?!.*\.\.)(?!.*\/\/)(?!.*@\{)(?!.*\.lock$)[A-Za-z0-9._/-]{1,100}(?<![/.])$/;
21
+ export function git(args, cwd) {
22
+ return new Promise((resolve) => execFile("git", args, { cwd, timeout: 60_000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => resolve({ ok: !err, out: (err ? `${stderr || stdout || err.message}` : stdout).trim() })));
23
+ }
24
+ export const worktreeRoot = () => join(overwatchHome(), "worktrees");
25
+ /** The repository's top-level directory, or undefined if `dir` isn't in a git work tree. */
26
+ export async function repoRoot(dir) {
27
+ const r = await git(["rev-parse", "--show-toplevel"], dir);
28
+ return r.ok && r.out ? r.out : undefined;
29
+ }
30
+ const gitDirs = new Map();
31
+ /** Whether `dir` is inside a git work tree (looks for .git upward; cached). For the watch's "New branch" toggle. */
32
+ export function isInGitRepo(dir) {
33
+ const cached = gitDirs.get(dir);
34
+ if (cached !== undefined)
35
+ return cached;
36
+ let d = dir;
37
+ let found = false;
38
+ for (;;) {
39
+ if (existsSync(join(d, ".git"))) {
40
+ found = true;
41
+ break;
42
+ }
43
+ const up = dirname(d);
44
+ if (up === d)
45
+ break;
46
+ d = up;
47
+ }
48
+ gitDirs.set(dir, found);
49
+ return found;
50
+ }
51
+ /** A branch-safe slug from the prompt: "Fix the flaky login test!" → "fix-the-flaky-login-test-3f9a". */
52
+ export function slugFor(prompt) {
53
+ const words = prompt
54
+ .toLowerCase()
55
+ .replace(/[^a-z0-9]+/g, " ")
56
+ .trim()
57
+ .split(" ")
58
+ .filter(Boolean)
59
+ .slice(0, 6)
60
+ .join("-")
61
+ .slice(0, 40)
62
+ .replace(/-+$/, "");
63
+ return `${words || "thread"}-${randomBytes(2).toString("hex")}`;
64
+ }
65
+ /**
66
+ * Create a worktree on a new branch from the repo's current HEAD (named after the prompt, or
67
+ * `branchName`, e.g. a Linear issue's suggested branch; an existing branch of that name is
68
+ * checked out instead). Returns the worktree and the directory the agent should run in (the
69
+ * same subdirectory of the repo the configured directory points at).
70
+ */
71
+ export async function createWorktree(dir, prompt, branchName) {
72
+ const repo = await repoRoot(dir);
73
+ if (!repo)
74
+ throw new Error(`${dir} isn't in a git repository`);
75
+ const slug = slugFor(branchName ?? prompt);
76
+ if (!/^[a-z0-9-]{1,60}$/.test(slug))
77
+ throw new Error("couldn't make a branch name");
78
+ let branch = `overwatch/${slug}`;
79
+ let existingBranch = false;
80
+ if (branchName) {
81
+ if (!BRANCH_RE.test(branchName) || !(await git(["check-ref-format", "--branch", branchName], repo)).ok)
82
+ throw new Error(`"${branchName}" isn't a usable branch name`);
83
+ branch = branchName;
84
+ existingBranch = (await git(["rev-parse", "--verify", "--quiet", `refs/heads/${branchName}`], repo)).ok;
85
+ }
86
+ const repoDir = join(worktreeRoot(), `${basename(repo).replace(/[^A-Za-z0-9._-]/g, "_")}-${createHash("sha256").update(repo).digest("hex").slice(0, 6)}`);
87
+ mkdirSync(repoDir, { recursive: true, mode: 0o700 });
88
+ const path = join(repoDir, slug);
89
+ const r = await git(existingBranch ? ["worktree", "add", path, branch] : ["worktree", "add", "-b", branch, path, "HEAD"], repo);
90
+ if (!r.ok)
91
+ throw new Error(`git worktree add failed: ${r.out}`);
92
+ const sub = relative(repo, dir);
93
+ return {
94
+ worktree: { repo, path, branch, ...(existingBranch ? { existingBranch } : {}) },
95
+ cwd: sub && !sub.startsWith("..") ? join(path, sub) : path,
96
+ };
97
+ }
98
+ /** Uncommitted files, and commits on the branch that no other branch or remote has. */
99
+ export async function worktreeStatus(wt) {
100
+ if (!existsSync(wt.path))
101
+ return { dirty: 0, unique: 0, missing: true };
102
+ const status = await git(["status", "--porcelain"], wt.path);
103
+ const dirty = status.ok ? status.out.split("\n").filter(Boolean).length : 1;
104
+ const refs = await git(["for-each-ref", "--format=%(refname)", "refs/heads", "refs/remotes"], wt.repo);
105
+ const others = refs.ok ? refs.out.split("\n").filter((r) => r && r !== `refs/heads/${wt.branch}`) : [];
106
+ const count = await git(["rev-list", "--count", `refs/heads/${wt.branch}`, "--not", ...others], wt.repo);
107
+ const unique = count.ok ? Number(count.out) || 0 : 1;
108
+ return { dirty, unique, missing: false };
109
+ }
110
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
111
+ /** Remove a worktree if that loses nothing; otherwise keep it and say why. */
112
+ export async function removeWorktree(wt) {
113
+ const s = await worktreeStatus(wt);
114
+ if (s.missing) {
115
+ await git(["worktree", "prune"], wt.repo);
116
+ if (!wt.existingBranch)
117
+ await git(["branch", "-d", wt.branch], wt.repo);
118
+ return { removed: true };
119
+ }
120
+ if (s.dirty || s.unique) {
121
+ const why = [
122
+ s.dirty ? plural(s.dirty, "uncommitted change") : "",
123
+ s.unique ? plural(s.unique, "commit") + " not on another branch" : "",
124
+ ]
125
+ .filter(Boolean)
126
+ .join(", ");
127
+ return { removed: false, kept: `kept ${wt.path} (${why}; branch ${wt.branch})` };
128
+ }
129
+ const r = await git(["worktree", "remove", wt.path], wt.repo); // no --force: git refuses if anything changed meanwhile
130
+ if (!r.ok)
131
+ return { removed: false, kept: `kept ${wt.path}: ${r.out}` };
132
+ if (!wt.existingBranch)
133
+ await git(["branch", "-d", wt.branch], wt.repo); // only succeeds when it adds nothing
134
+ return { removed: true };
135
+ }
136
+ /** Every worktree under ~/.agent-overwatch/worktrees, for `overwatch worktrees`. */
137
+ export async function listWorktrees() {
138
+ const root = worktreeRoot();
139
+ if (!existsSync(root))
140
+ return [];
141
+ const out = [];
142
+ for (const group of readdirSync(root)) {
143
+ for (const name of readdirSync(join(root, group))) {
144
+ const path = join(root, group, name);
145
+ const top = await repoRoot(path);
146
+ if (!top)
147
+ continue;
148
+ const common = await git(["rev-parse", "--path-format=absolute", "--git-common-dir"], path);
149
+ const branch = await git(["branch", "--show-current"], path);
150
+ if (!common.ok || !branch.ok)
151
+ continue;
152
+ const wt = { repo: common.out.replace(/\/\.git$/, ""), path, branch: branch.out };
153
+ out.push({ ...wt, ...(await worktreeStatus(wt)) });
154
+ }
155
+ }
156
+ return out;
157
+ }
package/dist/x509.js ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Just enough X.509 to run a private, per-bridge certificate authority with
3
+ * ECDSA P-256 — no OpenSSL or third-party dependencies. Certificates are built
4
+ * as DER by hand and signed with node:crypto.
5
+ */
6
+ import { createHash, createPublicKey, randomBytes, sign } from "node:crypto";
7
+ import { isIP } from "node:net";
8
+ // ---- DER primitives --------------------------------------------------------
9
+ function len(n) {
10
+ if (n < 0x80)
11
+ return Buffer.from([n]);
12
+ const bytes = [];
13
+ while (n > 0) {
14
+ bytes.unshift(n & 0xff);
15
+ n >>= 8;
16
+ }
17
+ return Buffer.from([0x80 | bytes.length, ...bytes]);
18
+ }
19
+ const tlv = (tag, body) => Buffer.concat([Buffer.from([tag]), len(body.length), body]);
20
+ const seq = (...items) => tlv(0x30, Buffer.concat(items));
21
+ const set = (...items) => tlv(0x31, Buffer.concat(items));
22
+ const octet = (b) => tlv(0x04, b);
23
+ const bitString = (b, unusedBits = 0) => tlv(0x03, Buffer.concat([Buffer.from([unusedBits]), b]));
24
+ const bool = (v) => tlv(0x01, Buffer.from([v ? 0xff : 0x00]));
25
+ const utf8 = (s) => tlv(0x0c, Buffer.from(s, "utf8"));
26
+ const explicit = (n, body) => tlv(0xa0 + n, body);
27
+ function uint(b) {
28
+ let i = 0;
29
+ while (i < b.length - 1 && b[i] === 0)
30
+ i++;
31
+ let v = b.subarray(i);
32
+ if (v[0] & 0x80)
33
+ v = Buffer.concat([Buffer.from([0]), v]);
34
+ return tlv(0x02, v);
35
+ }
36
+ function oid(dotted) {
37
+ const parts = dotted.split(".").map(Number);
38
+ const out = [40 * parts[0] + parts[1]];
39
+ for (const p of parts.slice(2)) {
40
+ const stack = [p & 0x7f];
41
+ let v = p >>> 7;
42
+ while (v > 0) {
43
+ stack.unshift((v & 0x7f) | 0x80);
44
+ v >>>= 7;
45
+ }
46
+ out.push(...stack);
47
+ }
48
+ return tlv(0x06, Buffer.from(out));
49
+ }
50
+ function time(d) {
51
+ const iso = d.toISOString(); // YYYY-MM-DDTHH:MM:SS.sssZ
52
+ const compact = iso.slice(0, 19).replace(/[-:T]/g, "") + "Z"; // YYYYMMDDHHMMSSZ
53
+ // RFC 5280: UTCTime through 2049, GeneralizedTime after.
54
+ return d.getUTCFullYear() < 2050 ? tlv(0x17, Buffer.from(compact.slice(2))) : tlv(0x18, Buffer.from(compact));
55
+ }
56
+ // ---- X.509 pieces ------------------------------------------------------------
57
+ const ECDSA_SHA256 = seq(oid("1.2.840.10045.4.3.2"));
58
+ const OID = {
59
+ cn: "2.5.4.3",
60
+ org: "2.5.4.10",
61
+ basicConstraints: "2.5.29.19",
62
+ keyUsage: "2.5.29.15",
63
+ extKeyUsage: "2.5.29.37",
64
+ subjectAltName: "2.5.29.17",
65
+ subjectKeyId: "2.5.29.14",
66
+ authorityKeyId: "2.5.29.35",
67
+ serverAuth: "1.3.6.1.5.5.7.3.1",
68
+ clientAuth: "1.3.6.1.5.5.7.3.2",
69
+ };
70
+ function name(cn) {
71
+ return seq(set(seq(oid(OID.org), utf8("Agent Overwatch"))), set(seq(oid(OID.cn), utf8(cn))));
72
+ }
73
+ function ext(id, critical, value) {
74
+ return critical ? seq(oid(id), bool(true), octet(value)) : seq(oid(id), octet(value));
75
+ }
76
+ /** The subjectPublicKey BIT STRING contents, hashed for key identifiers (RFC 5280 method 1). */
77
+ function keyId(spki) {
78
+ const pub = createPublicKey({ key: spki, format: "der", type: "spki" });
79
+ const raw = pub.export({ format: "jwk" });
80
+ const point = Buffer.concat([Buffer.from([4]), Buffer.from(raw.x, "base64url"), Buffer.from(raw.y, "base64url")]);
81
+ return createHash("sha1").update(point).digest();
82
+ }
83
+ export function issueCertificate(o) {
84
+ const spki = o.subjectPublicKey.export({ format: "der", type: "spki" });
85
+ const issuerSpki = o.issuerPublicKey.export({ format: "der", type: "spki" });
86
+ const serial = randomBytes(16);
87
+ serial[0] &= 0x7f; // positive
88
+ const notBefore = new Date(Date.now() - 5 * 60 * 1000); // tolerate small clock skew
89
+ const notAfter = new Date(Date.now() + o.validDays * 24 * 60 * 60 * 1000);
90
+ const exts = [];
91
+ if (o.role === "ca") {
92
+ exts.push(ext(OID.basicConstraints, true, seq(bool(true), uint(Buffer.from([0])))));
93
+ // keyCertSign (bit 5) + cRLSign (bit 6) → 0b0000_0110, 1 unused bit
94
+ exts.push(ext(OID.keyUsage, true, bitString(Buffer.from([0x06]), 1)));
95
+ }
96
+ else {
97
+ exts.push(ext(OID.basicConstraints, true, seq()));
98
+ // digitalSignature (bit 0) → 0b1000_0000, 7 unused bits
99
+ exts.push(ext(OID.keyUsage, true, bitString(Buffer.from([0x80]), 7)));
100
+ exts.push(ext(OID.extKeyUsage, false, seq(oid(o.role === "server" ? OID.serverAuth : OID.clientAuth))));
101
+ }
102
+ if (o.role === "server") {
103
+ const valid = [];
104
+ for (const n of o.altNames ?? []) {
105
+ if (isIP(n) === 4)
106
+ valid.push(tlv(0x87, Buffer.from(n.split(".").map(Number))));
107
+ else if (isIP(n) === 0)
108
+ valid.push(tlv(0x82, Buffer.from(n, "ascii")));
109
+ // IPv6 literals are skipped; they aren't needed here.
110
+ }
111
+ if (valid.length)
112
+ exts.push(ext(OID.subjectAltName, false, seq(...valid)));
113
+ }
114
+ exts.push(ext(OID.subjectKeyId, false, octet(keyId(spki))));
115
+ exts.push(ext(OID.authorityKeyId, false, seq(tlv(0x80, keyId(issuerSpki)))));
116
+ const tbs = seq(explicit(0, uint(Buffer.from([2]))), // v3
117
+ uint(serial), ECDSA_SHA256, name(o.issuerName), seq(time(notBefore), time(notAfter)), name(o.commonName), spki, explicit(3, seq(...exts)));
118
+ const signature = sign("sha256", tbs, { key: o.issuerPrivateKey, dsaEncoding: "der" });
119
+ return seq(tbs, ECDSA_SHA256, bitString(signature));
120
+ }
121
+ export function toPem(der, label = "CERTIFICATE") {
122
+ const b64 = der
123
+ .toString("base64")
124
+ .replace(/(.{64})/g, "$1\n")
125
+ .trimEnd();
126
+ return `-----BEGIN ${label}-----\n${b64}\n-----END ${label}-----\n`;
127
+ }
128
+ export function fingerprint(der) {
129
+ return createHash("sha256").update(der).digest("hex");
130
+ }
131
+ /** DER prefix of a P-256 SubjectPublicKeyInfo; append the 65-byte uncompressed point. */
132
+ const P256_SPKI_PREFIX = Buffer.from("3059301306072a8648ce3d020106082a8648ce3d030107034200", "hex");
133
+ /**
134
+ * Parse a P-256 public key sent by the watch: the X9.63 uncompressed point
135
+ * (0x04 || X || Y) that Apple's SecKeyCopyExternalRepresentation produces.
136
+ */
137
+ export function p256PublicKeyFromX963(raw) {
138
+ if (raw.length !== 65 || raw[0] !== 0x04)
139
+ throw new Error("public key must be a 65-byte uncompressed P-256 point");
140
+ const key = createPublicKey({ key: Buffer.concat([P256_SPKI_PREFIX, raw]), format: "der", type: "spki" });
141
+ if (key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1")
142
+ throw new Error("public key must be on P-256");
143
+ return key;
144
+ }