@lysyi3m/sidecar 0.0.0-stage → 1.6.1

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 +295 -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,108 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { z } from "zod";
5
+ import { writeFileAtomic } from "./lib/atomic-write.js";
6
+ import { isObject } from "./lib/json.js";
7
+ // ~/.sidecar/config.json, written by `sidecar setup`. Environment variables override it; tests and
8
+ // one-off runs use them.
9
+ const PORT = "must be a port number, 1–65535";
10
+ const port = z.number(PORT).int(PORT).min(1, PORT).max(65535, PORT);
11
+ const COUNT = "must be a whole number, 1 or more";
12
+ const positive = z.number(COUNT).int(COUNT).positive(COUNT);
13
+ /** The token travels in a URL query and a cookie value: URL-safe characters only, and long enough not to guess. */
14
+ export const TOKEN = /^[A-Za-z0-9._~-]{16,}$/;
15
+ const TOKEN_RULE = "16 or more of A–Z, a–z, 0–9, . _ ~ -";
16
+ /** The prompt limits in src/turns/prompt.ts are sized so that a prompt's mandatory part fits this. */
17
+ export const MIN_SEED_BOUND = 40_000;
18
+ /** At most 3 MB of UTF-8, well under the 10 MB claude documents for a prompt on stdin. */
19
+ export const MAX_SEED_BOUND = 1_000_000;
20
+ /**
21
+ * The config file's shape, with each setting's default. Unknown keys are dropped, so a save writes
22
+ * only known settings.
23
+ */
24
+ const Config = z
25
+ .object({
26
+ navigators: z
27
+ .record(z.string(), z.object({ model: z.string().optional(), effort: z.string().optional() }))
28
+ .default({}),
29
+ lockPort: port.default(47821),
30
+ /** The dashboard runs as a per-user service at dashboardPort. */
31
+ dashboardPort: port.default(47822),
32
+ /** Bind address. A loopback address keeps it local; any other opens it to the network, token required. */
33
+ dashboardHost: z.string().default("127.0.0.1"),
34
+ /** Required for any client that is not on loopback. Set by setup. */
35
+ dashboardToken: z.string().regex(TOKEN, `must be ${TOKEN_RULE}`).optional(),
36
+ seedBound: z
37
+ .number()
38
+ .int()
39
+ .min(MIN_SEED_BOUND, `must be at least ${MIN_SEED_BOUND}`)
40
+ .max(MAX_SEED_BOUND, `must be at most ${MAX_SEED_BOUND}`)
41
+ .default(MIN_SEED_BOUND),
42
+ /** Automatic navigator reviews per point. Past it, an unsettled point is left for the user. */
43
+ reviewBudget: positive.default(2),
44
+ })
45
+ .refine((c) => c.lockPort !== c.dashboardPort, {
46
+ // The dashboard holds its port for good, so every store operation would time out on the lock.
47
+ path: ["dashboardPort"],
48
+ message: "must differ from lockPort",
49
+ });
50
+ export const DEFAULTS = Config.parse({});
51
+ /** The store home when SIDECAR_HOME is unset. */
52
+ export const DEFAULT_HOME = join(homedir(), ".sidecar");
53
+ /**
54
+ * Absolute, so every process names the same store: setup registers it with each agent, and an app
55
+ * starts its server from another directory.
56
+ */
57
+ export const sidecarHome = () => process.env.SIDECAR_HOME ? resolve(process.env.SIDECAR_HOME) : DEFAULT_HOME;
58
+ export const configPath = (home) => join(home, "config.json");
59
+ /** The name sidecar's MCP server registers under with each driver agent. */
60
+ export const SERVER_NAME = "sidecar";
61
+ /** Environment variables that override a setting; tests and one-off runs use them. */
62
+ const OVERRIDES = {
63
+ lockPort: "SIDECAR_LOCK_PORT",
64
+ dashboardPort: "SIDECAR_DASHBOARD_PORT",
65
+ seedBound: "SIDECAR_SEED_BOUND",
66
+ reviewBudget: "SIDECAR_REVIEW_BUDGET",
67
+ };
68
+ export function loadConfig(home = sidecarHome()) {
69
+ const file = configPath(home);
70
+ const stored = existsSync(file) ? readStored(file) : {};
71
+ for (const [key, name] of Object.entries(OVERRIDES)) {
72
+ // An empty variable becomes 0 and fails validation, rather than silently meaning "unset".
73
+ if (process.env[name] !== undefined)
74
+ stored[key] = Number(process.env[name]);
75
+ }
76
+ return parseConfig(stored);
77
+ }
78
+ function readStored(file) {
79
+ let stored;
80
+ try {
81
+ stored = JSON.parse(readFileSync(file, "utf8"));
82
+ }
83
+ catch (err) {
84
+ throw new Error(`${file}: ${err.message}`);
85
+ }
86
+ if (!isObject(stored))
87
+ throw new Error(`${file}: not a JSON object`);
88
+ return stored;
89
+ }
90
+ /** Why `value` is not valid for the setting `key`, or undefined when it is. */
91
+ export function checkSetting(key, value) {
92
+ const parsed = Config.shape[key].safeParse(value);
93
+ return parsed.success ? undefined : parsed.error.issues[0]?.message;
94
+ }
95
+ /** Validates a config against the schema; throws with every problem found. */
96
+ function parseConfig(stored) {
97
+ const parsed = Config.safeParse(stored);
98
+ if (!parsed.success) {
99
+ throw new Error(`invalid sidecar config: ${parsed.error.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; ")}`);
100
+ }
101
+ return parsed.data;
102
+ }
103
+ /** Replaced atomically. Throws, writing nothing, on a config loadConfig would reject. */
104
+ export function saveConfig(config, home = sidecarHome()) {
105
+ parseConfig(config);
106
+ // Owner-only: the file can hold the dashboard access token.
107
+ writeFileAtomic(configPath(home), JSON.stringify(config, null, 2) + "\n", 0o600);
108
+ }
@@ -0,0 +1,109 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { readdirSync, statSync } from "node:fs";
3
+ import { isCaseId } from "../cases/store.js";
4
+ import { summarize } from "./view.js";
5
+ /**
6
+ * A write can leave size and mtime as they were: a tail repair can write a line as long as the one
7
+ * it drops, within one mtime tick. So, as git does for its index, a stamp taken within this window
8
+ * of the log's mtime proves nothing, and the log is read again until a later stamp falls past it.
9
+ */
10
+ const RACY_MS = 2_000;
11
+ /** The log's stamp, or undefined when it does not exist. Throws on any other stat failure. */
12
+ export function stampOf(file) {
13
+ const at = Date.now();
14
+ const s = statSync(file, { bigint: true, throwIfNoEntry: false });
15
+ return s && { ino: s.ino, size: s.size, mtimeNs: s.mtimeNs, at };
16
+ }
17
+ /** Whether a read made after `before` was taken still shows the log as `now` finds it. */
18
+ export const unchanged = (before, now) => before !== undefined &&
19
+ before.ino === now.ino &&
20
+ before.size === now.size &&
21
+ before.mtimeNs === now.mtimeNs &&
22
+ before.at - Number(before.mtimeNs / 1000000n) > RACY_MS;
23
+ /** Scans that start this soon after the last one share its result: tabs refresh both lists at once. */
24
+ const FRESH_MS = 1_000;
25
+ /** New for each process, so a restart with other code never matches a version from before it. */
26
+ const BOOT = randomBytes(8).toString("hex");
27
+ export class CaseIndex {
28
+ #store;
29
+ #freshMs;
30
+ #entries = new Map();
31
+ #scan;
32
+ /** `freshMs` replaces FRESH_MS (tests). */
33
+ constructor(store, freshMs = FRESH_MS) {
34
+ this.#store = store;
35
+ this.#freshMs = freshMs;
36
+ }
37
+ /**
38
+ * Every case's summary, and the list's version. One scan runs at a time; a caller during a scan,
39
+ * or within the freshness window after one, gets that scan's result.
40
+ */
41
+ list() {
42
+ if (this.#scan && Date.now() - this.#scan.done < this.#freshMs)
43
+ return this.#scan.result;
44
+ const result = this.#rescan();
45
+ const scan = { done: Number.POSITIVE_INFINITY, result };
46
+ this.#scan = scan;
47
+ // Both branches, so a failed scan is not an unhandled rejection here; its callers get the error.
48
+ const finish = () => {
49
+ scan.done = Date.now();
50
+ };
51
+ result.then(finish, finish);
52
+ return result;
53
+ }
54
+ async #rescan() {
55
+ const ids = new Set(caseIds(this.#store.casesDir));
56
+ const cases = [];
57
+ for (const caseId of ids) {
58
+ const summary = await this.#summary(caseId);
59
+ if (summary)
60
+ cases.push(summary);
61
+ }
62
+ for (const caseId of this.#entries.keys()) {
63
+ if (!ids.has(caseId))
64
+ this.#entries.delete(caseId);
65
+ }
66
+ cases.sort((a, b) => ("created" in b ? b.created : "").localeCompare("created" in a ? a.created : ""));
67
+ // From the summaries, not the stamps: within the racy window a log can change under one stamp.
68
+ const version = createHash("sha256")
69
+ .update(BOOT)
70
+ .update(JSON.stringify(cases))
71
+ .digest("base64url");
72
+ return { cases, version };
73
+ }
74
+ /** The case's summary; undefined when its log is gone. A failure is reported, never kept. */
75
+ async #summary(caseId) {
76
+ const cached = this.#entries.get(caseId);
77
+ try {
78
+ const stamp = stampOf(this.#store.logPath(caseId));
79
+ if (!stamp) {
80
+ this.#entries.delete(caseId);
81
+ return undefined;
82
+ }
83
+ if (cached && unchanged(cached.stamp, stamp))
84
+ return cached.summary;
85
+ const summary = summarize(caseId, await this.#store.read(caseId));
86
+ this.#entries.set(caseId, { stamp, summary });
87
+ return summary;
88
+ }
89
+ catch (err) {
90
+ // A lock timeout passes with the next scan, and a corrupt log may be repaired: retry each time.
91
+ this.#entries.delete(caseId);
92
+ return { case_id: caseId, state: "unreadable", error: err.message };
93
+ }
94
+ }
95
+ }
96
+ /**
97
+ * Every name of a case id's form, by name alone: a case whose directory cannot be read still gets a
98
+ * row, unreadable, where Store.listCaseIds would drop it.
99
+ */
100
+ function caseIds(casesDir) {
101
+ try {
102
+ return readdirSync(casesDir).filter(isCaseId);
103
+ }
104
+ catch (err) {
105
+ if (err.code === "ENOENT")
106
+ return [];
107
+ throw err;
108
+ }
109
+ }
@@ -0,0 +1,31 @@
1
+ // HTML templates that escape by default. Case text comes from agents and is untrusted: every
2
+ // interpolated value is escaped unless it is already Html, which only this module and `raw` make.
3
+ export class Html {
4
+ value;
5
+ constructor(value) {
6
+ this.value = value;
7
+ }
8
+ }
9
+ const ESCAPES = {
10
+ "&": "&amp;",
11
+ "<": "&lt;",
12
+ ">": "&gt;",
13
+ '"': "&quot;",
14
+ "'": "&#39;",
15
+ };
16
+ const escape = (text) => text.replace(/[&<>"']/g, (c) => ESCAPES[c]);
17
+ /** A value as markup: Html passes through, arrays join, nothing renders null, undefined or false. */
18
+ function render(value) {
19
+ if (value instanceof Html)
20
+ return value.value;
21
+ if (Array.isArray(value))
22
+ return value.map(render).join("");
23
+ if (value === null || value === undefined || value === false)
24
+ return "";
25
+ return escape(String(value));
26
+ }
27
+ export function html(strings, ...values) {
28
+ return new Html(strings.reduce((out, part, i) => out + part + (i < values.length ? render(values[i]) : ""), ""));
29
+ }
30
+ /** Markup sidecar wrote itself, such as icon path data. Never pass case text here. */
31
+ export const raw = (markup) => new Html(markup);
@@ -0,0 +1,35 @@
1
+ import { isIP } from "node:net";
2
+ import { networkInterfaces } from "node:os";
3
+ // Where the dashboard is reached, for the MCP server, setup and status. Kept apart from the HTTP
4
+ // server, so printing a link never loads the web stack.
5
+ /** 127.0.0.0/8 is loopback in full, not only 127.0.0.1. */
6
+ export const isLoopbackHost = (host) => host === "localhost" || host === "::1" || (isIP(host) === 4 && host.startsWith("127."));
7
+ /** Container and VM bridges: reachable from this machine only, so their links are noise. */
8
+ const VIRTUAL_INTERFACE = /^(docker|br-|veth|virbr|vmnet|vboxnet|cni|flannel|podman)/;
9
+ const isWildcard = (host) => host === "0.0.0.0" || host === "::";
10
+ /** An address as a URL host: IPv6 literals go in brackets. */
11
+ const urlHost = (address) => (isIP(address) === 6 ? `[${address}]` : address);
12
+ /**
13
+ * The dashboard's base URL as this machine reaches it. A wildcard bind accepts loopback; a bind to one
14
+ * address accepts only that address, so the URL names it.
15
+ */
16
+ export function dashboardBase(port, host) {
17
+ return `http://${isWildcard(host) ? "127.0.0.1" : urlHost(host)}:${port}/`;
18
+ }
19
+ /**
20
+ * Links to open the dashboard: the untokenized loopback link when the listener accepts loopback, and
21
+ * one tokenized link per network address it accepts.
22
+ */
23
+ export function dashboardLinks(port, host, token, interfaces = networkInterfaces()) {
24
+ if (isLoopbackHost(host) || !token)
25
+ return [dashboardBase(port, host)];
26
+ const tokenized = (address) => `http://${urlHost(address)}:${port}/?token=${encodeURIComponent(token)}`;
27
+ if (!isWildcard(host))
28
+ return [tokenized(host)];
29
+ const addresses = Object.entries(interfaces)
30
+ .filter(([name]) => !VIRTUAL_INTERFACE.test(name))
31
+ .flatMap(([, list]) => list ?? [])
32
+ .filter((a) => a.family === "IPv4" && !a.internal)
33
+ .map((a) => a.address);
34
+ return [dashboardBase(port, host), ...addresses.map(tokenized)];
35
+ }
@@ -0,0 +1,16 @@
1
+ import { readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ // Each agent's mark: static/agents/<adapter id>.svg, a single-colour SVG that carries its name in
5
+ // its <title>. The dashboard alone shows marks, so they live here, not in the adapters. The
6
+ // browser caches the files; the page draws one as a mask, so it takes the text colour of its theme.
7
+ const DIR = fileURLToPath(new URL("./static/agents/", import.meta.url));
8
+ /** Read once at start: a request names a mark by id, and only these ids reach the disk. */
9
+ export const MARKS = new Map(readdirSync(DIR)
10
+ .filter((name) => /^[a-z0-9-]+\.svg$/.test(name))
11
+ .map((name) => {
12
+ const svg = readFileSync(join(DIR, name), "utf8");
13
+ const id = name.slice(0, -".svg".length);
14
+ return [id, { svg, title: /<title>([^<]+)<\/title>/.exec(svg)?.[1] ?? id }];
15
+ }));
16
+ export const markUrl = (id) => `/assets/agents/${id}.svg`;