@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,80 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createServer } from "node:net";
3
+ // The store mutex is a listening TCP socket on loopback. The kernel releases it when the holder
4
+ // dies, so no process ever deletes a lock it judged stale — the race that filesystem-only locks
5
+ // cannot avoid. See docs/design.md → Store lock.
6
+ export class LockTimeoutError extends Error {
7
+ constructor(port) {
8
+ super(`could not acquire the sidecar store lock on 127.0.0.1:${port} before the deadline`);
9
+ this.name = "LockTimeoutError";
10
+ }
11
+ }
12
+ const holding = new AsyncLocalStorage();
13
+ let tail = Promise.resolve();
14
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
15
+ /**
16
+ * Runs `fn` while holding the store lock. Not reentrant: a nested call would wait on itself, so it
17
+ * throws instead. Contenders in one process queue in order; across processes they compete to bind.
18
+ */
19
+ export async function withStoreLock(opts, fn) {
20
+ if (holding.getStore())
21
+ throw new Error("the sidecar store lock is not reentrant");
22
+ const previous = tail;
23
+ let done;
24
+ tail = new Promise((resolve) => {
25
+ done = resolve;
26
+ });
27
+ try {
28
+ // A contender that gives up in the queue passes its turn on; the port still excludes the holder.
29
+ if (!(await settlesBefore(previous, opts.deadline)))
30
+ throw new LockTimeoutError(opts.port);
31
+ const server = await bind(opts);
32
+ try {
33
+ return await holding.run(true, fn);
34
+ }
35
+ finally {
36
+ await new Promise((resolve) => server.close(() => resolve()));
37
+ }
38
+ }
39
+ finally {
40
+ done();
41
+ }
42
+ }
43
+ /** Whether `promise` settles before the deadline. */
44
+ async function settlesBefore(promise, deadline) {
45
+ let timer;
46
+ const expired = new Promise((resolve) => {
47
+ timer = setTimeout(() => resolve(false), Math.max(0, deadline - Date.now()));
48
+ });
49
+ try {
50
+ return await Promise.race([promise.then(() => true), expired]);
51
+ }
52
+ finally {
53
+ clearTimeout(timer);
54
+ }
55
+ }
56
+ async function bind({ port, deadline }) {
57
+ for (;;) {
58
+ if (Date.now() > deadline)
59
+ throw new LockTimeoutError(port);
60
+ const server = createServer((socket) => socket.destroy());
61
+ try {
62
+ await new Promise((resolve, reject) => {
63
+ server.once("error", reject);
64
+ server.listen({ host: "127.0.0.1", port, exclusive: true }, () => {
65
+ server.off("error", reject);
66
+ resolve();
67
+ });
68
+ });
69
+ return server;
70
+ }
71
+ catch (err) {
72
+ if (err.code !== "EADDRINUSE")
73
+ throw err;
74
+ const remaining = deadline - Date.now();
75
+ if (remaining <= 0)
76
+ throw new LockTimeoutError(port);
77
+ await sleep(Math.min(remaining, 5 + Math.random() * 20));
78
+ }
79
+ }
80
+ }
@@ -0,0 +1,58 @@
1
+ import { z } from "zod";
2
+ import { REVIEW_STATUSES } from "./items.js";
3
+ const VERDICTS = ["agree", "disagree", "needs-info"];
4
+ /** A flag is a point the driver acts on, so none is merely informational. */
5
+ const SEVERITIES = ["low", "med", "high"];
6
+ const Flag = z.object({ severity: z.enum(SEVERITIES), body: z.string() });
7
+ const Review = z.object({ ref: z.string(), status: z.enum(REVIEW_STATUSES), body: z.string() });
8
+ const Opinion = z.object({
9
+ verdict: z.enum(VERDICTS),
10
+ body: z.string().refine((b) => b.trim() !== "", "an empty body"),
11
+ flags: z.array(Flag),
12
+ limits: z.array(z.string()),
13
+ reviews: z.array(Review),
14
+ });
15
+ /**
16
+ * The reply schema every navigator turn is held to, passed to the agent CLI's schema flag. Kept
17
+ * literal, not derived from `Opinion`: this exact shape is what both CLIs were checked against.
18
+ */
19
+ export const OPINION_SCHEMA = {
20
+ type: "object",
21
+ additionalProperties: false,
22
+ required: ["verdict", "body", "flags", "limits", "reviews"],
23
+ properties: {
24
+ verdict: { type: "string", enum: VERDICTS },
25
+ body: { type: "string" },
26
+ flags: {
27
+ type: "array",
28
+ items: {
29
+ type: "object",
30
+ additionalProperties: false,
31
+ required: ["severity", "body"],
32
+ properties: {
33
+ severity: { type: "string", enum: SEVERITIES },
34
+ body: { type: "string" },
35
+ },
36
+ },
37
+ },
38
+ limits: { type: "array", items: { type: "string" } },
39
+ reviews: {
40
+ type: "array",
41
+ items: {
42
+ type: "object",
43
+ additionalProperties: false,
44
+ required: ["ref", "status", "body"],
45
+ properties: {
46
+ ref: { type: "string" },
47
+ status: { type: "string", enum: REVIEW_STATUSES },
48
+ body: { type: "string" },
49
+ },
50
+ },
51
+ },
52
+ },
53
+ };
54
+ /** Validates a reply independently of the agent's own schema enforcement. Unknown fields are dropped. */
55
+ export function parseOpinion(value) {
56
+ const parsed = Opinion.safeParse(value);
57
+ return parsed.success ? parsed.data : null;
58
+ }
@@ -0,0 +1,121 @@
1
+ import { applyItemEvent, reviewTargetsOf } from "./items.js";
2
+ import { askUsage } from "./usage.js";
3
+ export const CASE_STATUSES = ["open", "closed"];
4
+ /** The case's state as the tools, the CLI and the dashboard name it. */
5
+ export const caseStatus = (s) => (s.closed ? "closed" : "open");
6
+ const TERMINAL_KINDS = new Set(["opinion", "turn-failed"]);
7
+ /** Derives the current case state from its event log. */
8
+ export function fold(events) {
9
+ const opened = events[0];
10
+ if (!opened || opened.kind !== "opened")
11
+ throw new Error("a case log must start with an opened event");
12
+ const state = {
13
+ opened,
14
+ ...(typeof opened.driverModel === "string" ? { driverModel: opened.driverModel } : {}),
15
+ ...(typeof opened.driverEffort === "string" ? { driverEffort: opened.driverEffort } : {}),
16
+ driverNotes: [],
17
+ asks: new Map(),
18
+ generation: 0,
19
+ sessionStart: -1,
20
+ watermark: -1,
21
+ closed: false,
22
+ items: new Map(),
23
+ };
24
+ const totals = new Map();
25
+ for (const e of events) {
26
+ switch (e.kind) {
27
+ case "attached":
28
+ state.owner = e.owner;
29
+ break;
30
+ case "detached":
31
+ if (state.owner?.token === e.token)
32
+ delete state.owner;
33
+ break;
34
+ case "brief":
35
+ state.brief = e;
36
+ break;
37
+ // The client knows what ran: its record wins over the model's own report.
38
+ case "driver-reported":
39
+ if (typeof e.model === "string")
40
+ state.driverModel = e.model;
41
+ if (typeof e.effort === "string")
42
+ state.driverEffort = e.effort;
43
+ break;
44
+ case "decision":
45
+ case "note":
46
+ state.driverNotes.push(e);
47
+ break;
48
+ case "opinion": {
49
+ const attempt = state.asks
50
+ .get(String(e.askId))
51
+ ?.attempts.find((a) => a.attemptId === e.attemptId);
52
+ state.watermark = attempt?.started.n ?? e.n;
53
+ break;
54
+ }
55
+ case "ask":
56
+ state.asks.set(String(e.askId), {
57
+ askId: String(e.askId),
58
+ key: String(e.key),
59
+ bodyHash: String(e.bodyHash),
60
+ event: e,
61
+ attempts: [],
62
+ });
63
+ break;
64
+ case "turn-started": {
65
+ const ask = state.asks.get(String(e.askId));
66
+ ask?.attempts.push({
67
+ attemptId: String(e.attemptId),
68
+ runnerPid: Number(e.runnerPid),
69
+ runnerStart: e.runnerStart ?? null,
70
+ hardDeadline: Number(e.hardDeadline),
71
+ reviewTargets: reviewTargetsOf(e),
72
+ started: e,
73
+ });
74
+ break;
75
+ }
76
+ case "navigator-session":
77
+ if (state.sessionId !== String(e.sessionId))
78
+ state.sessionStart = e.n;
79
+ state.sessionId = String(e.sessionId);
80
+ state.generation = Number(e.generation);
81
+ break;
82
+ case "session-reset":
83
+ // The new session's id may be unknown when the re-brief turn failed before reporting it.
84
+ if (e.newSessionId)
85
+ state.sessionId = String(e.newSessionId);
86
+ else
87
+ delete state.sessionId;
88
+ state.generation = Number(e.generation);
89
+ state.sessionStart = e.n;
90
+ break;
91
+ case "closed":
92
+ state.closed = true;
93
+ break;
94
+ // A reopened case keeps its items, review counts and navigator session: the same work continues.
95
+ case "reopened":
96
+ state.closed = false;
97
+ break;
98
+ // Old logs have them; a paused case reads as open.
99
+ case "paused":
100
+ case "resumed":
101
+ break;
102
+ }
103
+ applyItemEvent(state.items, e, (askId) => state.asks.get(askId)?.event);
104
+ if (TERMINAL_KINDS.has(e.kind)) {
105
+ const ask = state.asks.get(String(e.askId));
106
+ if (ask && !ask.terminal) {
107
+ ask.terminal = e;
108
+ if (Array.isArray(e.invocations))
109
+ ask.usage = askUsage(e.invocations, totals);
110
+ // A turn ended by someone other than its runner may have spent tokens nobody counted.
111
+ else if (state.sessionId !== undefined)
112
+ totals.set(state.sessionId, null);
113
+ }
114
+ }
115
+ }
116
+ for (const ask of state.asks.values()) {
117
+ if (!ask.terminal)
118
+ state.inFlight = ask;
119
+ }
120
+ return state;
121
+ }
@@ -0,0 +1,181 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { closeSync, existsSync, fsyncSync, ftruncateSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, writeSync, } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { loadConfig, sidecarHome } from "../config.js";
5
+ import { isEvent } from "./events.js";
6
+ import { failpoint, failpointActive } from "../lib/failpoint.js";
7
+ import { withStoreLock } from "./lock.js";
8
+ /** How long one store operation may wait for the lock. */
9
+ const LOCK_WAIT_MS = 5_000;
10
+ /** Whether `name` has a case id's form: it then names no path but its own directory. */
11
+ export const isCaseId = (name) => /^[0-9a-f]{8}$/.test(name);
12
+ export function defaultStoreOptions() {
13
+ const home = sidecarHome();
14
+ return { home, lockPort: loadConfig(home).lockPort };
15
+ }
16
+ export class CaseNotFoundError extends Error {
17
+ constructor(caseId) {
18
+ super(`no such case: ${caseId}`);
19
+ this.name = "CaseNotFoundError";
20
+ }
21
+ }
22
+ /** A newline-terminated line that is not a valid event. The case becomes read-only. */
23
+ export class CaseCorruptError extends Error {
24
+ constructor(caseId, line, reason) {
25
+ super(`case ${caseId} is corrupt at line ${line}: ${reason}. sidecar will not write to it`);
26
+ this.name = "CaseCorruptError";
27
+ }
28
+ }
29
+ export class Store {
30
+ casesDir;
31
+ options;
32
+ constructor(opts) {
33
+ this.options = opts;
34
+ this.casesDir = join(opts.home, "cases");
35
+ }
36
+ /**
37
+ * Creates a case whose first event is `opened`, followed by `following`. The new directory claims
38
+ * the id. The log is written under a temporary name and renamed into place, so readers and a
39
+ * crash see the whole initial log or no case. With `scratch`, the case's workspace is an empty
40
+ * `scratch` directory inside it, made before the log, so no reader sees a workspace that is not
41
+ * there yet.
42
+ */
43
+ async createCase(opened, following = [], opts = {}) {
44
+ mkdirSync(this.casesDir, { recursive: true });
45
+ for (let attempt = 0; attempt < 16; attempt++) {
46
+ const caseId = randomBytes(4).toString("hex");
47
+ const dir = join(this.casesDir, caseId);
48
+ try {
49
+ mkdirSync(dir);
50
+ }
51
+ catch (err) {
52
+ if (err.code === "EEXIST")
53
+ continue;
54
+ throw err;
55
+ }
56
+ fsyncDir(this.casesDir);
57
+ const workspace = opts.scratch ? join(dir, "scratch") : opened.workspace;
58
+ if (opts.scratch)
59
+ mkdirSync(workspace);
60
+ const ts = now();
61
+ const events = [
62
+ { ...opened, workspace, n: 0, ts, author: "sidecar", kind: "opened" },
63
+ ...following.map((draft, i) => ({ ...draft, n: i + 1, ts })),
64
+ ];
65
+ const tmp = join(dir, "events.jsonl.tmp");
66
+ const fd = openSync(tmp, "wx");
67
+ try {
68
+ writeAll(fd, Buffer.from(events.map((e) => JSON.stringify(e) + "\n").join("")), 0);
69
+ fsyncSync(fd);
70
+ }
71
+ finally {
72
+ closeSync(fd);
73
+ }
74
+ renameSync(tmp, this.logPath(caseId));
75
+ fsyncDir(dir);
76
+ return { caseId, workspace };
77
+ }
78
+ throw new Error("could not allocate a case id");
79
+ }
80
+ /** Reads every complete event. An unterminated last line is ignored, never repaired here. */
81
+ read(caseId) {
82
+ return this.#locked(() => this.#load(caseId).events);
83
+ }
84
+ /**
85
+ * Runs `fn` under the store lock with the case's events as of the start of the transaction.
86
+ * `fn` is synchronous on purpose: nothing may wait for a navigator while holding the lock.
87
+ */
88
+ transact(caseId, fn) {
89
+ return this.#locked(() => {
90
+ const loaded = this.#load(caseId);
91
+ let nextN = loaded.events.length;
92
+ let validLength = loaded.validLength;
93
+ let repaired = loaded.validLength === loaded.size;
94
+ const append = (draft) => {
95
+ const event = { ...draft, n: nextN, ts: now() };
96
+ const line = Buffer.from(JSON.stringify(event) + "\n");
97
+ const fd = openSync(this.logPath(caseId), "r+");
98
+ try {
99
+ if (!repaired) {
100
+ ftruncateSync(fd, validLength);
101
+ repaired = true;
102
+ }
103
+ if (failpointActive("store.append.partial")) {
104
+ writeAll(fd, line.subarray(0, Math.floor(line.length / 2)), validLength);
105
+ fsyncSync(fd);
106
+ failpoint("store.append.partial");
107
+ }
108
+ writeAll(fd, line, validLength);
109
+ fsyncSync(fd);
110
+ }
111
+ finally {
112
+ closeSync(fd);
113
+ }
114
+ validLength += line.length;
115
+ nextN++;
116
+ return event;
117
+ };
118
+ return fn(Object.freeze(loaded.events), append);
119
+ });
120
+ }
121
+ listCaseIds() {
122
+ if (!existsSync(this.casesDir))
123
+ return [];
124
+ return readdirSync(this.casesDir).filter((name) => isCaseId(name) && existsSync(this.logPath(name)));
125
+ }
126
+ #locked(fn) {
127
+ const deadline = Date.now() + LOCK_WAIT_MS;
128
+ return withStoreLock({ port: this.options.lockPort, deadline }, fn);
129
+ }
130
+ /** The case's log file. An id of any other form names no case. */
131
+ logPath(caseId) {
132
+ if (!isCaseId(caseId))
133
+ throw new CaseNotFoundError(caseId);
134
+ return join(this.casesDir, caseId, "events.jsonl");
135
+ }
136
+ #load(caseId) {
137
+ const path = this.logPath(caseId);
138
+ if (!existsSync(path))
139
+ throw new CaseNotFoundError(caseId);
140
+ const bytes = readFileSync(path);
141
+ const validLength = bytes.lastIndexOf(0x0a) + 1;
142
+ const complete = bytes.subarray(0, validLength).toString("utf8");
143
+ const events = complete === ""
144
+ ? []
145
+ : complete
146
+ .slice(0, -1)
147
+ .split("\n")
148
+ .map((line, i) => {
149
+ let event;
150
+ try {
151
+ event = JSON.parse(line);
152
+ }
153
+ catch {
154
+ throw new CaseCorruptError(caseId, i + 1, "not valid JSON");
155
+ }
156
+ if (!isEvent(event) || event.n !== i) {
157
+ throw new CaseCorruptError(caseId, i + 1, `not event n=${i}`);
158
+ }
159
+ return event;
160
+ });
161
+ return { events, validLength, size: bytes.length };
162
+ }
163
+ }
164
+ /** writeSync may write fewer bytes than asked; loop until the whole buffer is on disk. */
165
+ function writeAll(fd, buf, position) {
166
+ let offset = 0;
167
+ while (offset < buf.length) {
168
+ offset += writeSync(fd, buf, offset, buf.length - offset, position + offset);
169
+ }
170
+ }
171
+ /** Makes a new directory entry durable. */
172
+ function fsyncDir(dir) {
173
+ const fd = openSync(dir, "r");
174
+ try {
175
+ fsyncSync(fd);
176
+ }
177
+ finally {
178
+ closeSync(fd);
179
+ }
180
+ }
181
+ const now = () => new Date().toISOString();
@@ -0,0 +1,36 @@
1
+ const FIELDS = ["input", "cachedInput", "cacheWrite", "output", "reasoning"];
2
+ const ZERO = { input: 0, cachedInput: 0, cacheWrite: 0, output: 0, reasoning: 0 };
3
+ const sum = (a, b) => Object.fromEntries(FIELDS.map((f) => [f, a[f] + b[f]]));
4
+ const minus = (a, b) => FIELDS.every((f) => a[f] >= b[f])
5
+ ? Object.fromEntries(FIELDS.map((f) => [f, a[f] - b[f]]))
6
+ : null;
7
+ /**
8
+ * The counts an invocation spent itself. A running total counts only against a known total of the
9
+ * same session: after a missing report, or a total lower than the last one, it is unknown. The gap
10
+ * could hold several asks' tokens, and a lower total says nothing reliable. Either way the report
11
+ * becomes the session's new baseline.
12
+ */
13
+ function own(inv, totals) {
14
+ if (inv.scope === "turn")
15
+ return inv.usage;
16
+ const base = inv.fresh
17
+ ? ZERO
18
+ : inv.sessionId !== null
19
+ ? (totals.get(inv.sessionId) ?? null)
20
+ : null;
21
+ if (inv.sessionId !== null)
22
+ totals.set(inv.sessionId, inv.usage);
23
+ return inv.usage && base ? minus(inv.usage, base) : null;
24
+ }
25
+ /** An ask's usage from its terminal event's invocations. Updates the session totals. */
26
+ export function askUsage(invocations, totals) {
27
+ const parts = invocations.map((inv) => own(inv, totals));
28
+ const models = [...new Set(invocations.flatMap((i) => i.models ?? []))];
29
+ return {
30
+ usage: parts.every((p) => p !== null) ? parts.reduce((a, p) => sum(a, p), ZERO) : null,
31
+ toolCalls: invocations.every((i) => i.toolCalls !== null)
32
+ ? invocations.reduce((a, i) => a + i.toolCalls, 0)
33
+ : null,
34
+ models: models.length > 0 ? models : null,
35
+ };
36
+ }
@@ -0,0 +1,18 @@
1
+ import { adapters } from "../adapters/index.js";
2
+ import { isInstalled } from "../adapters/installed.js";
3
+ import { defaultSpec, installService, serviceStatus, uninstallService, } from "../dashboard/service.js";
4
+ import { exec } from "../lib/command.js";
5
+ /** The deps with every default filled in. */
6
+ export function withDefaults({ home, ...deps }) {
7
+ return {
8
+ all: deps.adapters ?? adapters(),
9
+ /** Each role is found on its own: an agent may be a navigator only, or a driver only. */
10
+ found: (adapter, role) => deps.installed?.(adapter.id) ?? isInstalled(role),
11
+ run: deps.run ?? exec,
12
+ service: deps.service ?? {
13
+ status: () => serviceStatus(defaultSpec(home)),
14
+ install: () => installService(defaultSpec(home)),
15
+ uninstall: () => uninstallService(),
16
+ },
17
+ };
18
+ }
@@ -0,0 +1,11 @@
1
+ import { dim, pad } from "./style.js";
2
+ // Section lines that setup and status share.
3
+ /** Every known agent on one line: installed ones ticked, the rest dim. */
4
+ export const agentsLine = (all, installed) => all
5
+ .map((a) => (installed.includes(a) ? `${dim("✓")} ${a.id}` : dim(`${a.id} not installed`)))
6
+ .join(" ");
7
+ /** A registration target as "agent where", from labels such as "claude-code — ~/.claude-x". */
8
+ export function targetLine(label) {
9
+ const [name, where] = label.split(" — ");
10
+ return where ? pad(name, 16) + dim(where) : label;
11
+ }
@@ -0,0 +1,44 @@
1
+ import { caseStatus, fold } from "../cases/state.js";
2
+ import { Store } from "../cases/store.js";
3
+ import { loadConfig } from "../config.js";
4
+ import { processAlive } from "../lib/proc.js";
5
+ export async function runList({ home, state, print = console.log }) {
6
+ const store = new Store({ home, lockPort: loadConfig(home).lockPort });
7
+ const rows = [];
8
+ for (const caseId of store.listCaseIds()) {
9
+ try {
10
+ const s = fold(await store.read(caseId));
11
+ const current = caseStatus(s);
12
+ if (state && state !== current)
13
+ continue;
14
+ const owner = s.owner
15
+ ? processAlive(s.owner.pid, s.owner.start)
16
+ ? `pid ${s.owner.pid}`
17
+ : "gone"
18
+ : "-";
19
+ rows.push([
20
+ caseId,
21
+ current,
22
+ String(s.opened.navigator),
23
+ owner,
24
+ s.opened.ts.slice(0, 16),
25
+ String(s.opened.title),
26
+ ]);
27
+ }
28
+ catch (err) {
29
+ rows.push([caseId, "unreadable", "-", "-", "-", err.message]);
30
+ }
31
+ }
32
+ rows.sort((a, b) => b[4].localeCompare(a[4]));
33
+ printTable(["CASE", "STATE", "NAVIGATOR", "OWNER", "CREATED", "TITLE"], rows, print);
34
+ }
35
+ function printTable(header, rows, print) {
36
+ if (rows.length === 0) {
37
+ print("no cases");
38
+ return;
39
+ }
40
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)));
41
+ for (const row of [header, ...rows]) {
42
+ print(row.map((cell, i) => (i === row.length - 1 ? cell : cell.padEnd(widths[i]))).join(" "));
43
+ }
44
+ }