@lysyi3m/sidecar 0.0.0-stage → 1.6.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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +285 -2
  3. package/dist/bin/sidecar-dashboard.js +27 -0
  4. package/dist/bin/sidecar-mcp.js +35 -0
  5. package/dist/bin/sidecar.js +70 -0
  6. package/dist/src/adapters/claude-code.js +333 -0
  7. package/dist/src/adapters/claude-desktop.js +184 -0
  8. package/dist/src/adapters/codex.js +383 -0
  9. package/dist/src/adapters/index.js +38 -0
  10. package/dist/src/adapters/installed.js +25 -0
  11. package/dist/src/adapters/outcome.js +30 -0
  12. package/dist/src/adapters/registration.js +69 -0
  13. package/dist/src/adapters/types.js +1 -0
  14. package/dist/src/cases/events.js +9 -0
  15. package/dist/src/cases/items.js +120 -0
  16. package/dist/src/cases/lock.js +80 -0
  17. package/dist/src/cases/opinion.js +58 -0
  18. package/dist/src/cases/state.js +121 -0
  19. package/dist/src/cases/store.js +181 -0
  20. package/dist/src/cases/usage.js +36 -0
  21. package/dist/src/cli/deps.js +18 -0
  22. package/dist/src/cli/lines.js +11 -0
  23. package/dist/src/cli/list.js +44 -0
  24. package/dist/src/cli/setup.js +202 -0
  25. package/dist/src/cli/status.js +111 -0
  26. package/dist/src/cli/style.js +26 -0
  27. package/dist/src/cli/ui.js +170 -0
  28. package/dist/src/cli/uninstall.js +73 -0
  29. package/dist/src/config.js +108 -0
  30. package/dist/src/dashboard/cases.js +109 -0
  31. package/dist/src/dashboard/html.js +31 -0
  32. package/dist/src/dashboard/links.js +35 -0
  33. package/dist/src/dashboard/marks.js +16 -0
  34. package/dist/src/dashboard/pages.js +516 -0
  35. package/dist/src/dashboard/server.js +305 -0
  36. package/dist/src/dashboard/service.js +138 -0
  37. package/dist/src/dashboard/static/agents/NOTICE +32 -0
  38. package/dist/src/dashboard/static/agents/claude-code.svg +1 -0
  39. package/dist/src/dashboard/static/agents/claude-desktop.svg +1 -0
  40. package/dist/src/dashboard/static/agents/codex.svg +1 -0
  41. package/dist/src/dashboard/static/app.css +1121 -0
  42. package/dist/src/dashboard/static/app.js +256 -0
  43. package/dist/src/dashboard/static/times.js +44 -0
  44. package/dist/src/dashboard/view.js +25 -0
  45. package/dist/src/lib/agent-process.js +57 -0
  46. package/dist/src/lib/atomic-write.js +35 -0
  47. package/dist/src/lib/command.js +20 -0
  48. package/dist/src/lib/failpoint.js +14 -0
  49. package/dist/src/lib/git.js +14 -0
  50. package/dist/src/lib/json.js +2 -0
  51. package/dist/src/lib/paths.js +19 -0
  52. package/dist/src/lib/proc.js +80 -0
  53. package/dist/src/lib/version.js +43 -0
  54. package/dist/src/mcp/server.js +800 -0
  55. package/dist/src/mcp/stdio.js +31 -0
  56. package/dist/src/mcp/tools.js +180 -0
  57. package/dist/src/turns/dispatch.js +188 -0
  58. package/dist/src/turns/knobs.js +14 -0
  59. package/dist/src/turns/prompt.js +284 -0
  60. package/dist/src/turns/runner.js +283 -0
  61. package/package.json +44 -4
