@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.
- package/LICENSE +21 -0
- package/README.md +285 -2
- package/dist/bin/sidecar-dashboard.js +27 -0
- package/dist/bin/sidecar-mcp.js +35 -0
- package/dist/bin/sidecar.js +70 -0
- package/dist/src/adapters/claude-code.js +333 -0
- package/dist/src/adapters/claude-desktop.js +184 -0
- package/dist/src/adapters/codex.js +383 -0
- package/dist/src/adapters/index.js +38 -0
- package/dist/src/adapters/installed.js +25 -0
- package/dist/src/adapters/outcome.js +30 -0
- package/dist/src/adapters/registration.js +69 -0
- package/dist/src/adapters/types.js +1 -0
- package/dist/src/cases/events.js +9 -0
- package/dist/src/cases/items.js +120 -0
- package/dist/src/cases/lock.js +80 -0
- package/dist/src/cases/opinion.js +58 -0
- package/dist/src/cases/state.js +121 -0
- package/dist/src/cases/store.js +181 -0
- package/dist/src/cases/usage.js +36 -0
- package/dist/src/cli/deps.js +18 -0
- package/dist/src/cli/lines.js +11 -0
- package/dist/src/cli/list.js +44 -0
- package/dist/src/cli/setup.js +202 -0
- package/dist/src/cli/status.js +111 -0
- package/dist/src/cli/style.js +26 -0
- package/dist/src/cli/ui.js +170 -0
- package/dist/src/cli/uninstall.js +73 -0
- package/dist/src/config.js +108 -0
- package/dist/src/dashboard/cases.js +109 -0
- package/dist/src/dashboard/html.js +31 -0
- package/dist/src/dashboard/links.js +35 -0
- package/dist/src/dashboard/marks.js +16 -0
- package/dist/src/dashboard/pages.js +516 -0
- package/dist/src/dashboard/server.js +305 -0
- package/dist/src/dashboard/service.js +138 -0
- package/dist/src/dashboard/static/agents/NOTICE +32 -0
- package/dist/src/dashboard/static/agents/claude-code.svg +1 -0
- package/dist/src/dashboard/static/agents/claude-desktop.svg +1 -0
- package/dist/src/dashboard/static/agents/codex.svg +1 -0
- package/dist/src/dashboard/static/app.css +1121 -0
- package/dist/src/dashboard/static/app.js +256 -0
- package/dist/src/dashboard/static/times.js +44 -0
- package/dist/src/dashboard/view.js +25 -0
- package/dist/src/lib/agent-process.js +57 -0
- package/dist/src/lib/atomic-write.js +35 -0
- package/dist/src/lib/command.js +20 -0
- package/dist/src/lib/failpoint.js +14 -0
- package/dist/src/lib/git.js +14 -0
- package/dist/src/lib/json.js +2 -0
- package/dist/src/lib/paths.js +19 -0
- package/dist/src/lib/proc.js +80 -0
- package/dist/src/lib/version.js +43 -0
- package/dist/src/mcp/server.js +800 -0
- package/dist/src/mcp/stdio.js +31 -0
- package/dist/src/mcp/tools.js +180 -0
- package/dist/src/turns/dispatch.js +188 -0
- package/dist/src/turns/knobs.js +14 -0
- package/dist/src/turns/prompt.js +284 -0
- package/dist/src/turns/runner.js +283 -0
- package/package.json +44 -4
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { closeSync, existsSync, fstatSync, openSync, readdirSync, readFileSync, readSync, } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { SERVER_NAME } from "../config.js";
|
|
6
|
+
import { parseOpinion } from "../cases/opinion.js";
|
|
7
|
+
import { isObject } from "../lib/json.js";
|
|
8
|
+
import { count, failed, tail } from "./outcome.js";
|
|
9
|
+
import { envArgs, judgeRegistration } from "./registration.js";
|
|
10
|
+
// Launch policy: docs/design.md → Launch policy → claude-code. Every turn passes the full policy:
|
|
11
|
+
// flags apply to one invocation only.
|
|
12
|
+
const ID = "claude-code";
|
|
13
|
+
/** The CLI on PATH, for both roles. The runner tells a missing CLI by this name. */
|
|
14
|
+
const COMMAND = "claude";
|
|
15
|
+
/**
|
|
16
|
+
* Read-only shell commands with no argument that writes, executes, fetches or blocks. `tail` is
|
|
17
|
+
* left out: `tail -f` blocks until the turn's deadline. An operand still can block: `cat` of a
|
|
18
|
+
* FIFO in the workspace waits until the deadline (docs/design.md → Launch policy). Claude's
|
|
19
|
+
* built-in read-only set applies on top.
|
|
20
|
+
*/
|
|
21
|
+
const ALLOWLIST = ["cat", "head", "wc", "ls", "grep"];
|
|
22
|
+
/** Web lookups: they read pages and write nothing. The shell gets no network command. */
|
|
23
|
+
const WEB_TOOLS = ["WebSearch", "WebFetch"];
|
|
24
|
+
/** Under `--setting-sources ""` the user's default model is not loaded. */
|
|
25
|
+
const DEFAULT_MODEL = "opus";
|
|
26
|
+
/** An alias names no version: the CLI resolves it per turn, and an update can move it. */
|
|
27
|
+
const LABELS = {
|
|
28
|
+
models: {
|
|
29
|
+
opus: "Opus",
|
|
30
|
+
sonnet: "Sonnet",
|
|
31
|
+
haiku: "Haiku",
|
|
32
|
+
fable: "Fable",
|
|
33
|
+
"claude-opus-5-5": "Opus 5.5",
|
|
34
|
+
"claude-sonnet-5-5": "Sonnet 5.5",
|
|
35
|
+
"claude-haiku-5-5": "Haiku 5.5",
|
|
36
|
+
"claude-fable-5-1": "Fable 5.1",
|
|
37
|
+
},
|
|
38
|
+
efforts: { low: "Low", medium: "Medium", high: "High", xhigh: "Extra high", max: "Max" },
|
|
39
|
+
};
|
|
40
|
+
const MODELS = ["opus", "sonnet", "fable"].map((model) => ({
|
|
41
|
+
model,
|
|
42
|
+
efforts: Object.keys(LABELS.efforts),
|
|
43
|
+
}));
|
|
44
|
+
/**
|
|
45
|
+
* `--setting-sources ""` does not stop auto memory: without this, the navigator reads the user's
|
|
46
|
+
* MEMORY.md for the workspace, notes written for the driver (measured, 2.1.302).
|
|
47
|
+
*/
|
|
48
|
+
const ENV = { CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" };
|
|
49
|
+
/** With -p and no prompt argument, claude reads the prompt from stdin. */
|
|
50
|
+
function args(session, opts, schema) {
|
|
51
|
+
return [
|
|
52
|
+
"-p",
|
|
53
|
+
...session,
|
|
54
|
+
"--setting-sources",
|
|
55
|
+
"",
|
|
56
|
+
"--tools",
|
|
57
|
+
`Read,Grep,Glob,Bash,${WEB_TOOLS.join(",")}`,
|
|
58
|
+
"--allowedTools",
|
|
59
|
+
...ALLOWLIST.map((c) => `Bash(${c}:*)`),
|
|
60
|
+
...WEB_TOOLS,
|
|
61
|
+
"--permission-mode",
|
|
62
|
+
"dontAsk",
|
|
63
|
+
"--permission-prompts",
|
|
64
|
+
"none",
|
|
65
|
+
"--model",
|
|
66
|
+
opts.model ?? DEFAULT_MODEL,
|
|
67
|
+
...(opts.effort ? ["--effort", opts.effort] : []),
|
|
68
|
+
"--output-format",
|
|
69
|
+
"json",
|
|
70
|
+
"--json-schema",
|
|
71
|
+
JSON.stringify(schema),
|
|
72
|
+
];
|
|
73
|
+
}
|
|
74
|
+
function parse(stdout) {
|
|
75
|
+
let parsed;
|
|
76
|
+
try {
|
|
77
|
+
parsed = JSON.parse(stdout.trim());
|
|
78
|
+
}
|
|
79
|
+
catch { }
|
|
80
|
+
// Output that is not a result object, such as `null`, is treated as no result.
|
|
81
|
+
return isObject(parsed) ? parsed : null;
|
|
82
|
+
}
|
|
83
|
+
const navigator = {
|
|
84
|
+
command: COMMAND,
|
|
85
|
+
turnTimeoutMs: 15 * 60_000,
|
|
86
|
+
start(opts, schema, prompt) {
|
|
87
|
+
const sessionId = randomUUID();
|
|
88
|
+
return {
|
|
89
|
+
invocation: {
|
|
90
|
+
command: COMMAND,
|
|
91
|
+
args: args(["--session-id", sessionId], opts, schema),
|
|
92
|
+
env: ENV,
|
|
93
|
+
input: prompt,
|
|
94
|
+
},
|
|
95
|
+
sessionId,
|
|
96
|
+
};
|
|
97
|
+
},
|
|
98
|
+
resume(sessionId, opts, schema, prompt) {
|
|
99
|
+
return {
|
|
100
|
+
invocation: {
|
|
101
|
+
command: COMMAND,
|
|
102
|
+
args: args(["--resume", sessionId], opts, schema),
|
|
103
|
+
env: ENV,
|
|
104
|
+
input: prompt,
|
|
105
|
+
},
|
|
106
|
+
sessionId,
|
|
107
|
+
};
|
|
108
|
+
},
|
|
109
|
+
// The session id is chosen up front, never learned from output.
|
|
110
|
+
sessionIdFrom: () => null,
|
|
111
|
+
// The result's usage totals every step of this invocation (measured: it equals modelUsage, while
|
|
112
|
+
// usage.iterations holds the last step only). input_tokens leaves out cache reads and writes.
|
|
113
|
+
// The JSON result does not report tool calls. A missing counter makes the usage unknown, not zero.
|
|
114
|
+
// modelUsage names each model that ran.
|
|
115
|
+
measure(stdout) {
|
|
116
|
+
const result = parse(stdout);
|
|
117
|
+
const u = result?.usage;
|
|
118
|
+
const fields = u
|
|
119
|
+
? [
|
|
120
|
+
u.input_tokens,
|
|
121
|
+
u.cache_read_input_tokens,
|
|
122
|
+
u.cache_creation_input_tokens,
|
|
123
|
+
u.output_tokens,
|
|
124
|
+
u.output_tokens_details?.thinking_tokens,
|
|
125
|
+
].map(count)
|
|
126
|
+
: null;
|
|
127
|
+
// Thinking tokens are part of output_tokens.
|
|
128
|
+
const usage = fields && fields.every((f) => f !== null)
|
|
129
|
+
? {
|
|
130
|
+
input: fields[0] + fields[1] + fields[2],
|
|
131
|
+
cachedInput: fields[1],
|
|
132
|
+
cacheWrite: fields[2],
|
|
133
|
+
output: fields[3],
|
|
134
|
+
reasoning: fields[4],
|
|
135
|
+
}
|
|
136
|
+
: null;
|
|
137
|
+
const modelUsage = result?.modelUsage;
|
|
138
|
+
const models = modelUsage && typeof modelUsage === "object" && Object.keys(modelUsage).length > 0
|
|
139
|
+
? Object.keys(modelUsage)
|
|
140
|
+
: null;
|
|
141
|
+
return { usage, scope: "turn", toolCalls: null, models };
|
|
142
|
+
},
|
|
143
|
+
classify({ exitCode, stdout, stderr }) {
|
|
144
|
+
if (/No conversation found with session ID/.test(stderr)) {
|
|
145
|
+
return { kind: "failed", outcome: "session-missing", detail: tail(stderr) };
|
|
146
|
+
}
|
|
147
|
+
const result = parse(stdout);
|
|
148
|
+
if (!result) {
|
|
149
|
+
return exitCode === 0
|
|
150
|
+
? { kind: "failed", outcome: "malformed-reply", detail: tail(stdout) }
|
|
151
|
+
: failed(`exit ${exitCode}: `, stderr.trim() || stdout);
|
|
152
|
+
}
|
|
153
|
+
if (result.subtype === "error_max_structured_output_retries") {
|
|
154
|
+
return {
|
|
155
|
+
kind: "failed",
|
|
156
|
+
outcome: "malformed-reply",
|
|
157
|
+
detail: "the agent could not produce a schema-valid reply",
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
if (exitCode !== 0 || result.is_error || result.subtype !== "success") {
|
|
161
|
+
const status = result.api_error_status ? `HTTP ${result.api_error_status}: ` : "";
|
|
162
|
+
return failed(`exit ${exitCode}, ${result.subtype ?? "no subtype"}: ${status}`, result.result ?? stderr);
|
|
163
|
+
}
|
|
164
|
+
const opinion = parseOpinion(result.structured_output);
|
|
165
|
+
return opinion
|
|
166
|
+
? { kind: "opinion", opinion }
|
|
167
|
+
: {
|
|
168
|
+
kind: "failed",
|
|
169
|
+
outcome: "malformed-reply",
|
|
170
|
+
detail: tail(JSON.stringify(result.structured_output ?? null)),
|
|
171
|
+
};
|
|
172
|
+
},
|
|
173
|
+
models: () => MODELS,
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* Every Claude Code profile, each one config directory: the default (~/.claude.json, used when
|
|
177
|
+
* CLAUDE_CONFIG_DIR is unset), every ~/.claude-* directory holding a .claude.json, and the current
|
|
178
|
+
* one. A session only sees the servers in its own profile, so each profile is its own target.
|
|
179
|
+
*/
|
|
180
|
+
export function claudeProfiles(home = homedir(), current = process.env.CLAUDE_CONFIG_DIR) {
|
|
181
|
+
const profiles = [{ label: "claude-code — default (~/.claude.json)" }];
|
|
182
|
+
for (const name of readdirSync(home).sort()) {
|
|
183
|
+
const dir = join(home, name);
|
|
184
|
+
if (name.startsWith(".claude-") && existsSync(join(dir, ".claude.json")))
|
|
185
|
+
profiles.push({ label: `claude-code — ~/${name}`, configDir: dir });
|
|
186
|
+
}
|
|
187
|
+
if (current && !profiles.some((p) => p.configDir === current))
|
|
188
|
+
profiles.push({ label: `claude-code — ${current}`, configDir: current });
|
|
189
|
+
return profiles;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Claude keeps user-scope servers in `.claude.json`: in the home directory for the default profile,
|
|
193
|
+
* in CLAUDE_CONFIG_DIR otherwise. Read directly: `claude mcp get` prints text and starts the server.
|
|
194
|
+
*/
|
|
195
|
+
export function claudeRegistration(configDir, expected) {
|
|
196
|
+
const file = join(configDir ?? homedir(), ".claude.json");
|
|
197
|
+
if (!existsSync(file))
|
|
198
|
+
return { state: "missing" };
|
|
199
|
+
try {
|
|
200
|
+
const config = JSON.parse(readFileSync(file, "utf8"));
|
|
201
|
+
const server = config.mcpServers?.[SERVER_NAME];
|
|
202
|
+
return judgeRegistration(server
|
|
203
|
+
? { command: [server.command ?? "", ...(server.args ?? [])], env: server.env }
|
|
204
|
+
: undefined, expected);
|
|
205
|
+
}
|
|
206
|
+
catch (err) {
|
|
207
|
+
return { state: "unreadable", detail: `${file}: ${err.message}` };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/** A session id names one transcript file: anything but a UUID could name a path. */
|
|
211
|
+
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
212
|
+
/** How much of a transcript's end is searched for a call: the calls looked up are recent. */
|
|
213
|
+
const TRANSCRIPT_TAIL = 4 * 1024 * 1024;
|
|
214
|
+
/** Claude Code names each tool call in `_meta["claudecode/toolUseId"]` (measured 2.1.319). */
|
|
215
|
+
export function toolUseId(meta) {
|
|
216
|
+
const id = meta?.["claudecode/toolUseId"];
|
|
217
|
+
return typeof id === "string" && id ? id : undefined;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* The model and effort of the turn that made tool call `id`, from the session's transcript:
|
|
221
|
+
* `<CLAUDE_CONFIG_DIR or ~/.claude>/projects/<project>/<CLAUDE_CODE_SESSION_ID>.jsonl`, whose
|
|
222
|
+
* assistant entry holding the call records `message.model` and `effort` (measured 2.1.319). Claude
|
|
223
|
+
* Code writes that entry only after the call returns, so only a later call can look it up. The
|
|
224
|
+
* server inherits the session id at spawn: after /clear it names an older transcript, which holds
|
|
225
|
+
* no such entry. null when no entry is found.
|
|
226
|
+
*/
|
|
227
|
+
export function transcriptTurn(id, env = process.env) {
|
|
228
|
+
const session = env.CLAUDE_CODE_SESSION_ID;
|
|
229
|
+
if (!session || !SESSION_ID.test(session))
|
|
230
|
+
return null;
|
|
231
|
+
const projects = join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "projects");
|
|
232
|
+
let dirs;
|
|
233
|
+
try {
|
|
234
|
+
dirs = readdirSync(projects);
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
for (const dir of dirs) {
|
|
240
|
+
const file = join(projects, dir, `${session}.jsonl`);
|
|
241
|
+
if (!existsSync(file))
|
|
242
|
+
continue;
|
|
243
|
+
for (const line of readTail(file).split("\n")) {
|
|
244
|
+
if (!line.includes(id))
|
|
245
|
+
continue;
|
|
246
|
+
const turn = assistantTurn(line, id);
|
|
247
|
+
if (turn)
|
|
248
|
+
return turn;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
/** The last TRANSCRIPT_TAIL bytes of a file; a cut first line fails to parse and is skipped. */
|
|
254
|
+
function readTail(file) {
|
|
255
|
+
const fd = openSync(file, "r");
|
|
256
|
+
try {
|
|
257
|
+
const size = fstatSync(fd).size;
|
|
258
|
+
const length = Math.min(size, TRANSCRIPT_TAIL);
|
|
259
|
+
const buffer = Buffer.alloc(length);
|
|
260
|
+
// One read may return fewer bytes than asked: read on until the tail is in, or the file ends.
|
|
261
|
+
let read = 0;
|
|
262
|
+
while (read < length) {
|
|
263
|
+
const got = readSync(fd, buffer, read, length - read, size - length + read);
|
|
264
|
+
if (got === 0)
|
|
265
|
+
break;
|
|
266
|
+
read += got;
|
|
267
|
+
}
|
|
268
|
+
return buffer.toString("utf8", 0, read);
|
|
269
|
+
}
|
|
270
|
+
finally {
|
|
271
|
+
closeSync(fd);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function assistantTurn(line, id) {
|
|
275
|
+
let entry;
|
|
276
|
+
try {
|
|
277
|
+
entry = JSON.parse(line);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
const content = entry.message?.content;
|
|
283
|
+
const holds = entry.type === "assistant" &&
|
|
284
|
+
Array.isArray(content) &&
|
|
285
|
+
content.some((block) => block?.type === "tool_use" && block.id === id);
|
|
286
|
+
if (!holds)
|
|
287
|
+
return null;
|
|
288
|
+
const { model } = entry.message;
|
|
289
|
+
return {
|
|
290
|
+
...(typeof model === "string" && model ? { model } : {}),
|
|
291
|
+
...(typeof entry.effort === "string" && entry.effort ? { effort: entry.effort } : {}),
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
/** Always set or clear CLAUDE_CONFIG_DIR explicitly: setup may itself run inside another profile. */
|
|
295
|
+
const profile = (target) => ({ CLAUDE_CONFIG_DIR: target.configDir });
|
|
296
|
+
const driver = {
|
|
297
|
+
command: COMMAND,
|
|
298
|
+
// Claude Code waits longer than 300 s for a tool call (measured 2.1.300).
|
|
299
|
+
askBudgetMs: 240_000,
|
|
300
|
+
targets: () => claudeProfiles(),
|
|
301
|
+
plan: {
|
|
302
|
+
remove: (target) => ({
|
|
303
|
+
command: COMMAND,
|
|
304
|
+
args: ["mcp", "remove", SERVER_NAME, "-s", "user"],
|
|
305
|
+
env: profile(target),
|
|
306
|
+
}),
|
|
307
|
+
// -e takes several values, so it follows the name and ends at "--" (2.1.304).
|
|
308
|
+
add: (target, server) => ({
|
|
309
|
+
command: COMMAND,
|
|
310
|
+
args: [
|
|
311
|
+
"mcp",
|
|
312
|
+
"add",
|
|
313
|
+
"-s",
|
|
314
|
+
"user",
|
|
315
|
+
SERVER_NAME,
|
|
316
|
+
...envArgs("-e", server.env),
|
|
317
|
+
"--",
|
|
318
|
+
...server.command,
|
|
319
|
+
],
|
|
320
|
+
env: profile(target),
|
|
321
|
+
}),
|
|
322
|
+
},
|
|
323
|
+
read: (target, _run, expected) => claudeRegistration(target.configDir, expected),
|
|
324
|
+
tip: 'Allow "mcp__sidecar" in Claude\'s permissions.allow to skip per-call prompts',
|
|
325
|
+
callId: toolUseId,
|
|
326
|
+
turnOf: (id) => transcriptTurn(id),
|
|
327
|
+
};
|
|
328
|
+
export const claudeCode = {
|
|
329
|
+
id: ID,
|
|
330
|
+
labels: LABELS,
|
|
331
|
+
navigator,
|
|
332
|
+
driver,
|
|
333
|
+
};
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { SERVER_NAME } from "../config.js";
|
|
5
|
+
import { writeFileAtomic } from "../lib/atomic-write.js";
|
|
6
|
+
import { exec } from "../lib/command.js";
|
|
7
|
+
import { isObject } from "../lib/json.js";
|
|
8
|
+
import { isInstalled } from "./installed.js";
|
|
9
|
+
import { judgeRegistration } from "./registration.js";
|
|
10
|
+
// The Claude desktop app, on macOS only: a driver only. It has no CLI for its MCP servers, so setup edits
|
|
11
|
+
// its config file itself, guarded against the app's own writes. The measured facts:
|
|
12
|
+
// docs/design.md → Driver interface → MCP clients.
|
|
13
|
+
const ID = "claude-desktop";
|
|
14
|
+
/** The ids a chat reports for itself as the driver: API ids, since the app has no aliases. */
|
|
15
|
+
const LABELS = {
|
|
16
|
+
models: {
|
|
17
|
+
"claude-opus-5-5": "Opus 5.5",
|
|
18
|
+
"claude-sonnet-5-5": "Sonnet 5.5",
|
|
19
|
+
"claude-haiku-5-5": "Haiku 5.5",
|
|
20
|
+
"claude-fable-5-1": "Fable 5.1",
|
|
21
|
+
},
|
|
22
|
+
efforts: { low: "Low", medium: "Medium", high: "High", xhigh: "Extra high", max: "Max" },
|
|
23
|
+
};
|
|
24
|
+
/** The install on macOS (2.42304.2); none elsewhere. */
|
|
25
|
+
export function installOn(platform, home = homedir()) {
|
|
26
|
+
if (platform !== "darwin")
|
|
27
|
+
return undefined;
|
|
28
|
+
return {
|
|
29
|
+
bundles: ["/Applications/Claude.app", join(home, "Applications", "Claude.app")],
|
|
30
|
+
configDir: join(home, "Library", "Application Support", "Claude"),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
const INSTALL = installOn(process.platform);
|
|
34
|
+
const BUNDLE_ID = "com.anthropic.claudefordesktop";
|
|
35
|
+
/** The main executable inside the bundle, whatever the bundle is named. */
|
|
36
|
+
const EXECUTABLE = "Contents/MacOS/Claude";
|
|
37
|
+
/**
|
|
38
|
+
* The app's bundles: the usual places, and any other copy Spotlight knows by its bundle id, such
|
|
39
|
+
* as a renamed one. A failed `mdfind` (Spotlight off) leaves the usual places.
|
|
40
|
+
*/
|
|
41
|
+
export function findBundles(install, run) {
|
|
42
|
+
const found = run({
|
|
43
|
+
command: "mdfind",
|
|
44
|
+
args: [`kMDItemCFBundleIdentifier == '${BUNDLE_ID}'`],
|
|
45
|
+
});
|
|
46
|
+
const indexed = found.ok ? found.output.split("\n").filter((line) => line.endsWith(".app")) : [];
|
|
47
|
+
return [...new Set([...install.bundles, ...indexed])].filter((bundle) => isInstalled({ command: join(bundle, EXECUTABLE) }));
|
|
48
|
+
}
|
|
49
|
+
const CONFIG = "claude_desktop_config.json";
|
|
50
|
+
function snapshot(file) {
|
|
51
|
+
if (!existsSync(file))
|
|
52
|
+
return { exists: false };
|
|
53
|
+
return { exists: true, text: readFileSync(file, "utf8"), mode: statSync(file).mode & 0o777 };
|
|
54
|
+
}
|
|
55
|
+
const unchanged = (a, b) => a.exists === b.exists && (!a.exists || (b.exists && a.text === b.text));
|
|
56
|
+
/**
|
|
57
|
+
* The config and its MCP servers, or why sidecar may not edit it. Any other shape is refused, not
|
|
58
|
+
* replaced: assigning a key to an array is lost when it is written, and replacing a container
|
|
59
|
+
* would drop the user's data.
|
|
60
|
+
*/
|
|
61
|
+
function parse(text) {
|
|
62
|
+
let config;
|
|
63
|
+
try {
|
|
64
|
+
config = JSON.parse(text);
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
return { error: err.message };
|
|
68
|
+
}
|
|
69
|
+
if (!isObject(config))
|
|
70
|
+
return { error: "its root is not a JSON object" };
|
|
71
|
+
if (config.mcpServers === undefined)
|
|
72
|
+
return { config, servers: {} };
|
|
73
|
+
if (!isObject(config.mcpServers))
|
|
74
|
+
return { error: "its mcpServers is not a JSON object" };
|
|
75
|
+
return { config, servers: config.mcpServers };
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The app rewrites its config while it runs; an edit then may lose its write or ours. `ps -Ao
|
|
79
|
+
* comm=` prints each process's argv[0], or its short name in parentheses when it cannot read the
|
|
80
|
+
* arguments. A launch from Finder or `open` gives the bundle's executable path. Any process whose
|
|
81
|
+
* argv[0] ends in `Claude`, or `(Claude)`, counts: that also catches any bundle, a relative launch
|
|
82
|
+
* and a symlink named `Claude`. A symlink of another name passes unseen. The helpers (Claude
|
|
83
|
+
* Helper, disclaimer) have other names.
|
|
84
|
+
*/
|
|
85
|
+
function refuseWhileRunning(run) {
|
|
86
|
+
const ps = run({ command: "ps", args: ["-Ao", "comm="] });
|
|
87
|
+
if (!ps.ok)
|
|
88
|
+
throw new Error(`cannot tell whether the Claude desktop app runs: ${ps.output}`);
|
|
89
|
+
if (ps.output.split("\n").some((line) => /(^|\/)Claude$|^\(Claude\)$/.test(line.trim())))
|
|
90
|
+
throw new Error("the Claude desktop app is running; quit it, then try again");
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Replaces the file atomically, keeping its mode (0600 for a new file: it can hold credentials). A
|
|
94
|
+
* file that changed since `before` is left as it is. The check and the rename are two steps: a
|
|
95
|
+
* write between them is lost. Quitting the app first makes that unlikely.
|
|
96
|
+
*/
|
|
97
|
+
function replace(file, before, config) {
|
|
98
|
+
writeFileAtomic(file, JSON.stringify(config, null, 2) + "\n", before.exists ? before.mode : 0o600, () => {
|
|
99
|
+
if (!unchanged(before, snapshot(file)))
|
|
100
|
+
throw new Error(`${file} changed while sidecar edited it; quit the Claude desktop app and try again`);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
const configFile = (target) => join(target.configDir, CONFIG);
|
|
104
|
+
/** A config value as status shows it. String() throws on an object whose toString is no function. */
|
|
105
|
+
const text = (value) => (typeof value === "string" ? value : JSON.stringify(value));
|
|
106
|
+
/** Never throws: status reads every target, and one it cannot read is reported, not fatal. */
|
|
107
|
+
function read(target, expected) {
|
|
108
|
+
const file = configFile(target);
|
|
109
|
+
let before;
|
|
110
|
+
try {
|
|
111
|
+
before = snapshot(file);
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
return { state: "unreadable", detail: `${file}: ${err.message}` };
|
|
115
|
+
}
|
|
116
|
+
if (!before.exists)
|
|
117
|
+
return { state: "missing" };
|
|
118
|
+
const parsed = parse(before.text);
|
|
119
|
+
if ("error" in parsed)
|
|
120
|
+
return { state: "unreadable", detail: `${file}: ${parsed.error}` };
|
|
121
|
+
const server = parsed.servers[SERVER_NAME];
|
|
122
|
+
if (!isObject(server))
|
|
123
|
+
return { state: "missing" };
|
|
124
|
+
const args = Array.isArray(server.args) ? server.args.map(text) : [];
|
|
125
|
+
return judgeRegistration({ command: [text(server.command ?? ""), ...args], env: server.env }, expected);
|
|
126
|
+
}
|
|
127
|
+
function add(target, server, run) {
|
|
128
|
+
const file = configFile(target);
|
|
129
|
+
const before = snapshot(file);
|
|
130
|
+
const parsed = before.exists ? parse(before.text) : { config: {}, servers: {} };
|
|
131
|
+
if ("error" in parsed)
|
|
132
|
+
throw new Error(`${file}: ${parsed.error}; fix it, then try again`);
|
|
133
|
+
refuseWhileRunning(run);
|
|
134
|
+
const [command, ...args] = server.command;
|
|
135
|
+
const env = Object.keys(server.env).length > 0 ? { env: server.env } : {};
|
|
136
|
+
replace(file, before, {
|
|
137
|
+
...parsed.config,
|
|
138
|
+
mcpServers: { ...parsed.servers, [SERVER_NAME]: { command, args, ...env } },
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
function remove(target, run) {
|
|
142
|
+
const file = configFile(target);
|
|
143
|
+
try {
|
|
144
|
+
const before = snapshot(file);
|
|
145
|
+
if (!before.exists)
|
|
146
|
+
return { state: "absent" };
|
|
147
|
+
const parsed = parse(before.text);
|
|
148
|
+
if ("error" in parsed)
|
|
149
|
+
return { state: "failed", detail: `${file}: ${parsed.error}` };
|
|
150
|
+
// Nothing to remove needs no edit, so it needs no quit app either.
|
|
151
|
+
if (!(SERVER_NAME in parsed.servers))
|
|
152
|
+
return { state: "absent" };
|
|
153
|
+
refuseWhileRunning(run);
|
|
154
|
+
const { [SERVER_NAME]: _removed, ...servers } = parsed.servers;
|
|
155
|
+
replace(file, before, { ...parsed.config, mcpServers: servers });
|
|
156
|
+
return { state: "removed" };
|
|
157
|
+
}
|
|
158
|
+
catch (err) {
|
|
159
|
+
return { state: "failed", detail: err.message };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/** The driver for the app as installed; `run` runs mdfind. */
|
|
163
|
+
export function desktopDriver(install, run = exec) {
|
|
164
|
+
return {
|
|
165
|
+
// A label: installed() finds the app wherever it is.
|
|
166
|
+
command: join(install.bundles[0], EXECUTABLE),
|
|
167
|
+
installed: () => findBundles(install, run).length > 0,
|
|
168
|
+
// The relay that carries a chat's tool calls to this computer gives up after 60 s
|
|
169
|
+
// (measured 2.42304.0, macOS).
|
|
170
|
+
askBudgetMs: 45_000,
|
|
171
|
+
// The app starts its server at "/", which is no project.
|
|
172
|
+
workspace: "scratch",
|
|
173
|
+
targets: () => [{ label: "claude-desktop", configDir: install.configDir }],
|
|
174
|
+
edit: { add, remove },
|
|
175
|
+
read: (target, _run, expected) => read(target, expected),
|
|
176
|
+
tip: "Restart the Claude desktop app, then set sidecar's tools to Always allow (Customize → Connectors → sidecar)",
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/** No driver off macOS, so setup and status never look for the app there. */
|
|
180
|
+
export const claudeDesktop = {
|
|
181
|
+
id: ID,
|
|
182
|
+
labels: LABELS,
|
|
183
|
+
...(INSTALL ? { driver: desktopDriver(INSTALL) } : {}),
|
|
184
|
+
};
|