@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,383 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { SERVER_NAME, sidecarHome } from "../config.js";
6
+ import { parseOpinion } from "../cases/opinion.js";
7
+ import { writeFileAtomic } from "../lib/atomic-write.js";
8
+ import { exec } from "../lib/command.js";
9
+ import { count, failed, tail } from "./outcome.js";
10
+ import { envArgs, judgeRegistration } from "./registration.js";
11
+ // Launch policy: docs/design.md → Launch policy → codex. Every turn passes the full policy;
12
+ // `exec resume` has no `-s`, and a resumed session does not reliably keep its first sandbox.
13
+ // User context stays out of the independent navigator, whatever the user's config says: memories
14
+ // (notes written for the driver), developer instructions, hooks (user scripts run on session
15
+ // start), plugins, apps, and sidecar's own MCP server (see sidecarServerOff).
16
+ const ID = "codex";
17
+ /** The CLI on PATH, for both roles. The runner tells a missing CLI by this name. */
18
+ const COMMAND = "codex";
19
+ const POLICY = [
20
+ "--json",
21
+ "--skip-git-repo-check",
22
+ "-c",
23
+ 'sandbox_mode="read-only"',
24
+ "-c",
25
+ 'approval_policy="never"',
26
+ "-c",
27
+ "features.memories=false",
28
+ "-c",
29
+ 'developer_instructions=""',
30
+ "-c",
31
+ "features.hooks=false",
32
+ "-c",
33
+ "features.plugins=false",
34
+ "-c",
35
+ "features.apps=false",
36
+ // Web search runs on the model's side, not in the sandbox, which still denies shell network
37
+ // access. Pinned, so the navigator can look things up whatever the user's config says.
38
+ "-c",
39
+ 'web_search="live"',
40
+ ];
41
+ /**
42
+ * Disables sidecar's MCP server: its tools would let the navigator act on cases. codex validates an
43
+ * entry even when it is disabled. A defined entry needs only enabled=false, since a command would
44
+ * clash with a url transport; an entry the config lacks needs a transport, or the config fails to
45
+ * load ("invalid transport").
46
+ */
47
+ export function sidecarServerOff(defined) {
48
+ return [
49
+ "-c",
50
+ `mcp_servers.${SERVER_NAME}.enabled=false`,
51
+ ...(defined ? [] : ["-c", `mcp_servers.${SERVER_NAME}.command="true"`]),
52
+ ];
53
+ }
54
+ /**
55
+ * codex itself resolves the entry, in whatever TOML form, profile or CODEX_HOME defines it. Bounded:
56
+ * the call blocks the runner, its deadline timer included. A timeout reads as false, which adds a
57
+ * transport to the override; codex then fails at launch only if a url entry exists.
58
+ */
59
+ export function sidecarDefined(env = {}, timeoutMs = 10_000) {
60
+ return exec(mcpGet(env), { timeoutMs }).ok;
61
+ }
62
+ /** codex's own view of sidecar's entry, as JSON. */
63
+ const mcpGet = (env) => ({
64
+ command: COMMAND,
65
+ args: ["mcp", "get", SERVER_NAME, "--json"],
66
+ env,
67
+ });
68
+ function options(opts, schema) {
69
+ const args = [...POLICY, ...sidecarServerOff(sidecarDefined())];
70
+ if (opts.model)
71
+ args.push("-m", opts.model);
72
+ // JSON string literals are valid TOML basic strings, which `-c` parses.
73
+ if (opts.effort)
74
+ args.push("-c", `model_reasoning_effort=${JSON.stringify(opts.effort)}`);
75
+ args.push("--output-schema", schemaFile(schema));
76
+ return args;
77
+ }
78
+ /**
79
+ * `--output-schema` takes a file. One file per schema content, reused across turns. It lives in the
80
+ * sidecar home, not the shared tmpdir, where another user could plant it; a file whose content
81
+ * differs, e.g. from a torn write, is replaced atomically.
82
+ */
83
+ function schemaFile(schema) {
84
+ const text = JSON.stringify(schema);
85
+ const dir = join(sidecarHome(), "schemas");
86
+ const path = join(dir, `${createHash("sha256").update(text).digest("hex").slice(0, 16)}.json`);
87
+ let current = null;
88
+ try {
89
+ current = readFileSync(path, "utf8");
90
+ }
91
+ catch { }
92
+ if (current !== text)
93
+ writeFileAtomic(path, text, 0o600);
94
+ return path;
95
+ }
96
+ /** The exec exporter's tool item types: codex-rs/exec/src/exec_events.rs, ThreadItemDetails. */
97
+ const TOOL_ITEMS = new Set([
98
+ "command_execution",
99
+ "file_change",
100
+ "mcp_tool_call",
101
+ "collab_tool_call",
102
+ "web_search",
103
+ ]);
104
+ function events(stdout) {
105
+ return stdout.split("\n").flatMap((line) => {
106
+ try {
107
+ const parsed = JSON.parse(line);
108
+ return typeof parsed === "object" && parsed !== null ? [parsed] : [];
109
+ }
110
+ catch {
111
+ return [];
112
+ }
113
+ });
114
+ }
115
+ /**
116
+ * sidecar's own labels, not the catalog's `display_name`: that one is inconsistent ("GPT-6.1-Sol",
117
+ * "GPT-6.1 Terra"), and reading it takes a subprocess.
118
+ */
119
+ const LABELS = {
120
+ models: {
121
+ "gpt-6.1-sol": "GPT-6.1 Sol",
122
+ "gpt-6.1-terra": "GPT-6.1 Terra",
123
+ "gpt-6-astra": "GPT-6 Astra",
124
+ "gpt-6-sol": "GPT-6 Sol",
125
+ "gpt-6-luna": "GPT-6 Luna",
126
+ "gpt-5.6-sol": "GPT-5.6 Sol",
127
+ "gpt-5.6-terra": "GPT-5.6 Terra",
128
+ "gpt-5.6-luna": "GPT-5.6 Luna",
129
+ },
130
+ efforts: {
131
+ none: "None",
132
+ minimal: "Minimal",
133
+ low: "Low",
134
+ medium: "Medium",
135
+ high: "High",
136
+ xhigh: "Extra high",
137
+ max: "Max",
138
+ },
139
+ };
140
+ /**
141
+ * Codex's catalog lists `ultra`, which its server rejects; never offer it. A `debug` command is no
142
+ * stable interface: any failure, or output of another shape, gives no catalog.
143
+ */
144
+ function models() {
145
+ const run = exec({ command: COMMAND, args: ["debug", "models"] });
146
+ if (!run.ok)
147
+ return [];
148
+ let catalog;
149
+ try {
150
+ catalog = JSON.parse(run.stdout);
151
+ }
152
+ catch {
153
+ return [];
154
+ }
155
+ if (!Array.isArray(catalog?.models))
156
+ return [];
157
+ return catalog.models
158
+ .filter((m) => m.visibility === "list")
159
+ .map((m) => ({
160
+ model: m.slug,
161
+ efforts: (m.supported_reasoning_levels ?? [])
162
+ .map((l) => l.effort)
163
+ .filter((e) => e !== "ultra"),
164
+ }));
165
+ }
166
+ const navigator = {
167
+ command: COMMAND,
168
+ turnTimeoutMs: 15 * 60_000,
169
+ start(opts, schema, prompt) {
170
+ // A prompt argument of "-" makes codex read the prompt from stdin.
171
+ return {
172
+ invocation: {
173
+ command: COMMAND,
174
+ args: ["exec", "-s", "read-only", ...options(opts, schema), "--", "-"],
175
+ input: prompt,
176
+ },
177
+ sessionId: null,
178
+ };
179
+ },
180
+ resume(sessionId, opts, schema, prompt) {
181
+ return {
182
+ invocation: {
183
+ command: COMMAND,
184
+ args: ["exec", "resume", ...options(opts, schema), "--", sessionId, "-"],
185
+ input: prompt,
186
+ },
187
+ sessionId,
188
+ };
189
+ },
190
+ sessionIdFrom(stdout) {
191
+ return (events(stdout).find((e) => e.type === "thread.started" && e.thread_id)?.thread_id ?? null);
192
+ },
193
+ // turn.completed carries the thread's running total, not the turn's own counts: the exporter
194
+ // copies usage.total, and a resumed thread reports its earlier turns too (measured). A missing
195
+ // counter makes the usage unknown, not zero.
196
+ measure(stdout) {
197
+ const all = events(stdout);
198
+ const u = all.filter((e) => e.type === "turn.completed").at(-1)?.usage;
199
+ const fields = u &&
200
+ [
201
+ u.input_tokens,
202
+ u.cached_input_tokens,
203
+ u.cache_write_input_tokens,
204
+ u.output_tokens,
205
+ u.reasoning_output_tokens,
206
+ ].map(count);
207
+ const usage = fields && fields.every((f) => f !== null)
208
+ ? {
209
+ input: fields[0],
210
+ cachedInput: fields[1],
211
+ cacheWrite: fields[2],
212
+ output: fields[3],
213
+ reasoning: fields[4],
214
+ }
215
+ : null;
216
+ const toolCalls = all.filter((e) => e.type === "item.completed" && TOOL_ITEMS.has(e.item?.type ?? "")).length;
217
+ // The JSON events do not name the model.
218
+ return { usage, scope: "session", toolCalls, models: null };
219
+ },
220
+ classify({ exitCode, stdout, stderr }) {
221
+ if (/no rollout found for thread id/.test(stderr)) {
222
+ return { kind: "failed", outcome: "session-missing", detail: tail(stderr) };
223
+ }
224
+ const all = events(stdout);
225
+ const errors = all
226
+ .filter((e) => e.type === "error" || e.type === "turn.failed")
227
+ .map((e) => e.message ?? e.error?.message ?? "")
228
+ .filter((m) => m !== "");
229
+ if (exitCode !== 0 || errors.length > 0) {
230
+ return failed(`exit ${exitCode}: `, [...errors, stderr.trim()].filter((s) => s !== "").join("\n"));
231
+ }
232
+ const reply = all
233
+ .filter((e) => e.type === "item.completed" && e.item?.type === "agent_message")
234
+ .at(-1)?.item?.text;
235
+ let parsed;
236
+ try {
237
+ parsed = JSON.parse(reply ?? "");
238
+ }
239
+ catch {
240
+ return { kind: "failed", outcome: "malformed-reply", detail: tail(reply ?? stdout) };
241
+ }
242
+ const opinion = parseOpinion(parsed);
243
+ return opinion
244
+ ? { kind: "opinion", opinion }
245
+ : { kind: "failed", outcome: "malformed-reply", detail: tail(reply ?? "") };
246
+ },
247
+ models,
248
+ };
249
+ /**
250
+ * Whether each line starts inside a TOML multiline string. A line there is string content, never
251
+ * a table header or a key, whatever it looks like.
252
+ */
253
+ function inMultilineString(lines) {
254
+ let open = null;
255
+ return lines.map((line) => {
256
+ const starts = open !== null;
257
+ for (let i = 0; i < line.length;) {
258
+ if (open) {
259
+ if (open === '"""' && line[i] === "\\") {
260
+ i += 2;
261
+ continue;
262
+ }
263
+ if (line.startsWith(open, i)) {
264
+ i += 3;
265
+ open = null;
266
+ continue;
267
+ }
268
+ i++;
269
+ continue;
270
+ }
271
+ const c = line[i];
272
+ if (c === "#")
273
+ break;
274
+ if (line.startsWith('"""', i) || line.startsWith("'''", i)) {
275
+ open = line.slice(i, i + 3);
276
+ i += 3;
277
+ continue;
278
+ }
279
+ if (c === '"' || c === "'") {
280
+ // A one-line string: skip to its closing quote; a basic string's escapes may hide one.
281
+ let j = i + 1;
282
+ while (j < line.length && line[j] !== c)
283
+ j += c === '"' && line[j] === "\\" ? 2 : 1;
284
+ i = j + 1;
285
+ continue;
286
+ }
287
+ i++;
288
+ }
289
+ return starts;
290
+ });
291
+ }
292
+ /** Sets `default_tools_approval_mode = "approve"` inside `[mcp_servers.sidecar]`, and nowhere else. */
293
+ export function withCodexAutoApprove(toml) {
294
+ const lines = toml.split("\n");
295
+ const inString = inMultilineString(lines);
296
+ const header = lines.findIndex((l, i) => !inString[i] && l.trim() === `[mcp_servers.${SERVER_NAME}]`);
297
+ if (header === -1)
298
+ throw new Error(`no [mcp_servers.${SERVER_NAME}] table in the codex config`);
299
+ let end = lines.findIndex((l, i) => i > header && !inString[i] && /^\s*\[/.test(l));
300
+ if (end === -1)
301
+ end = lines.length;
302
+ const setting = 'default_tools_approval_mode = "approve"';
303
+ const existing = lines.findIndex((l, i) => i > header && i < end && !inString[i] && /^\s*default_tools_approval_mode\s*=/.test(l));
304
+ if (existing !== -1)
305
+ lines[existing] = setting;
306
+ else
307
+ lines.splice(header + 1, 0, setting);
308
+ return lines.join("\n");
309
+ }
310
+ function codexRegistration(run, env, expected) {
311
+ const result = run(mcpGet(env));
312
+ if (!result.ok)
313
+ return /No MCP server named/.test(result.output)
314
+ ? { state: "missing" }
315
+ : { state: "unreadable", detail: result.output };
316
+ try {
317
+ const server = JSON.parse(result.output);
318
+ return judgeRegistration({
319
+ command: [server.transport?.command ?? "", ...(server.transport?.args ?? [])],
320
+ env: server.transport?.env,
321
+ }, expected);
322
+ }
323
+ catch (err) {
324
+ return { state: "unreadable", detail: err.message };
325
+ }
326
+ }
327
+ /** Every codex command runs in the target's config directory, which afterAdd then edits. */
328
+ const home = (target) => ({ CODEX_HOME: target.configDir });
329
+ /**
330
+ * `codex mcp remove` drops the whole `[mcp_servers.sidecar]` table, the auto-approve line with it.
331
+ * The only direct config edit is that line, in the table `codex mcp add` itself just created:
332
+ * without it, codex asks before every sidecar call.
333
+ */
334
+ const driver = {
335
+ command: COMMAND,
336
+ // codex waits 300 s for a tool call by default (measured 0.154.0).
337
+ askBudgetMs: 240_000,
338
+ targets: () => [
339
+ { label: "codex", configDir: process.env.CODEX_HOME ?? join(homedir(), ".codex") },
340
+ ],
341
+ plan: {
342
+ remove: (target) => ({
343
+ command: COMMAND,
344
+ args: ["mcp", "remove", SERVER_NAME],
345
+ env: home(target),
346
+ }),
347
+ // codex writes the variables into an [mcp_servers.sidecar.env] table (0.163.0).
348
+ add: (target, server) => ({
349
+ command: COMMAND,
350
+ args: ["mcp", "add", SERVER_NAME, ...envArgs("--env", server.env), "--", ...server.command],
351
+ env: home(target),
352
+ }),
353
+ },
354
+ read: (target, run, expected) => codexRegistration(run, home(target), expected),
355
+ afterAdd(target) {
356
+ const file = join(target.configDir, "config.toml");
357
+ if (!existsSync(file))
358
+ throw new Error(`${file} not found after codex mcp add`);
359
+ // The replacement keeps the file's mode: the config can hold credentials for MCP servers.
360
+ writeFileAtomic(file, withCodexAutoApprove(readFileSync(file, "utf8")), statSync(file).mode & 0o777);
361
+ },
362
+ reported: reportedTurn,
363
+ };
364
+ /**
365
+ * Codex sends each tool call the turn's model and effort, in `_meta["x-codex-turn-metadata"]`
366
+ * (measured: exec 0.164.0 and 0.166.0, interactive 0.164.0). A field of another type is not reported.
367
+ */
368
+ export function reportedTurn(meta) {
369
+ const turn = meta?.["x-codex-turn-metadata"];
370
+ if (typeof turn !== "object" || turn === null)
371
+ return {};
372
+ const { model, reasoning_effort: effort } = turn;
373
+ return {
374
+ ...(typeof model === "string" && model ? { model } : {}),
375
+ ...(typeof effort === "string" && effort ? { effort } : {}),
376
+ };
377
+ }
378
+ export const codex = {
379
+ id: ID,
380
+ labels: LABELS,
381
+ navigator,
382
+ driver,
383
+ };
@@ -0,0 +1,38 @@
1
+ import { claudeCode } from "./claude-code.js";
2
+ import { claudeDesktop } from "./claude-desktop.js";
3
+ import { codex } from "./codex.js";
4
+ const ADAPTERS = {
5
+ "claude-code": claudeCode,
6
+ codex,
7
+ "claude-desktop": claudeDesktop,
8
+ };
9
+ /** Every adapter, in a stable order: setup, status and the navigator choice list them so. */
10
+ export const adapters = () => Object.values(ADAPTERS);
11
+ export function findAdapter(id) {
12
+ // Own keys only: inherited names such as `constructor` are not adapters.
13
+ return Object.hasOwn(ADAPTERS, id) ? ADAPTERS[id] : undefined;
14
+ }
15
+ /** The label a list gives an id; the id itself when it is not listed. */
16
+ export const labelIn = (labels, id) => labels && Object.hasOwn(labels, id) ? labels[id] : id;
17
+ /** The agent's label for a model id; the id itself for an unlisted model or an unknown agent. */
18
+ export const modelLabel = (agent, model) => labelIn(findAdapter(agent)?.labels.models, model);
19
+ /** The agent's label for an effort id; the id itself for an unlisted effort or an unknown agent. */
20
+ export const effortLabel = (agent, effort) => labelIn(findAdapter(agent)?.labels.efforts, effort);
21
+ export function getNavigator(id) {
22
+ const navigator = findAdapter(id)?.navigator;
23
+ if (!navigator)
24
+ throw new Error(`unknown navigator adapter: ${id}`);
25
+ return navigator;
26
+ }
27
+ /** Every adapter that can navigate. */
28
+ export const selectableNavigatorIds = () => adapters()
29
+ .filter((a) => a.navigator)
30
+ .map((a) => a.id);
31
+ /**
32
+ * The navigator to suggest: another agent than the driver, because an independent second opinion
33
+ * is the point; the driver's own agent only when it is the one available. Candidates keep adapter
34
+ * order, so a choice among several is stable.
35
+ */
36
+ export function preferredNavigator(driver, candidates) {
37
+ return candidates.find((id) => id !== driver?.id) ?? candidates[0];
38
+ }
@@ -0,0 +1,25 @@
1
+ import { accessSync, constants, statSync } from "node:fs";
2
+ import { delimiter, isAbsolute, join } from "node:path";
3
+ /**
4
+ * Whether a role's command resolves to an executable file, as the runner's spawn looks it up. An
5
+ * agent that finds itself (`installed()`) decides on its own.
6
+ */
7
+ export function isInstalled(role, path = process.env.PATH ?? "") {
8
+ if (role.installed)
9
+ return role.installed();
10
+ const files = isAbsolute(role.command)
11
+ ? [role.command]
12
+ : path
13
+ .split(delimiter)
14
+ .filter(Boolean)
15
+ .map((dir) => join(dir, role.command));
16
+ return files.some((file) => {
17
+ try {
18
+ accessSync(file, constants.X_OK);
19
+ return statSync(file).isFile();
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ });
25
+ }
@@ -0,0 +1,30 @@
1
+ // Helpers the navigators share to read an agent's output into a turn outcome.
2
+ /** A non-negative integer count, or null for anything else. */
3
+ export const count = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
4
+ const TAIL_MAX = 2_000;
5
+ /** The end of a long diagnostic: what an agent prints last says most about why it failed. */
6
+ export const tail = (text) => (text.length > TAIL_MAX ? text.slice(-TAIL_MAX) : text);
7
+ /** A status code as an HTTP status, not a number in a path or a count. */
8
+ const status = (code, reason) => new RegExp(`\\b(?:HTTP(?:/[\\d.]+)?|status|code)[ :=]*${code}\\b|\\b${code} ${reason}`, "i");
9
+ /** An invalid key or token as the subject, as in "Invalid API key", not "invalid token count". */
10
+ const INVALID_CREDENTIAL = /invalid[ _-]?(?:api[ _-]?)?(?:key|token)\b(?![ \t]+(?!provided\b)[a-z])/i;
11
+ /** `auth` or `rate-limit` only when an explicit diagnostic says so; no match means no hint. */
12
+ export function hintFrom(text) {
13
+ if (status(401, "Unauthorized").test(text) ||
14
+ INVALID_CREDENTIAL.test(text) ||
15
+ /unauthori[sz]ed|not logged in|please (run )?\/?login|failed to authenticate|oauth (session|token) (has )?expired/i.test(text))
16
+ return "auth";
17
+ if (status(429, "Too Many Requests").test(text) || /rate[ _-]?limit|usage limit/i.test(text))
18
+ return "rate-limit";
19
+ return undefined;
20
+ }
21
+ /** The hint comes from the whole diagnostic; the stored detail keeps its tail. */
22
+ export function failed(prefix, diagnostic) {
23
+ const hint = hintFrom(`${prefix}${diagnostic}`);
24
+ return {
25
+ kind: "failed",
26
+ outcome: "failed",
27
+ detail: `${prefix}${tail(diagnostic)}`,
28
+ ...(hint ? { hint } : {}),
29
+ };
30
+ }
@@ -0,0 +1,69 @@
1
+ import { DEFAULT_HOME } from "../config.js";
2
+ import { exec } from "../lib/command.js";
3
+ import { modulePath } from "../lib/paths.js";
4
+ // Registers sidecar's MCP server with a driver agent. Each driver states its own commands; these
5
+ // functions run them the same way for every agent.
6
+ export const MCP_ENTRY = modulePath("../../bin/sidecar-mcp", import.meta.url);
7
+ /**
8
+ * The server setup registers for a driver: `node`, the entry and the adapter's id. A store home
9
+ * other than the default travels as SIDECAR_HOME, so a server the agent starts uses the same store
10
+ * as setup and the dashboard. `node` is the absolute path of the Node running setup: the agent's
11
+ * own PATH may resolve an older Node without type stripping.
12
+ */
13
+ export const serverFor = (driverId, home, node = process.execPath) => ({
14
+ command: [node, MCP_ENTRY, "--driver", driverId],
15
+ env: home === DEFAULT_HOME ? {} : { SIDECAR_HOME: home },
16
+ });
17
+ /** Replaces any existing registration, so re-running setup is safe. */
18
+ export function register(driver, target, server, run = exec) {
19
+ if (driver.edit) {
20
+ driver.edit.add(target, server, run);
21
+ return;
22
+ }
23
+ run(driver.plan.remove(target)); // Absent on a first setup; a failure here is expected and harmless.
24
+ const add = driver.plan.add(target, server);
25
+ const added = run(add);
26
+ if (!added.ok)
27
+ throw new Error(`${add.command} ${add.args.join(" ")} failed: ${added.output}`);
28
+ driver.afterAdd?.(target);
29
+ }
30
+ /**
31
+ * Removes the registration. The message tells an absent server from a failure: codex 0.162.1
32
+ * exits 0 for an absent server, Claude Code 2.1.302 exits 1, and both print "No MCP server named".
33
+ */
34
+ export function unregister(driver, target, run = exec) {
35
+ if (driver.edit)
36
+ return driver.edit.remove(target, run);
37
+ const remove = driver.plan.remove(target);
38
+ const result = run(remove);
39
+ if (/No MCP server named/.test(result.output))
40
+ return { state: "absent" };
41
+ return result.ok
42
+ ? { state: "removed" }
43
+ : {
44
+ state: "failed",
45
+ detail: result.output || `${remove.command} ${remove.args.join(" ")} failed`,
46
+ };
47
+ }
48
+ /** The `KEY=value` arguments of an agent CLI's environment flag. */
49
+ export const envArgs = (flag, env) => Object.entries(env).flatMap(([key, value]) => [flag, `${key}=${value}`]);
50
+ /** A registered server's store home: its SIDECAR_HOME, or the default. */
51
+ function homeOf(env) {
52
+ const home = env?.SIDECAR_HOME;
53
+ return typeof home === "string" ? home : DEFAULT_HOME;
54
+ }
55
+ /**
56
+ * Compares a registered server with the one setup would write now. The right Node, entry and home
57
+ * without this driver's `--driver` is its own state: the fix is the same setup re-run, but the cause
58
+ * is no `--driver`, or another adapter's, not a moved Node or clone.
59
+ */
60
+ export function judgeRegistration(found, expected) {
61
+ if (!found)
62
+ return { state: "missing" };
63
+ const { command } = found;
64
+ const same = (a, b) => a.length === b.length && a.every((p, i) => p === b[i]);
65
+ if (homeOf(found.env) !== homeOf(expected.env) ||
66
+ !same(command.slice(0, 2), expected.command.slice(0, 2)))
67
+ return { state: "stale", command };
68
+ return same(command, expected.command) ? { state: "current" } : { state: "no-driver", command };
69
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import { z } from "zod";
2
+ /** The envelope every stored line must carry. Kind-specific fields pass through unchecked. */
3
+ const Envelope = z.looseObject({
4
+ n: z.number().int(),
5
+ ts: z.string(),
6
+ kind: z.string(),
7
+ author: z.enum(["driver", "navigator", "sidecar"]),
8
+ });
9
+ export const isEvent = (value) => Envelope.safeParse(value).success;
@@ -0,0 +1,120 @@
1
+ // Review items. An item is one point the navigator raised: a flag, or an opinion's main point. Each
2
+ // tracks whether the navigator itself has accepted how the driver settled it. One reducer, applied by fold() event by event; tools, prompts and
3
+ // the dashboard all read its result. See docs/design.md → Review.
4
+ // `reviewBudget` in config.json limits the automatic reviews per item: past it, an unsettled item
5
+ // waits for the user. How many items one turn reviews is set by the prompt bound alone.
6
+ export const REVIEW_STATUSES = ["confirmed", "reopened", "held"];
7
+ /**
8
+ * How far a decision has got. A decision without a state is ready.
9
+ * - ready: the resolution exists — a fix in the workspace, a rejection, an explanation, a design agreed.
10
+ * - planned: accepted, but the change is not made yet. The navigator does not review it.
11
+ * - deferred: the point moves out of this case, for later work or for the user.
12
+ */
13
+ export const DECISION_STATES = ["ready", "planned", "deferred"];
14
+ export const decisionState = (e) => e.state === "planned" || e.state === "deferred" ? e.state : "ready";
15
+ // An event's payload fields are unchecked on read: a field that is no array reads as none.
16
+ const list = (value) => (Array.isArray(value) ? value : []);
17
+ export const flagsOf = (e) => list(e.flags);
18
+ export const reviewsOf = (e) => list(e.reviews);
19
+ export const reviewTargetsOf = (e) => list(e.reviewTargets);
20
+ /** Folds one event into the items. `askOf` finds an ask event by id. */
21
+ export function applyItemEvent(items, e, askOf) {
22
+ if (e.kind === "opinion") {
23
+ const askId = String(e.askId);
24
+ const ask = askOf(askId);
25
+ const flags = flagsOf(e);
26
+ // Each point is a flag, so the opinion's own verdict is an item only when it raised none. An
27
+ // opinion that carries its own severity always makes its verdict an item.
28
+ // A review turn answers no new question, so its own verdict raises nothing to review.
29
+ const legacy = e.severity !== undefined;
30
+ if (!ask?.review &&
31
+ (e.verdict === "disagree" || e.verdict === "needs-info") &&
32
+ (legacy || flags.length === 0)) {
33
+ items.set(askId, {
34
+ ref: askId,
35
+ kind: "opinion",
36
+ ...(legacy ? { severity: String(e.severity) } : {}),
37
+ point: String(e.body),
38
+ question: String(ask?.body ?? ""),
39
+ raisedN: e.n,
40
+ reviews: [],
41
+ reviewTurns: 0,
42
+ status: "open",
43
+ });
44
+ }
45
+ for (const flag of flags) {
46
+ items.set(flag.id, {
47
+ ref: flag.id,
48
+ kind: "flag",
49
+ severity: flag.severity,
50
+ point: flag.body,
51
+ raisedN: e.n,
52
+ reviews: [],
53
+ reviewTurns: 0,
54
+ status: "open",
55
+ });
56
+ }
57
+ // The runner stores the turn's targets with its opinion; each one used a review turn.
58
+ for (const target of reviewTargetsOf(e)) {
59
+ const item = items.get(target.ref);
60
+ if (item)
61
+ item.reviewTurns++;
62
+ }
63
+ for (const review of reviewsOf(e)) {
64
+ const item = items.get(review.ref);
65
+ if (!item)
66
+ continue;
67
+ // A review without a decision to match applies to nothing.
68
+ const applied = item.decision !== undefined && item.decision.n === review.decisionN;
69
+ item.reviews.push({ opinionN: e.n, applied });
70
+ if (!applied)
71
+ continue;
72
+ item.status =
73
+ review.status === "confirmed" && decisionState(item.decision) === "deferred"
74
+ ? "deferred"
75
+ : review.status;
76
+ }
77
+ return;
78
+ }
79
+ if (e.kind === "decision" && typeof e.ref === "string") {
80
+ const item = items.get(e.ref);
81
+ if (!item)
82
+ return;
83
+ item.decision = e;
84
+ item.status = decisionState(e) === "planned" ? "planned" : "addressed";
85
+ }
86
+ }
87
+ /** An item's status under a review budget: a decision past the budget is left for the user. */
88
+ export const itemStatus = (item, budget) => item.status === "addressed" && item.reviewTurns >= budget ? "exhausted" : item.status;
89
+ /** Items whose latest decision awaits the navigator's review, oldest decision first. */
90
+ export function awaitingReview(items, budget) {
91
+ return [...items.values()]
92
+ .filter((i) => itemStatus(i, budget) === "addressed")
93
+ .sort((a, b) => a.decision.n - b.decision.n);
94
+ }
95
+ /** Items not settled: everything but confirmed. */
96
+ export function unsettled(items) {
97
+ return [...items.values()].filter((i) => i.status !== "confirmed");
98
+ }
99
+ /**
100
+ * Keeps the reviews a reply may record: one per target ref, for targets the turn was shown. An
101
+ * invented or repeated ref is dropped; an omitted target stays awaiting review.
102
+ */
103
+ export function acceptReviews(reviews, targets) {
104
+ const byRef = new Map(targets.map((t) => [t.ref, t]));
105
+ const seen = new Set();
106
+ const kept = [];
107
+ for (const review of reviews) {
108
+ // The prompt shows refs in brackets, and a model may copy them (observed: codex-cli 0.162.1).
109
+ const ref = review.ref
110
+ .trim()
111
+ .replace(/^\[(.*)\]$/, "$1")
112
+ .trim();
113
+ const target = byRef.get(ref);
114
+ if (!target || seen.has(ref))
115
+ continue;
116
+ seen.add(ref);
117
+ kept.push({ ...target, status: review.status, body: review.body });
118
+ }
119
+ return kept;
120
+ }