@@ -0,0 +1,256 @@
1
+ // The dashboard's browser code. The server renders every page; this module only keeps them live.
2
+ // Markup it inserts comes from the server's escaping templates (src/dashboard/html.ts), never
3
+ // from case text, so parsing it as HTML is safe.
4
+
5
+ import { ago, local, utc } from "./times.js";
6
+
7
+ /** Replaces each element of `markup` that has an id on the page; appends the others to `container`. */
8
+ function apply(markup, container) {
9
+ const parsed = document.createElement("template");
10
+ parsed.innerHTML = markup;
11
+ // oxlint-disable-next-line unicorn/no-useless-spread -- children is live: moving a node out skips the next one
12
+ for (const node of [...parsed.content.children]) {
13
+ const current = node.id && document.getElementById(node.id);
14
+ if (current) current.replaceWith(node);
15
+ else container?.append(node);
16
+ }
17
+ times();
18
+ }
19
+
20
+ /* ---------------------------------------------------------------- times */
21
+
22
+ /**
23
+ * The server writes UTC times; they read in the browser's time zone here, and relative ones keep
24
+ * ageing while the page is open. The title keeps the UTC time the log records.
25
+ */
26
+ function times() {
27
+ for (const time of document.querySelectorAll("time[datetime]")) {
28
+ const iso = time.dateTime;
29
+ const text = time.classList.contains("ago") ? ago(iso) : local(iso, time.dataset.format);
30
+ if (text === null) continue;
31
+ time.textContent = text;
32
+ time.title = `${iso.slice(0, 19).replace("T", " ")} UTC`;
33
+ }
34
+ }
35
+
36
+ /* ---------------------------------------------------------------- live case */
37
+
38
+ const timeline = document.getElementById("timeline");
39
+ if (timeline) {
40
+ /** Near the bottom: the reader is following the case, not reading back. */
41
+ const following = () => innerHeight + scrollY >= document.documentElement.scrollHeight - 160;
42
+ const stream = new EventSource(timeline.dataset.stream);
43
+ stream.addEventListener("patch", ({ data }) => {
44
+ const follow = following();
45
+ apply(data, timeline);
46
+ if (follow) timeline.lastElementChild?.scrollIntoView({ behavior: "smooth", block: "end" });
47
+ });
48
+ // While the case's log cannot be read, the page does not update: it says why. Empty data clears it.
49
+ const problem = document.querySelector("[data-problem]");
50
+ stream.addEventListener("problem", ({ data }) => {
51
+ problem.hidden = !data;
52
+ problem.textContent = data ? `This page is not updating: ${data}` : "";
53
+ });
54
+ }
55
+
56
+ /**
57
+ * Lists the server re-renders: each element with data-refresh is refetched from that URL. The next
58
+ * fetch is scheduled once the last one settles, so a slow response never overlaps a newer one. The
59
+ * request carries the last response's ETag: a 304 means the list did not change, and the page
60
+ * keeps it as it is. A hidden tab does not poll; it refreshes as soon as it is shown again.
61
+ */
62
+ for (const element of document.querySelectorAll("[data-refresh]")) {
63
+ let etag = null;
64
+ let timer;
65
+ let busy = false;
66
+ const refresh = async () => {
67
+ if (busy) return;
68
+ busy = true;
69
+ clearTimeout(timer);
70
+ if (!document.hidden) {
71
+ try {
72
+ const response = await fetch(document.getElementById(element.id).dataset.refresh, {
73
+ headers: etag ? { "if-none-match": etag } : {},
74
+ signal: AbortSignal.timeout(10_000),
75
+ });
76
+ if (response.status === 200) {
77
+ // Kept only once the list is applied: a body lost to the timeout must not earn a 304.
78
+ const next = response.headers.get("etag");
79
+ apply(await response.text());
80
+ filterCases();
81
+ etag = next;
82
+ }
83
+ } catch {
84
+ // The next poll retries; the page keeps what it has.
85
+ }
86
+ }
87
+ busy = false;
88
+ timer = setTimeout(refresh, 5_000);
89
+ };
90
+ timer = setTimeout(refresh, 5_000);
91
+ document.addEventListener("visibilitychange", () => {
92
+ if (!document.hidden) void refresh();
93
+ });
94
+ }
95
+
96
+ /* ---------------------------------------------------------------- export */
97
+
98
+ /** An agent mark's SVG as a data: URI. Percent-encoded, so no quote or bracket ends the url(). */
99
+ async function inlineMark(url) {
100
+ const response = await fetch(url);
101
+ // As for the stylesheet: an error page must not become a mark.
102
+ if (!response.ok) throw new Error(`an agent mark could not be loaded (HTTP ${response.status})`);
103
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(await response.text())}`;
104
+ }
105
+
106
+ /**
107
+ * Saves the case as one self-contained HTML file: the page without the sidebar, the top bar or
108
+ * any script, with the stylesheet inlined and every time back in UTC: "2 h ago" would be wrong
109
+ * tomorrow, and the reader's time zone is not the exporter's. The file is built as a DOM, never
110
+ * from strings, so the case text stays as escaped as the server rendered it.
111
+ */
112
+ async function exportCase(caseId) {
113
+ const response = await fetch("/assets/app.css");
114
+ // An error page, e.g. an expired token's 401, must not become the file's stylesheet.
115
+ if (!response.ok) throw new Error(`the stylesheet could not be loaded (HTTP ${response.status})`);
116
+ // Inside <style>, only "</style" (any case) ends the text: keep any in the CSS from closing it early.
117
+ const css = (await response.text()).replace(/<\/style/gi, "<\\/style");
118
+ const page = document.querySelector(".page").cloneNode(true);
119
+ page.querySelector(".topbar")?.remove();
120
+ page.querySelector("[data-problem]")?.remove();
121
+ for (const node of page.querySelectorAll("[data-stream], [data-refresh]")) {
122
+ node.removeAttribute("data-stream");
123
+ node.removeAttribute("data-refresh");
124
+ }
125
+ for (const time of page.querySelectorAll("time[datetime]")) {
126
+ time.textContent = utc(time.dateTime, time.dataset.format);
127
+ time.removeAttribute("title");
128
+ }
129
+ // Each agent mark's file is inlined as a data: URI, so the file still loads nothing.
130
+ const marks = new Map();
131
+ for (const mark of page.querySelectorAll(".agent-mark")) {
132
+ const url = /url\((["']?)(.*?)\1\)/.exec(mark.style.getPropertyValue("--mark"))?.[2];
133
+ if (!url) continue;
134
+ if (!marks.has(url)) marks.set(url, await inlineMark(url));
135
+ mark.style.setProperty("--mark", `url("${marks.get(url)}")`);
136
+ }
137
+ const note = document.createElement("footer");
138
+ note.className = "export-note";
139
+ note.textContent = `Exported from sidecar on ${utc(new Date().toISOString())}.`;
140
+ page.append(note);
141
+
142
+ const file = document.implementation.createHTMLDocument(document.title);
143
+ file.documentElement.lang = "en";
144
+ const charset = file.createElement("meta");
145
+ charset.setAttribute("charset", "utf-8");
146
+ const viewport = file.createElement("meta");
147
+ viewport.name = "viewport";
148
+ viewport.content = "width=device-width, initial-scale=1";
149
+ const style = file.createElement("style");
150
+ style.textContent = css;
151
+ file.head.prepend(charset, viewport);
152
+ file.head.append(document.querySelector('link[rel="icon"]')?.cloneNode() ?? "", style);
153
+ const main = file.createElement("main");
154
+ main.className = "main";
155
+ main.append(file.importNode(page, true));
156
+ file.body.append(main);
157
+
158
+ const blob = new Blob([`<!doctype html>\n${file.documentElement.outerHTML}\n`], {
159
+ type: "text/html",
160
+ });
161
+ const title = document.querySelector(".case-head .title")?.textContent ?? "";
162
+ const slug = title
163
+ .toLowerCase()
164
+ .replace(/[^a-z0-9]+/g, "-")
165
+ .replace(/^-|-$/g, "")
166
+ .slice(0, 60);
167
+ const link = document.createElement("a");
168
+ link.href = URL.createObjectURL(blob);
169
+ link.download = `sidecar-${caseId}${slug ? `-${slug}` : ""}.html`;
170
+ link.click();
171
+ // Revoked later: some browsers cancel a download whose URL is revoked in the same tick.
172
+ setTimeout(() => URL.revokeObjectURL(link.href), 60_000);
173
+ }
174
+
175
+ document.querySelector("[data-export]")?.addEventListener("click", (event) => {
176
+ const button = event.currentTarget;
177
+ exportCase(button.dataset.export).catch((err) => {
178
+ // Nothing was saved: say so on the button; the next click retries.
179
+ button.classList.add("is-failed");
180
+ button.title = `Export failed: ${err.message}. Click to retry.`;
181
+ setTimeout(() => {
182
+ button.classList.remove("is-failed");
183
+ button.title = "Export as HTML";
184
+ }, 5_000);
185
+ });
186
+ });
187
+
188
+ /* ---------------------------------------------------------------- sidebar */
189
+
190
+ // Small screens have no sidebar and no toggle (app.css), so the stored state applies to wide ones only.
191
+ // The state lives in a cookie the server reads, so the page arrives already in it: this script
192
+ // runs after the first paint, and applying the state here would animate the sidebar shut.
193
+ const shell = document.querySelector(".shell");
194
+
195
+ document.querySelector("[data-toggle-sidebar]")?.addEventListener("click", () => {
196
+ const collapsed = shell.classList.toggle("is-collapsed");
197
+ document.cookie = `sidecar_sidebar=${collapsed ? "collapsed" : "open"}; Path=/; SameSite=Strict; Max-Age=31536000`;
198
+ });
199
+
200
+ /* ---------------------------------------------------------------- case index */
201
+
202
+ const search = document.querySelector("[data-search]");
203
+ // The server renders the filter the URL asks for, already checked.
204
+ let filter = document.querySelector("[data-cases]")?.dataset.filterState ?? "all";
205
+
206
+ /** Shows the rows that match the state filter and the search text, and keeps the URL in step. */
207
+ function filterCases() {
208
+ if (!search) return;
209
+ const rows = [...document.querySelectorAll("#case-rows tr")];
210
+ const needle = search.value.trim().toLowerCase();
211
+ let shown = 0;
212
+ for (const row of rows) {
213
+ row.hidden = !(
214
+ (filter === "all" || row.dataset.state === filter) &&
215
+ row.dataset.haystack.includes(needle)
216
+ );
217
+ if (!row.hidden) shown++;
218
+ }
219
+ document.querySelector("[data-cases]").dataset.filterState = filter;
220
+ for (const button of document.querySelectorAll("[data-filter]")) {
221
+ const name = button.dataset.filter;
222
+ button.setAttribute("aria-pressed", String(name === filter));
223
+ button.querySelector("[data-count]").textContent = rows.filter(
224
+ (r) => name === "all" || r.dataset.state === name,
225
+ ).length;
226
+ }
227
+ document.querySelector("[data-result-count]").textContent = `${shown} / ${rows.length}`;
228
+ const message = document.querySelector("[data-message]");
229
+ message.hidden = shown > 0;
230
+ message.textContent = rows.length === 0 ? "No cases yet." : "No case matches this filter.";
231
+
232
+ const url = new URL(location.href);
233
+ if (filter === "all") url.searchParams.delete("state");
234
+ else url.searchParams.set("state", filter);
235
+ if (needle) url.searchParams.set("search", search.value.trim());
236
+ else url.searchParams.delete("search");
237
+ history.replaceState(null, "", url);
238
+ }
239
+
240
+ if (search) {
241
+ search.addEventListener("input", filterCases);
242
+ for (const button of document.querySelectorAll("[data-filter]")) {
243
+ button.addEventListener("click", () => {
244
+ filter = button.dataset.filter;
245
+ filterCases();
246
+ });
247
+ }
248
+ document.addEventListener("click", (event) => {
249
+ const row = event.target.closest("tr[data-href]");
250
+ if (row && !event.target.closest("a")) location.href = row.dataset.href;
251
+ });
252
+ filterCases();
253
+ }
254
+
255
+ times();
256
+ setInterval(times, 30_000);
@@ -0,0 +1,44 @@
1
+ // How the dashboard's browser code writes a time. The server renders every time in UTC; the page
2
+ // shows it in the browser's time zone, in the same ISO layout. No DOM here, so tests run it as is.
3
+
4
+ /** A relative time, e.g. "5 min ago"; null for a timestamp the browser cannot read. */
5
+ export function ago(iso) {
6
+ const at = Date.parse(iso);
7
+ if (Number.isNaN(at)) return null;
8
+ const seconds = Math.max(0, (Date.now() - at) / 1000);
9
+ if (seconds < 60) return "just now";
10
+ if (seconds < 3600) return `${Math.floor(seconds / 60)} min ago`;
11
+ if (seconds < 86_400) return `${Math.floor(seconds / 3600)} h ago`;
12
+ return `${Math.floor(seconds / 86_400)} d ago`;
13
+ }
14
+
15
+ /** A time as the server renders it, in UTC: what the export keeps, and every time's title. */
16
+ export const utc = (iso, format) =>
17
+ format === "clock" ? iso.slice(11, 19) : `${iso.slice(0, 16).replace("T", " ")} UTC`;
18
+
19
+ // The browser's time zone, but a fixed locale: the page is in English, and only the parts are used.
20
+ const LOCAL = new Intl.DateTimeFormat("en-US", {
21
+ year: "numeric",
22
+ month: "2-digit",
23
+ day: "2-digit",
24
+ hour: "2-digit",
25
+ minute: "2-digit",
26
+ second: "2-digit",
27
+ hourCycle: "h23",
28
+ timeZoneName: "short",
29
+ });
30
+
31
+ /**
32
+ * A time in the browser's time zone, in the server's ISO layout. `zoned` adds the zone's name.
33
+ * Null for a timestamp the browser cannot read: the server's UTC text then stays.
34
+ */
35
+ export function local(iso, format) {
36
+ const date = new Date(iso);
37
+ if (Number.isNaN(date.getTime())) return null;
38
+ const part = Object.fromEntries(
39
+ LOCAL.formatToParts(date).map(({ type, value }) => [type, value]),
40
+ );
41
+ if (format === "clock") return `${part.hour}:${part.minute}:${part.second}`;
42
+ const stamp = `${part.year}-${part.month}-${part.day} ${part.hour}:${part.minute}`;
43
+ return format === "zoned" ? `${stamp} ${part.timeZoneName}` : stamp;
44
+ }
@@ -0,0 +1,25 @@
1
+ import { itemStatus } from "../cases/items.js";
2
+ import { caseStatus, fold } from "../cases/state.js";
3
+ export function caseModel(caseId, events, reviewBudget) {
4
+ const state = fold(events);
5
+ const items = new Map([...state.items].map(([ref, item]) => [ref, { item, status: itemStatus(item, reviewBudget) }]));
6
+ return { caseId, events, state, status: caseStatus(state), items };
7
+ }
8
+ export function summarize(caseId, events) {
9
+ const s = fold(events);
10
+ return {
11
+ case_id: caseId,
12
+ title: String(s.opened.title ?? ""),
13
+ state: caseStatus(s),
14
+ navigator: String(s.opened.navigator ?? ""),
15
+ model: s.opened.model ?? null,
16
+ effort: s.opened.effort ?? null,
17
+ driver: s.opened.driver ?? null,
18
+ driver_model: s.driverModel ?? null,
19
+ driver_effort: s.driverEffort ?? null,
20
+ workspace: String(s.opened.workspace ?? ""),
21
+ created: s.opened.ts,
22
+ updated: events.at(-1)?.ts ?? s.opened.ts,
23
+ in_flight: s.inFlight !== undefined,
24
+ };
25
+ }
@@ -0,0 +1,57 @@
1
+ import { spawn } from "node:child_process";
2
+ const MAX_OUTPUT = 10 * 1024 * 1024;
3
+ /** Spawns an agent CLI in the caller's process group, with the input on stdin, output kept in memory. */
4
+ export function startAgent(invocation, cwd, graceMs) {
5
+ const child = spawn(invocation.command, invocation.args, {
6
+ cwd,
7
+ stdio: ["pipe", "pipe", "pipe"],
8
+ env: { ...process.env, ...invocation.env },
9
+ });
10
+ let stdout = "";
11
+ let stderr = "";
12
+ // Decoded as streams, so a UTF-8 character split across chunks stays whole.
13
+ child.stdout.setEncoding("utf8");
14
+ child.stderr.setEncoding("utf8");
15
+ child.stdout.on("data", (chunk) => {
16
+ if (stdout.length < MAX_OUTPUT)
17
+ stdout += chunk;
18
+ });
19
+ child.stderr.on("data", (chunk) => {
20
+ if (stderr.length < MAX_OUTPUT)
21
+ stderr += chunk;
22
+ });
23
+ // EPIPE when the agent exits before reading it all: recorded, never thrown.
24
+ let inputError;
25
+ child.stdin.on("error", (err) => {
26
+ inputError = err;
27
+ });
28
+ child.stdin.end(invocation.input ?? "");
29
+ let stopping = false;
30
+ const stop = () => {
31
+ if (stopping)
32
+ return;
33
+ stopping = true;
34
+ child.kill("SIGTERM");
35
+ setTimeout(() => child.kill("SIGKILL"), graceMs).unref();
36
+ };
37
+ const done = new Promise((resolve) => {
38
+ child.once("error", (spawnError) => resolve({ spawnError }));
39
+ child.once("exit", (exitCode, signal) => {
40
+ // A grandchild can hold the pipes open after the agent exits; drain briefly, then stop.
41
+ const settle = () => resolve({
42
+ result: { exitCode, signal, stdout, stderr },
43
+ ...(inputError ? { inputError } : {}),
44
+ });
45
+ const drained = setTimeout(() => {
46
+ child.stdout.destroy();
47
+ child.stderr.destroy();
48
+ settle();
49
+ }, 200);
50
+ child.once("close", () => {
51
+ clearTimeout(drained);
52
+ settle();
53
+ });
54
+ });
55
+ });
56
+ return { done, stop };
57
+ }
@@ -0,0 +1,35 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, renameSync, rmSync, writeFileSync, } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ /**
5
+ * Replaces `file` through a temporary file beside it, so a crash never leaves it truncated. The
6
+ * temporary file is owner-only until it takes `mode`. `beforeRename` runs last and may throw to
7
+ * cancel the write. On any failure the temporary file is removed and `file` stays as it was.
8
+ */
9
+ export function writeFileAtomic(file, text, mode, beforeRename) {
10
+ // The rename would replace a symlink, not its target: a file kept elsewhere, e.g. in dotfiles,
11
+ // would silently fork. A dangling one reads as absent, so check the link itself.
12
+ if (lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink())
13
+ throw new Error(`${file} is a symlink; sidecar replaces only a regular file`);
14
+ mkdirSync(dirname(file), { recursive: true });
15
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
16
+ // "wx" creates the file or fails: a leftover file or a planted symlink at that path is never
17
+ // truncated or followed.
18
+ const fd = openSync(tmp, "wx", 0o600);
19
+ try {
20
+ try {
21
+ writeFileSync(fd, text);
22
+ }
23
+ finally {
24
+ closeSync(fd);
25
+ }
26
+ chmodSync(tmp, mode);
27
+ beforeRename?.();
28
+ renameSync(tmp, file);
29
+ }
30
+ catch (err) {
31
+ // Only the file this write created: the path is its own.
32
+ rmSync(tmp, { force: true });
33
+ throw err;
34
+ }
35
+ }
@@ -0,0 +1,20 @@
1
+ import { spawnSync } from "node:child_process";
2
+ /**
3
+ * Runs a short command synchronously, bounded by `timeoutMs`. `stdout` alone is for a caller that
4
+ * parses it.
5
+ */
6
+ export function exec({ command, args, env }, { timeoutMs = 30_000 } = {}) {
7
+ // SIGKILL: spawnSync keeps waiting for a child that ignores the default SIGTERM.
8
+ const run = spawnSync(command, args, {
9
+ encoding: "utf8",
10
+ timeout: timeoutMs,
11
+ killSignal: "SIGKILL",
12
+ maxBuffer: 64 * 1024 * 1024,
13
+ env: { ...process.env, ...env },
14
+ });
15
+ return {
16
+ ok: run.error === undefined && run.status === 0,
17
+ output: `${run.stdout ?? ""}${run.stderr ?? ""}`.trim() || (run.error?.message ?? ""),
18
+ stdout: run.stdout ?? "",
19
+ };
20
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Deterministic crash injection for tests. When SIDECAR_FAILPOINT names this step, the process
3
+ * SIGKILLs itself: no finally blocks, no exit handlers run — the same as a real crash.
4
+ */
5
+ export function failpoint(name) {
6
+ if (!failpointActive(name))
7
+ return;
8
+ process.kill(process.pid, "SIGKILL");
9
+ // Signal delivery is asynchronous; never return into the code the failpoint guards.
10
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
11
+ }
12
+ export function failpointActive(name) {
13
+ return process.env.SIDECAR_FAILPOINT === name;
14
+ }
@@ -0,0 +1,14 @@
1
+ import { statSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ /**
4
+ * Whether `dir` is inside a git work tree: some ancestor holds `.git`, a directory or, for a
5
+ * worktree or submodule, a file. A filesystem walk, not `git rev-parse`: no process per turn.
6
+ */
7
+ export function inGitRepo(dir) {
8
+ for (let current = resolve(dir);; current = dirname(current)) {
9
+ if (statSync(`${current}/.git`, { throwIfNoEntry: false }))
10
+ return true;
11
+ if (dirname(current) === current)
12
+ return false;
13
+ }
14
+ }
@@ -0,0 +1,2 @@
1
+ /** A JSON object: not null, not an array. */
2
+ export const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -0,0 +1,19 @@
1
+ import { existsSync } from "node:fs";
2
+ import { dirname, extname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ // sidecar runs from its .ts sources in a clone and from emitted .js in the npm package. The emitted
5
+ // tree mirrors the sources, so a relative path stays valid; only the extension differs.
6
+ const EXT = extname(fileURLToPath(import.meta.url));
7
+ /** The absolute path of a module given without its extension, relative to `base` (an import.meta.url). */
8
+ export const modulePath = (relative, base) => fileURLToPath(new URL(`${relative}${EXT}`, base));
9
+ /** The directory of the nearest package.json at or above `base`'s directory. */
10
+ export function packageRoot(base) {
11
+ let dir = dirname(fileURLToPath(base));
12
+ while (!existsSync(join(dir, "package.json"))) {
13
+ const parent = dirname(dir);
14
+ if (parent === dir)
15
+ throw new Error(`no package.json above ${fileURLToPath(base)}`);
16
+ dir = parent;
17
+ }
18
+ return dir;
19
+ }
@@ -0,0 +1,80 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ // A bare pid is ambiguous: the OS reuses pids. Pairing it with the process start time makes the
4
+ // identity unique for practical purposes.
5
+ const PS_TIMEOUT_MS = 5000;
6
+ /**
7
+ * The kernel start time of a live, non-zombie process, or null. Throws when the start time cannot
8
+ * be read: a caller must not take an unreadable process for a dead one. `ps` is called by its
9
+ * absolute path, so a caller started with a minimal PATH still reads it.
10
+ */
11
+ export function startTime(pid, ps = "/bin/ps") {
12
+ if (process.platform === "linux") {
13
+ let stat;
14
+ try {
15
+ stat = readFileSync(`/proc/${pid}/stat`, "utf8");
16
+ }
17
+ catch (err) {
18
+ // No /proc entry: the process is gone. Any other error leaves its state unknown.
19
+ if (err.code === "ENOENT")
20
+ return null;
21
+ throw new Error(`cannot read the start time of pid ${pid}: ${err.message}`);
22
+ }
23
+ // Fields after the parenthesised command name: state is the 1st, starttime the 20th.
24
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
25
+ if (fields[0] === "Z")
26
+ return null;
27
+ return fields[19] ?? null;
28
+ }
29
+ // lstart is local time in the caller's locale. One process records it and another compares it,
30
+ // so every caller formats it the same way: the C locale and the system time zone.
31
+ const env = { ...process.env, LC_ALL: "C" };
32
+ delete env.TZ;
33
+ const run = spawnSync(ps, ["-o", "lstart=,stat=", "-p", String(pid)], {
34
+ encoding: "utf8",
35
+ env,
36
+ timeout: PS_TIMEOUT_MS,
37
+ });
38
+ if (run.error)
39
+ throw new Error(`cannot read the start time of pid ${pid}: ${run.error.message}`);
40
+ const line = run.stdout.trim();
41
+ // ps exits 1 with no output when no process has the pid.
42
+ if (run.status === 1 && line === "")
43
+ return null;
44
+ if (run.status !== 0) {
45
+ throw new Error(`cannot read the start time of pid ${pid}: ps exited ${run.status ?? run.signal}`);
46
+ }
47
+ if (/\sZ\S*$/.test(line))
48
+ return null;
49
+ return line.replace(/\s+\S+$/, "");
50
+ }
51
+ export function processAlive(pid, start) {
52
+ const current = startTime(pid);
53
+ return current !== null && current === start;
54
+ }
55
+ /** POSIX never reuses a pid while a process group with that id exists. */
56
+ export function groupExists(pgid) {
57
+ try {
58
+ process.kill(-pgid, 0);
59
+ return true;
60
+ }
61
+ catch (err) {
62
+ return err.code === "EPERM";
63
+ }
64
+ }
65
+ /**
66
+ * Kills every process in the group that can still be signalled. On macOS the kernel skips zombies
67
+ * and fails with EPERM when no member can be signalled: a group of zombies that await their parent,
68
+ * or members this user may not signal. Nothing is killed then; the group stays, and a caller that
69
+ * checks `groupExists` keeps waiting for it.
70
+ */
71
+ export function killGroup(pgid) {
72
+ try {
73
+ process.kill(-pgid, "SIGKILL");
74
+ }
75
+ catch (err) {
76
+ const code = err.code;
77
+ if (code !== "ESRCH" && code !== "EPERM")
78
+ throw err;
79
+ }
80
+ }
@@ -0,0 +1,43 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { packageRoot } from "./paths.js";
4
+ const ROOT = packageRoot(import.meta.url);
5
+ /** The version in the package.json at `root`, or null when it cannot be read or names none. */
6
+ export function installedVersion(root) {
7
+ try {
8
+ const { version } = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
9
+ return typeof version === "string" && version !== "" ? version : null;
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ }
15
+ /** The package's version. A case log records the version that opened it. */
16
+ export const SIDECAR_VERSION = installedVersion(ROOT) ??
17
+ (() => {
18
+ throw new Error(`no version in ${join(ROOT, "package.json")}`);
19
+ })();
20
+ /**
21
+ * Calls `onChange` once, when the installed version differs from the running one, or when it stays
22
+ * unreadable past the grace. A long-lived process keeps the code it started with; this tells it an
23
+ * upgrade replaced that code on disk. The timer does not keep the process alive. Returns a stop
24
+ * function.
25
+ */
26
+ export function watchVersion(onChange, { root = ROOT, running = SIDECAR_VERSION, intervalMs = 5_000, graceTicks = 12, } = {}) {
27
+ let unreadable = 0;
28
+ const timer = setInterval(() => {
29
+ const installed = installedVersion(root);
30
+ if (installed === null && ++unreadable <= graceTicks)
31
+ return;
32
+ if (installed === running) {
33
+ unreadable = 0;
34
+ return;
35
+ }
36
+ clearInterval(timer);
37
+ onChange(installed === null
38
+ ? `the installed version has been unreadable for ${graceTicks} checks`
39
+ : `sidecar ${installed} is installed, but this process runs ${running}`);
40
+ }, intervalMs);
41
+ timer.unref();
42
+ return () => clearInterval(timer);
43
+ }