capy-mcp-server 0.0.0-stage → 0.1.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/dist/bin.js ADDED
@@ -0,0 +1,2431 @@
1
+ #!/usr/bin/env node
2
+
3
+ // ../core/src/config.ts
4
+ import { homedir } from "node:os";
5
+ import { join, posix, win32 } from "node:path";
6
+ var SHARED_KEY = "the Capy API key that capy-acp, capy-mcp-server and capy-cli share";
7
+ var flag = (value) => value === "1" || value === "true";
8
+ var desktopConfigDir = (env, home, platform = process.platform) => {
9
+ const { join: join3 } = platform === "win32" ? win32 : posix;
10
+ if (platform === "darwin") return join3(home, "Library", "Application Support", "Capy");
11
+ if (platform === "win32") return join3(env.APPDATA ?? join3(home, "AppData", "Roaming"), "Capy");
12
+ return join3(env.XDG_CONFIG_HOME ?? join3(home, ".config"), "Capy");
13
+ };
14
+ var readConfig = (env, product) => {
15
+ const home = homedir();
16
+ const waiting = Number(env.CAPY_ACP_WAITING_LIMIT_MS ?? 10 * 6e4);
17
+ return {
18
+ product,
19
+ apiUrl: (env.CAPY_API_URL ?? "https://api.capy.ai/api/v1").replace(/\/+$/, ""),
20
+ apiKeyFile: env.CAPY_API_KEY_FILE ?? join(home, ".config", "capy-acp", "api-key"),
21
+ pricingUrl: env.CAPY_ACP_PRICING_URL ?? "https://docs.capy.ai/models-and-pricing.md",
22
+ defaultModel: env.CAPY_ACP_MODEL ?? "anthropic/claude-opus-5-5",
23
+ defaultReasoning: env.CAPY_ACP_REASONING ?? "high",
24
+ workspaceMode: env.CAPY_ACP_WORKSPACE === "worktree" || env.CAPY_ACP_WORKSPACE === "cloud" ? env.CAPY_ACP_WORKSPACE : "linked",
25
+ allowWorktreeFallback: flag(env.CAPY_ACP_ALLOW_WORKTREE_FALLBACK),
26
+ waitingLimitMs: Number.isFinite(waiting) && waiting >= 0 ? waiting : 10 * 6e4,
27
+ forwardHostInstructions: flag(env.CAPY_ACP_FORWARD_HOST_INSTRUCTIONS),
28
+ deviceIdOverride: env.CAPY_DEVICE_ID,
29
+ capyDesktopConfigDir: env.CAPY_DESKTOP_CONFIG_DIR ?? desktopConfigDir(env, home),
30
+ capyHome: env.CAPY_HOME ?? join(home, ".capy"),
31
+ stateDir: env.CAPY_ACP_STATE_DIR ?? join(env.XDG_STATE_HOME ?? join(home, ".local", "state"), "capy-acp", "sessions"),
32
+ attachmentsDir: env.CAPY_ACP_ATTACHMENTS_DIR ?? join(env.XDG_CACHE_HOME ?? join(home, ".cache"), "capy-acp", "attachments")
33
+ };
34
+ };
35
+
36
+ // ../core/src/setup.ts
37
+ import { chmod, mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
38
+ import { dirname as dirname2 } from "node:path";
39
+
40
+ // ../core/src/machine.ts
41
+ import { spawn } from "node:child_process";
42
+ import { access, mkdir, rm, writeFile } from "node:fs/promises";
43
+ import { homedir as homedir2 } from "node:os";
44
+ import { dirname, posix as posix3, win32 as win323 } from "node:path";
45
+ import { createInterface } from "node:readline/promises";
46
+
47
+ // ../core/src/problems.ts
48
+ var ProblemError = class extends Error {
49
+ constructor(problem) {
50
+ super(`${problem.title}. ${problem.detail}`);
51
+ this.problem = problem;
52
+ }
53
+ problem;
54
+ };
55
+ var problemOf = (error) => error instanceof ProblemError ? error.problem : void 0;
56
+ var toText = (problem, indent = "") => [`${problem.title}. ${problem.detail}`, ...problem.steps.map((step2, i) => `${indent}${i + 1}. ${step2}`)].join("\n");
57
+ var RETRY = "Send your message again.";
58
+ var NEW_SESSION = "Start a new chat in that folder. A session keeps the folder that it opened with.";
59
+ var CHAT_ONLY = /* @__PURE__ */ new Set([RETRY, NEW_SESSION]);
60
+ var outsideChat = (problem) => ({
61
+ ...problem,
62
+ steps: problem.steps.filter((s) => !CHAT_ONLY.has(s)).map((s) => s.replace(/ Then send your message again\.$/, ""))
63
+ });
64
+ var NO_DEVICE_TITLE = "Start Capy on this computer";
65
+ var noDevice = (files, product) => ({
66
+ title: NO_DEVICE_TITLE,
67
+ detail: `Capy threads run on this computer, and ${product.name} found no Capy device here.`,
68
+ steps: [
69
+ `Run \`${product.setup}\` in a terminal in this folder: it sets this computer up as a Capy device with \`capy dock\` and links the folder. Or open the Capy desktop app and sign in.`,
70
+ RETRY,
71
+ `${product.name} looked in ${files.map((file) => `${file.path} (${file.found === "missing" ? "missing" : "no device in it"})`).join(" and ")}. Capy desktop 0.10.0 writes device-ids.json when it starts, and older versions may not, so update the desktop app if you use it. Or set \`CAPY_DEVICE_ID\` to this computer's device id.`
72
+ ]
73
+ });
74
+ var unreadableDeviceFile = (file, detail, product) => ({
75
+ title: "Check the Capy desktop app",
76
+ detail: `${product.name} could not read the device file ${file} (${detail}).`,
77
+ steps: ["Restart the Capy desktop app, or set `CAPY_DEVICE_ID` to the id of this computer's Capy device.", RETRY]
78
+ });
79
+ var manyOrganizations = (count, product) => ({
80
+ title: "Choose a Capy organization",
81
+ detail: `This computer is paired with ${count} Capy organizations, so ${product.name} cannot tell which device to use.`,
82
+ steps: [`Set \`CAPY_DEVICE_ID\` in ${product.env} to the device id of the organization that you want.`, RETRY]
83
+ });
84
+ var isT3Scratch = (folder) => {
85
+ const parts = folder.split(/[\\/]+/);
86
+ return parts.some((part, i) => part === ".t3" && parts[i + 1] === "scratch");
87
+ };
88
+ var notGit = (folder) => isT3Scratch(folder) ? {
89
+ title: "Open a project to use Capy",
90
+ detail: "T3 Code started this chat without a project. Capy threads run on a GitHub repository from one of your Capy projects.",
91
+ steps: ["In T3 Code, add a project for a clone of that repository.", "Start a new chat in that project."]
92
+ } : {
93
+ title: "Open a repository to use Capy",
94
+ detail: `${folder} is not in a git repository. Capy threads run on a GitHub repository from one of your Capy projects.`,
95
+ steps: ["Open a clone of that repository in your editor.", NEW_SESSION]
96
+ };
97
+ var noGitHubRemote = (gitRoot) => ({
98
+ title: "Add the GitHub remote",
99
+ detail: `${gitRoot} has no git remote that names a GitHub repository, so its Capy project cannot be found.`,
100
+ steps: ["Add the remote, for example `git remote add origin git@github.com:owner/repo.git`.", RETRY]
101
+ });
102
+ var notInProject = (repos) => ({
103
+ title: `Add ${repos[0]} to a Capy project`,
104
+ detail: `No Capy project includes ${repos.join(" or ")}.`,
105
+ steps: ["Open https://capy.ai/settings/projects and add the repository to a project.", RETRY]
106
+ });
107
+ var linkSteps = (input) => {
108
+ const desktop = `Open \`capy://app/settings/projects/${input.projectId}\` to show "${input.projectName}" in the Capy desktop app. Set it up on this computer and choose ${input.root}.`;
109
+ const dock = [
110
+ "Stop `capy dock`. Caution: this also stops the Capy threads that run on this computer.",
111
+ `Run \`capy dock dirs add ${input.root}\`, then start \`capy dock\` again.`
112
+ ];
113
+ if (input.device === "desktop") return [desktop];
114
+ if (input.device === "dock") return dock;
115
+ return [`With the desktop app: ${desktop}`, `With \`capy dock\`: ${dock.join(" ")}`];
116
+ };
117
+ var sameRepoForTools = (product, root, repo, sameRepoRoot, link) => {
118
+ const mcp = product.kind === "mcp";
119
+ return {
120
+ title: `Use the folder that Capy links for ${repo}`,
121
+ detail: `On this computer, Capy links ${repo} at ${sameRepoRoot}, not at ${root}.`,
122
+ steps: [
123
+ mcp ? `Call again with folder "${sameRepoRoot}".` : `Run the command again with \`--folder ${sameRepoRoot}\`.`,
124
+ `Or link ${root} instead. ${link.join(" ")}`,
125
+ `Or use ${mcp ? 'where "worktree"' : "`--where worktree`"}. Capy then works in a new worktree of ${sameRepoRoot}, and ${root} does not change.`
126
+ ]
127
+ };
128
+ };
129
+ var notLinked = (input) => input.sameRepoRoot !== void 0 && input.product !== void 0 && input.product.kind !== "acp" ? sameRepoForTools(input.product, input.root, input.repo, input.sameRepoRoot, linkSteps(input)) : input.sameRepoRoot === void 0 ? {
130
+ title: "Link this folder to Capy",
131
+ detail: `Capy runs threads only in folders that are linked to this computer, and ${input.root} is not linked.`,
132
+ steps: [...linkSteps(input), RETRY]
133
+ } : {
134
+ title: `Use the folder that Capy links for ${input.repo}`,
135
+ detail: `On this computer, Capy links ${input.repo} at ${input.sameRepoRoot}, not at ${input.root}.`,
136
+ steps: [
137
+ `Open ${input.sameRepoRoot} in your editor, and start a new chat there.`,
138
+ `Or link ${input.root} instead. ${linkSteps(input).join(" ")} Then send your message again.`,
139
+ `Or set \`CAPY_ACP_ALLOW_WORKTREE_FALLBACK=1\` in the agent's environment. Capy then works in a new worktree of ${input.sameRepoRoot}, and its edits do not appear in ${input.root}.`
140
+ ]
141
+ };
142
+
143
+ // ../core/src/workspace.ts
144
+ import { execFile } from "node:child_process";
145
+ import { readFile, realpath } from "node:fs/promises";
146
+ import { join as join2, posix as posix2, relative, resolve, win32 as win322 } from "node:path";
147
+ import { promisify } from "node:util";
148
+ var run = promisify(execFile);
149
+ var samePath = (a, b, platform = process.platform) => {
150
+ const norm = (p) => {
151
+ const resolved = (platform === "win32" ? win322 : posix2).resolve(p);
152
+ return platform === "win32" || platform === "darwin" ? resolved.toLowerCase() : resolved;
153
+ };
154
+ return norm(a) === norm(b);
155
+ };
156
+ var parseRemote = (url) => {
157
+ const trimmed = url.trim();
158
+ const path = /^[a-z][a-z0-9+.-]*:\/\/[^/]*\/(.*)$/i.exec(trimmed)?.[1] ?? /^[^/:\s]+:(?!\/\/)(.*)$/.exec(trimmed)?.[1];
159
+ const parts = path?.replace(/\/+$/, "").replace(/\.git$/i, "").split("/").filter((part) => part !== "");
160
+ return parts !== void 0 && parts.length >= 2 ? parts.slice(-2).join("/").toLowerCase() : void 0;
161
+ };
162
+ var resolveWorkspace = (input) => {
163
+ const unresolved = (problem) => ({ _tag: "Unresolved", problem });
164
+ if (input.gitRoot === void 0) return unresolved(notGit(input.cwd));
165
+ const gitRoot = input.gitRoot;
166
+ const here = input.linked.find((folder) => samePath(folder.realRoot ?? folder.root, gitRoot) || samePath(folder.root, gitRoot));
167
+ const candidates = [.../* @__PURE__ */ new Set([...input.repos, ...(here?.repos ?? []).map((r) => r.toLowerCase())])];
168
+ const matches = (repo2) => input.projects.find((p) => p.repos.some((r) => r.repoFullName.toLowerCase() === repo2));
169
+ const repo = candidates.find((candidate) => matches(candidate) !== void 0);
170
+ const project = repo === void 0 ? void 0 : matches(repo);
171
+ if (repo === void 0 || project === void 0) {
172
+ return unresolved(candidates.length === 0 ? noGitHubRemote(gitRoot) : notInProject(candidates));
173
+ }
174
+ const sameRepo = input.linked.find((folder) => folder !== here && folder.repos.some((r) => r.toLowerCase() === repo));
175
+ const notLinkedHere = notLinked({
176
+ root: gitRoot,
177
+ repo,
178
+ projectId: project.id,
179
+ projectName: project.name,
180
+ device: input.device,
181
+ sameRepoRoot: sameRepo?.root,
182
+ product: input.product
183
+ });
184
+ const base = { projectId: project.id, projectName: project.name, repo, notLinked: notLinkedHere };
185
+ if (here !== void 0) {
186
+ return input.mode === "linked" ? { _tag: "Resolved", value: { ...base, workspace: { kind: "linked", root: here.root }, note: void 0 } } : {
187
+ _tag: "Resolved",
188
+ value: {
189
+ ...base,
190
+ workspace: { kind: "worktree" },
191
+ note: "Capy is working in its own git worktree (in Capy's worktree folder, ~/.capy/worktrees by default), not in this folder (CAPY_ACP_WORKSPACE=worktree)."
192
+ }
193
+ };
194
+ }
195
+ if (sameRepo !== void 0 && input.allowWorktreeFallback) {
196
+ return {
197
+ _tag: "Resolved",
198
+ value: {
199
+ ...base,
200
+ workspace: { kind: "worktree" },
201
+ note: `${input.gitRoot} is not linked to this Capy device, so Capy is working in a new worktree of ${sameRepo.root} in Capy's worktree folder (~/.capy/worktrees by default). Its edits will not appear in this folder.`
202
+ }
203
+ };
204
+ }
205
+ if (input.mode === "worktree") {
206
+ return unresolved(notLinkedHere);
207
+ }
208
+ const opened = input.openedRoot ?? gitRoot;
209
+ const root = (input.platform ?? process.platform) === "win32" ? win322.normalize(opened) : opened;
210
+ return { _tag: "Resolved", value: { ...base, workspace: { kind: "linked", root }, note: void 0 } };
211
+ };
212
+ var readJson = async (path) => JSON.parse(await readFile(path, "utf8"));
213
+ var readDevice = async (config2) => {
214
+ if (config2.deviceIdOverride) return { id: config2.deviceIdOverride, kind: void 0 };
215
+ const desktop = join2(config2.capyDesktopConfigDir, "device-ids.json");
216
+ const checked = [];
217
+ let ids = [];
218
+ try {
219
+ const data = await readJson(desktop);
220
+ ids = Object.values(data.orgs ?? {}).filter((id) => typeof id === "string" && id !== "");
221
+ checked.push({ path: desktop, found: "no device" });
222
+ } catch (error) {
223
+ if (error.code !== "ENOENT") {
224
+ throw new ProblemError(unreadableDeviceFile(desktop, error instanceof Error ? error.message : String(error), config2.product));
225
+ }
226
+ checked.push({ path: desktop, found: "missing" });
227
+ }
228
+ if (ids.length === 1 && ids[0]) return { id: ids[0], kind: "desktop" };
229
+ if (ids.length > 1) throw new ProblemError(manyOrganizations(ids.length, config2.product));
230
+ const dock = join2(config2.capyHome, "dock", "status.json");
231
+ const docked = await readJson(dock).then(
232
+ (data) => ({ found: "no device", id: data.deviceId }),
233
+ () => ({ found: "missing", id: void 0 })
234
+ );
235
+ if (typeof docked.id === "string" && docked.id !== "") return { id: docked.id, kind: "dock" };
236
+ checked.push({ path: dock, found: docked.found });
237
+ throw new ProblemError(noDevice(checked, config2.product));
238
+ };
239
+ var readLinkedFolders = async (config2) => {
240
+ try {
241
+ const data = await readJson(join2(config2.capyHome, "device", "workspaces.json"));
242
+ const folders = (data.folders ?? []).flatMap(
243
+ (folder) => typeof folder.root === "string" ? [{ root: folder.root, repos: Array.isArray(folder.repos) ? folder.repos.filter((r) => typeof r === "string") : [] }] : []
244
+ );
245
+ return Promise.all(
246
+ folders.map(async (folder) => ({ ...folder, realRoot: await realpath(folder.root).catch(() => folder.root) }))
247
+ );
248
+ } catch {
249
+ return [];
250
+ }
251
+ };
252
+ var readGit = async (cwd) => {
253
+ const git = async (...args) => {
254
+ try {
255
+ return (await run("git", ["-C", cwd, ...args], { timeout: 5e3 })).stdout.trim();
256
+ } catch {
257
+ return void 0;
258
+ }
259
+ };
260
+ const gitRoot = await git("rev-parse", "--show-toplevel");
261
+ const remotes = gitRoot === void 0 ? [] : (await git("remote", "-v") ?? "").split("\n").flatMap((line) => {
262
+ const match = /^(\S+)\s+(\S+)\s+\(fetch\)$/.exec(line.trim());
263
+ return match ? [{ name: match[1], url: match[2] }] : [];
264
+ });
265
+ const ordered = [...remotes.filter((r) => r.name === "origin"), ...remotes.filter((r) => r.name !== "origin")];
266
+ const repos = [...new Set(ordered.flatMap((remote) => parseRemote(remote.url) ?? []))];
267
+ const openedRoot = gitRoot === void 0 ? void 0 : await realpath(cwd).then((real) => resolve(cwd, relative(real, gitRoot)), () => gitRoot);
268
+ return { gitRoot, openedRoot, repos };
269
+ };
270
+
271
+ // ../core/src/machine.ts
272
+ var dockOs = (platform) => platform === "linux" || platform === "darwin" || platform === "win32" ? platform : void 0;
273
+ var pathFor = (os) => os === "win32" ? win323 : posix3;
274
+ var dockBinary = (os, capyHome) => os === "win32" ? win323.join(capyHome, "dock-install", "current", "bin", "capy.exe") : posix3.join(capyHome, "bin", "capy");
275
+ var INSTALL_SH = "curl -fsSL https://downloads.capy.ai/stable/dock/install.sh | sh";
276
+ var INSTALL_PS1 = "irm https://downloads.capy.ai/stable/dock/install.ps1 | iex";
277
+ var installCommand = (os) => os === "win32" ? { command: "powershell.exe", args: ["-NoProfile", "-Command", INSTALL_PS1], display: INSTALL_PS1 } : { command: "sh", args: ["-c", INSTALL_SH], display: INSTALL_SH };
278
+ var psQuote = (value) => `'${value.replace(/'/g, "''")}'`;
279
+ var quoteArg = (os, arg) => os === "win32" ? /^[\w:./\\-]+$/.test(arg) ? arg : psQuote(arg) : /^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, "'\\''")}'`;
280
+ var command = (os, program, args, mayFail = false) => {
281
+ const shown = quoteArg(os, program);
282
+ return {
283
+ command: program,
284
+ args,
285
+ display: [os === "win32" && shown !== program ? `& ${shown}` : shown, ...args.map((arg) => quoteArg(os, arg))].join(" "),
286
+ ...mayFail ? { mayFail } : {}
287
+ };
288
+ };
289
+ var dockCommand = (os, binary, args) => command(os, binary, ["dock", ...args]);
290
+ var systemdEscape = (value) => value.replace(/%/g, "%%");
291
+ var systemdQuote = (value) => `"${systemdEscape(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
292
+ var systemdUnit = (input) => [
293
+ "[Unit]",
294
+ "Description=Capy dock: runs Capy threads on this computer",
295
+ "Documentation=https://docs.capy.ai/dock",
296
+ "",
297
+ "[Service]",
298
+ `ExecStart=${systemdQuote(input.binary).replace(/\$/g, "$$$$")} dock`,
299
+ "WorkingDirectory=%h",
300
+ // A user service starts with a short PATH; threads need the git, gh and tools that the person uses.
301
+ ...input.path ? [`Environment=${systemdQuote(`PATH=${input.path}`)}`] : [],
302
+ "Restart=on-failure",
303
+ "RestartSec=10",
304
+ "",
305
+ "[Install]",
306
+ "WantedBy=default.target",
307
+ ""
308
+ ].join("\n");
309
+ var xml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
310
+ var LAUNCHD_LABEL = "capy-acp.dock";
311
+ var launchAgent = (input) => [
312
+ `<?xml version="1.0" encoding="UTF-8"?>`,
313
+ `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
314
+ `<plist version="1.0">`,
315
+ `<dict>`,
316
+ ` <key>Label</key>`,
317
+ ` <string>${LAUNCHD_LABEL}</string>`,
318
+ ` <key>ProgramArguments</key>`,
319
+ ` <array>`,
320
+ ` <string>${xml(input.binary)}</string>`,
321
+ ` <string>dock</string>`,
322
+ ` </array>`,
323
+ // launchd starts agents with PATH=/usr/bin:/bin:/usr/sbin:/sbin, which misses Homebrew's git and gh.
324
+ ...input.path ? [` <key>EnvironmentVariables</key>`, ` <dict>`, ` <key>PATH</key>`, ` <string>${xml(input.path)}</string>`, ` </dict>`] : [],
325
+ ` <key>RunAtLoad</key>`,
326
+ ` <true/>`,
327
+ ` <key>KeepAlive</key>`,
328
+ ` <dict>`,
329
+ ` <key>SuccessfulExit</key>`,
330
+ ` <false/>`,
331
+ ` </dict>`,
332
+ ` <key>ThrottleInterval</key>`,
333
+ ` <integer>10</integer>`,
334
+ ` <key>StandardOutPath</key>`,
335
+ ` <string>${xml(input.logFile)}</string>`,
336
+ ` <key>StandardErrorPath</key>`,
337
+ ` <string>${xml(input.logFile)}</string>`,
338
+ `</dict>`,
339
+ `</plist>`,
340
+ ``
341
+ ].join("\n");
342
+ var TASK_NAME = "capy-acp dock";
343
+ var scheduledTask = (input) => [
344
+ `<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">`,
345
+ ` <RegistrationInfo>`,
346
+ ` <Description>Runs capy dock, which runs Capy threads on this computer. https://docs.capy.ai/dock</Description>`,
347
+ ` </RegistrationInfo>`,
348
+ ` <Triggers>`,
349
+ ` <LogonTrigger>`,
350
+ ` <Enabled>true</Enabled>`,
351
+ ` <UserId>${xml(input.userId)}</UserId>`,
352
+ ` </LogonTrigger>`,
353
+ ` </Triggers>`,
354
+ ` <Principals>`,
355
+ ` <Principal id="Author">`,
356
+ ` <UserId>${xml(input.userId)}</UserId>`,
357
+ ` <LogonType>InteractiveToken</LogonType>`,
358
+ ` <RunLevel>LeastPrivilege</RunLevel>`,
359
+ ` </Principal>`,
360
+ ` </Principals>`,
361
+ ` <Settings>`,
362
+ ` <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>`,
363
+ ` <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>`,
364
+ ` <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>`,
365
+ ` <StartWhenAvailable>true</StartWhenAvailable>`,
366
+ ` <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>`,
367
+ ` <RestartOnFailure>`,
368
+ ` <Interval>PT1M</Interval>`,
369
+ ` <Count>999</Count>`,
370
+ ` </RestartOnFailure>`,
371
+ ` </Settings>`,
372
+ ` <Actions Context="Author">`,
373
+ ` <Exec>`,
374
+ ` <Command>${xml(input.binary)}</Command>`,
375
+ ` <Arguments>dock</Arguments>`,
376
+ ` <WorkingDirectory>${xml(input.workingDirectory)}</WorkingDirectory>`,
377
+ ` </Exec>`,
378
+ ` </Actions>`,
379
+ `</Task>`,
380
+ ``
381
+ ].join("\n");
382
+ var servicePlan = (input) => {
383
+ const { join: join3 } = pathFor(input.os);
384
+ const path = input.env.PATH;
385
+ if (input.os === "linux") {
386
+ const file2 = join3(input.env.XDG_CONFIG_HOME ?? join3(input.home, ".config"), "systemd", "user", "capy-dock.service");
387
+ return {
388
+ name: "a systemd user service",
389
+ file: file2,
390
+ content: systemdUnit({ binary: input.binary, path }),
391
+ commands: [
392
+ command("linux", "systemctl", ["--user", "daemon-reload"]),
393
+ command("linux", "systemctl", ["--user", "enable", "--now", "capy-dock.service"])
394
+ ],
395
+ notes: [
396
+ "On a server, also run `loginctl enable-linger` (it may need sudo), so the dock keeps running after you log out.",
397
+ "Logs: `journalctl --user -u capy-dock`."
398
+ ]
399
+ };
400
+ }
401
+ if (input.os === "darwin") {
402
+ const file2 = join3(input.home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
403
+ const logFile = join3(input.home, "Library", "Logs", "capy-dock.log");
404
+ const domain = `gui/${input.uid ?? 501}`;
405
+ return {
406
+ name: "a launchd LaunchAgent",
407
+ file: file2,
408
+ content: launchAgent({ binary: input.binary, path, logFile }),
409
+ commands: [
410
+ command("darwin", "launchctl", ["bootout", `${domain}/${LAUNCHD_LABEL}`], true),
411
+ command("darwin", "launchctl", ["bootstrap", domain, file2])
412
+ ],
413
+ notes: [`Logs: ${logFile}.`]
414
+ };
415
+ }
416
+ const file = win323.join(input.configDir, "capy-dock-task.xml");
417
+ const user = input.env.USERNAME ?? "user";
418
+ const userId = input.env.USERDOMAIN ? `${input.env.USERDOMAIN}\\${user}` : user;
419
+ const script = `Register-ScheduledTask -TaskName ${psQuote(TASK_NAME)} -Xml (Get-Content -Raw -Encoding UTF8 -LiteralPath ${psQuote(file)}) -Force | Out-Null; Start-ScheduledTask -TaskName ${psQuote(TASK_NAME)}`;
420
+ return {
421
+ name: "a Scheduled Task that starts when you log on",
422
+ file,
423
+ content: scheduledTask({ binary: input.binary, userId, workingDirectory: input.home }),
424
+ commands: [{ command: "powershell.exe", args: ["-NoProfile", "-NonInteractive", "-Command", script], display: script }],
425
+ notes: ["The dock runs in a console window. Closing that window stops the dock until you log on again."]
426
+ };
427
+ };
428
+ var DOCS = "https://docs.capy.ai/dock";
429
+ var DEVICES = "https://capy.ai/settings/devices";
430
+ var PAIRING_LIMIT_MS = 15 * 6e4;
431
+ var POLL_MS = 1e3;
432
+ var findDevice = async (config2) => {
433
+ try {
434
+ const device = await readDevice(config2);
435
+ return { kind: "device", id: device.id, from: device.kind ?? "setting" };
436
+ } catch (error) {
437
+ const problem = problemOf(error);
438
+ if (problem !== void 0 && problem.title !== NO_DEVICE_TITLE) return { kind: "desktop", text: toText(problem, " ") };
439
+ if (problem === void 0) throw error;
440
+ return { kind: "none" };
441
+ }
442
+ };
443
+ var pairedDock = async (config2) => {
444
+ const found = await findDevice(config2).catch(() => ({ kind: "none" }));
445
+ return found.kind === "device" ? found.id : void 0;
446
+ };
447
+ var manualSteps = (os, binary, root) => [
448
+ `To set it up yourself (${DOCS}):`,
449
+ ` 1. Install Capy's dock as the user that should run threads: ${installCommand(os).display}`,
450
+ ` 2. Run \`${dockCommand(os, binary, []).display}\` in a terminal, approve the pairing on capy.ai, then choose Yes when capy dock asks to pair.`,
451
+ root === void 0 ? ` 3. Stop it, and link your clones with \`${dockCommand(os, binary, ["dirs", "add", "<folder>"]).display}\`.` : ` 3. Stop it, run \`${dockCommand(os, binary, ["dirs", "add", root]).display}\`, then start \`capy dock\` again and keep it running.`
452
+ ].join("\n") + "\n";
453
+ var stopDock = async (io, dock) => {
454
+ const exits = (ms) => Promise.race([dock.exited.then(() => true), io.sleep(ms).then(() => false)]);
455
+ dock.stop();
456
+ if (await exits(1e4)) return true;
457
+ dock.stop(true);
458
+ return exits(5e3);
459
+ };
460
+ var waitForPairing = async (config2, io, dock) => {
461
+ let exited = false;
462
+ void dock.exited.then(() => exited = true);
463
+ for (let waited = 0; waited < PAIRING_LIMIT_MS; waited += POLL_MS) {
464
+ const id = await pairedDock(config2);
465
+ if (id !== void 0) return { kind: "paired", id };
466
+ if (exited) return { kind: "exited" };
467
+ await io.sleep(POLL_MS);
468
+ }
469
+ return { kind: "timeout" };
470
+ };
471
+ var runAll = async (io, commands, write2) => {
472
+ for (const step2 of commands) {
473
+ const result = await io.run(step2);
474
+ if (result.code === 0 || step2.mayFail) continue;
475
+ write2(`\`${step2.display}\` failed${result.code === void 0 ? "" : ` (exit code ${result.code})`}.
476
+ ${result.output.trim()}
477
+ `);
478
+ return false;
479
+ }
480
+ return true;
481
+ };
482
+ var offerService = async (config2, io, write2, os, binary) => {
483
+ const plan = servicePlan({ os, home: io.home, binary, env: io.env, uid: io.uid, configDir: dirname(config2.apiKeyFile) });
484
+ write2(
485
+ `
486
+ The dock must keep running for Capy threads to run here. ${config2.product.name} can keep it running with ${plan.name}.
487
+ It writes ${plan.file}:
488
+
489
+ ${plan.content}
490
+ Then it runs:
491
+ ${plan.commands.map((step2) => ` ${step2.display}`).join("\n")}
492
+ `
493
+ );
494
+ if (!await io.confirm(`Install and start ${plan.name}?`)) {
495
+ write2(
496
+ `No service was installed. The dock is offline until you start it: run \`${dockCommand(os, binary, []).display}\` and keep it running, for example in tmux or with a service manager.
497
+ `
498
+ );
499
+ return "declined";
500
+ }
501
+ try {
502
+ await io.writeFile(plan.file, plan.content);
503
+ } catch (error) {
504
+ write2(`${config2.product.name} could not write ${plan.file} (${error instanceof Error ? error.message : String(error)}).
505
+ `);
506
+ return "failed";
507
+ }
508
+ if (!await runAll(io, plan.commands, write2)) {
509
+ if (os === "darwin") {
510
+ const removed = await io.removeFile(plan.file).then(() => true, () => false);
511
+ write2(
512
+ removed ? `${config2.product.name} removed ${plan.file} again, so the dock does not start at your next login. Fix the error above and run \`${config2.product.setup}\` again, or run \`${dockCommand(os, binary, []).display}\` yourself.
513
+ ` : `${plan.file} stays, and launchd starts the dock from it at your next login. Delete it if you do not want that: \`rm ${quoteArg(os, plan.file)}\`.
514
+ `
515
+ );
516
+ return "failed";
517
+ }
518
+ write2(`The service file is at ${plan.file}. Fix the error above and run the commands again, or run \`${dockCommand(os, binary, []).display}\` yourself.
519
+ `);
520
+ return "failed";
521
+ }
522
+ write2(`Started ${plan.name}.
523
+ ${plan.notes.join("\n")}
524
+ `);
525
+ return "installed";
526
+ };
527
+ var linkFolder = async (name, io, write2, os, binary, root) => {
528
+ if (root === void 0) {
529
+ write2(`${io.folder} is not in a git repository, so ${name} linked no folder. Later, stop the dock and run \`${dockCommand(os, binary, ["dirs", "add", "<folder>"]).display}\` for each clone.
530
+ `);
531
+ return false;
532
+ }
533
+ const step2 = dockCommand(os, binary, ["dirs", "add", root]);
534
+ write2(`Linking ${root}, so Capy threads can work on this repository: ${step2.display}
535
+ `);
536
+ const result = await io.run(step2);
537
+ if (result.code === 0) return true;
538
+ write2(`\`${step2.display}\` failed${result.code === void 0 ? "" : ` (exit code ${result.code})`}.
539
+ ${result.output.trim()}
540
+ Run it again while the dock is stopped.
541
+ `);
542
+ return false;
543
+ };
544
+ var setupMachine = async (config2, io, write2) => {
545
+ const { name, setup } = config2.product;
546
+ const found = await findDevice(config2);
547
+ if (found.kind === "device" && found.from !== "dock") {
548
+ write2(
549
+ found.from === "desktop" ? `Capy device on this computer: ${found.id}, from the Capy desktop app. Keep the app running while Capy threads run here.
550
+ ` : `CAPY_DEVICE_ID names the Capy device ${found.id}, so ${name} sets up no device on this computer.
551
+ `
552
+ );
553
+ return { status: "ready", deviceId: found.id };
554
+ }
555
+ if (found.kind === "desktop") {
556
+ write2(`The Capy desktop app pairs this computer, but ${name} cannot tell which device to use:
557
+ ${found.text}
558
+ `);
559
+ return { status: "skipped" };
560
+ }
561
+ const os = dockOs(io.platform);
562
+ if (os === void 0) {
563
+ write2(`This computer has no Capy device, and Capy's dock does not run on ${io.platform}. See ${DOCS}.
564
+ `);
565
+ return { status: "skipped" };
566
+ }
567
+ const binary = dockBinary(os, config2.capyHome);
568
+ const root = await io.gitRoot(io.folder);
569
+ if (found.kind === "device") {
570
+ write2(`Capy device on this computer: ${found.id}, from capy dock. Keep \`capy dock\` running while Capy threads run here.
571
+ `);
572
+ const linked2 = await readLinkedFolders(config2);
573
+ if (root !== void 0 && !linked2.some((folder) => samePath(folder.realRoot ?? folder.root, root) || samePath(folder.root, root))) {
574
+ write2(
575
+ `${root} may not be linked to this device. To link it, stop \`capy dock\` (this also stops the Capy threads that run here), run \`${dockCommand(os, binary, ["dirs", "add", root]).display}\`, then start \`capy dock\` again.
576
+ `
577
+ );
578
+ }
579
+ return { status: "ready", deviceId: found.id };
580
+ }
581
+ if (await io.exists(config2.capyDesktopConfigDir)) {
582
+ write2(
583
+ `The Capy desktop app is set up for this user (${config2.capyDesktopConfigDir}), but it has no device yet. Open the app and sign in. Capy runs one device per user, so ${name} does not install capy dock as well.
584
+ `
585
+ );
586
+ return { status: "skipped" };
587
+ }
588
+ write2("\nThis computer has no Capy device yet. Capy threads that run here need one: Capy's dock (`capy dock`) makes this computer one.\n");
589
+ if (!io.interactive) {
590
+ write2(`Pairing needs a person at a terminal, so ${name} set up no device. ${manualSteps(os, binary, root)}`);
591
+ return { status: "skipped" };
592
+ }
593
+ if (await io.isElevated()) {
594
+ write2(
595
+ (os === "win32" ? "This PowerShell runs as administrator. Capy's installer refuses that, and threads would run with admin rights. " : "This runs as root. Capy's installer refuses that, and threads would run with root's permissions. ") + `Run \`${setup}\` again as the user that should run Capy threads.
596
+ `
597
+ );
598
+ return { status: "skipped" };
599
+ }
600
+ if (!await io.exists(binary)) {
601
+ const install = installCommand(os);
602
+ write2(
603
+ `${name} can run Capy's official installer${os === "win32" ? " in PowerShell" : ""}:
604
+ ${install.display}
605
+ It installs capy in ${pathFor(os).dirname(binary)} for this user only.` + (os === "win32" ? " Threads run commands in Git Bash, so install Git for Windows too." : "") + "\n"
606
+ );
607
+ if (!await io.confirm("Run it now?")) {
608
+ write2(`Nothing was installed. ${manualSteps(os, binary, root)}`);
609
+ return { status: "skipped" };
610
+ }
611
+ const result = await io.run(install, { terminal: true });
612
+ if (!await io.exists(binary)) {
613
+ write2(`The installer did not install ${binary}${result.code ? ` (exit code ${result.code})` : ""}. Check its output above, and see ${DOCS}.
614
+ `);
615
+ return { status: "failed" };
616
+ }
617
+ } else {
618
+ write2(`Capy's dock is installed at ${binary}, but it is not paired yet.
619
+ `);
620
+ }
621
+ write2(
622
+ "\nNext, pair this computer with your Capy organization. capy dock shows a link, a QR code and a pairing code here.\n 1. Open the link or scan the code, and sign in to Capy.\n 2. Check the hostname and system, pick the organization, name the device, and approve it.\n 3. Back here, capy dock asks whether to pair with that organization. Choose Yes. It defaults to No.\nNever approve a code that someone sent you. Press Ctrl+C to stop.\n\n"
623
+ );
624
+ const dock = io.start(dockCommand(os, binary, []));
625
+ const pairing = await waitForPairing(config2, io, dock);
626
+ let stopped = true;
627
+ if (pairing.kind !== "exited") {
628
+ if (pairing.kind === "paired") await io.sleep(2e3);
629
+ stopped = await stopDock(io, dock);
630
+ }
631
+ const stillRuns = `capy dock did not stop when ${name} asked it to, and still runs. Stop it yourself (Ctrl+C in its window, or end the process).`;
632
+ if (pairing.kind !== "paired") {
633
+ write2(
634
+ (pairing.kind === "timeout" ? `The pairing did not finish within ${PAIRING_LIMIT_MS / 6e4} minutes, so ${name} stopped capy dock.` : "capy dock stopped before the pairing finished.") + (stopped ? "" : ` ${stillRuns}`) + ` Run \`${dockCommand(os, binary, []).display}\` to try again, then run \`${setup}\` again.
635
+ `
636
+ );
637
+ return { status: "failed" };
638
+ }
639
+ if (!stopped) {
640
+ write2(
641
+ `
642
+ Paired. Capy device: ${pairing.id}. ${stillRuns} ${name} linked no folder and installed no service.
643
+ Check that the organization and device name that capy dock showed are yours. If not, revoke the device at ${DEVICES}.
644
+ ` + (root === void 0 ? "" : `Once it has stopped, run \`${dockCommand(os, binary, ["dirs", "add", root]).display}\`. `) + `Then start \`${dockCommand(os, binary, []).display}\` again and keep it running.
645
+ `
646
+ );
647
+ return { status: "failed", deviceId: pairing.id };
648
+ }
649
+ write2(
650
+ `
651
+ Paired. Capy device: ${pairing.id}. ${name} stopped capy dock to link folders.
652
+ Check that the organization and device name that capy dock showed are yours. If not, revoke the device at ${DEVICES}.
653
+ `
654
+ );
655
+ const linked = await linkFolder(name, io, write2, os, binary, root);
656
+ const service = await offerService(config2, io, write2, os, binary);
657
+ write2(
658
+ `
659
+ Done. Capy device ${pairing.id} runs on this computer with capy dock` + (linked ? `, linked to ${root}` : "") + (service === "installed" ? ", and a service keeps it running.\n" : ". It is offline until you start `capy dock`.\n")
660
+ );
661
+ return { status: service === "failed" ? "failed" : "ready", deviceId: pairing.id };
662
+ };
663
+ var nodeMachineIo = (folder = process.cwd()) => {
664
+ const platform = process.platform;
665
+ const spawnArgs = (step2) => [step2.command, [...step2.args]];
666
+ const run2 = (step2, options) => new Promise((resolve3) => {
667
+ let output = "";
668
+ const child = spawn(...spawnArgs(step2), { stdio: options?.terminal ? "inherit" : ["ignore", "pipe", "pipe"] });
669
+ child.stdout?.on("data", (chunk2) => output += chunk2.toString());
670
+ child.stderr?.on("data", (chunk2) => output += chunk2.toString());
671
+ child.on("error", (error) => resolve3({ code: void 0, output: error.message }));
672
+ child.on("close", (code) => resolve3({ code: code ?? void 0, output }));
673
+ });
674
+ return {
675
+ platform,
676
+ home: homedir2(),
677
+ env: process.env,
678
+ uid: process.getuid?.(),
679
+ interactive: process.stdin.isTTY === true && process.stdout.isTTY === true,
680
+ folder,
681
+ isElevated: async () => {
682
+ if (platform !== "win32") return process.getuid?.() === 0;
683
+ const check = await run2({
684
+ command: "powershell.exe",
685
+ args: [
686
+ "-NoProfile",
687
+ "-NonInteractive",
688
+ "-Command",
689
+ "([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)"
690
+ ],
691
+ display: ""
692
+ });
693
+ return check.output.trim() === "True";
694
+ },
695
+ exists: (path) => access(path).then(() => true, () => false),
696
+ writeFile: async (path, content) => {
697
+ await mkdir(dirname(path), { recursive: true });
698
+ await writeFile(path, content);
699
+ },
700
+ removeFile: (path) => rm(path, { force: true }),
701
+ confirm: async (question) => {
702
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
703
+ const cancel = new AbortController();
704
+ rl.on("SIGINT", () => (process.stdout.write("\n"), cancel.abort()));
705
+ try {
706
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `, { signal: cancel.signal })).trim());
707
+ } catch {
708
+ return false;
709
+ } finally {
710
+ rl.close();
711
+ }
712
+ },
713
+ run: run2,
714
+ start: (step2) => {
715
+ const child = spawn(...spawnArgs(step2), { stdio: "inherit" });
716
+ const exited = new Promise((resolve3) => {
717
+ child.on("error", () => resolve3(void 0));
718
+ child.on("exit", (code) => resolve3(code ?? void 0));
719
+ });
720
+ return { exited, stop: (force) => void child.kill(force === true ? "SIGKILL" : "SIGTERM") };
721
+ },
722
+ sleep: (ms) => new Promise((resolve3) => setTimeout(resolve3, ms)),
723
+ gitRoot: (dir) => readGit(dir).then((git) => git.openedRoot ?? git.gitRoot)
724
+ };
725
+ };
726
+
727
+ // ../core/src/setup.ts
728
+ var savedApiKey = async (config2) => {
729
+ const fromEnv = process.env.CAPY_API_KEY?.trim();
730
+ if (fromEnv) return fromEnv;
731
+ const fromFile = await readFile2(config2.apiKeyFile, "utf8").then((text) => text.trim(), () => "");
732
+ return fromFile || void 0;
733
+ };
734
+ var runSetup = async (config2, io) => {
735
+ io.write(`${config2.product.name} setup. It saves ${SHARED_KEY}, in ${config2.apiKeyFile} (readable only by you).
736
+ `);
737
+ const saved = await savedApiKey(config2);
738
+ const typed = (await io.readSecret(saved === void 0 ? "Capy API key: " : "Capy API key (press Enter to keep the saved key): ")).trim();
739
+ const key = typed === "" ? saved : typed;
740
+ if (key === void 0) {
741
+ io.write("No key entered. Nothing was saved.\n");
742
+ return 1;
743
+ }
744
+ const check = await io.fetch(`${config2.apiUrl}/projects`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" } }).then((response) => response.status, (error) => error instanceof Error ? error.message : String(error));
745
+ if (check === 401 || check === 403) {
746
+ io.write(typed === "" ? "Capy rejects the saved key. Run setup again and paste a new key.\n" : "Capy rejected this key. Nothing was saved.\n");
747
+ return 1;
748
+ }
749
+ if (typed === "") {
750
+ io.write(`Kept the saved key${process.env.CAPY_API_KEY?.trim() ? " (from CAPY_API_KEY)" : ""}.
751
+ `);
752
+ const machine2 = await setupMachine(config2, io.machine ?? nodeMachineIo(), io.write);
753
+ return machine2.status === "failed" ? 1 : 0;
754
+ }
755
+ await mkdir2(dirname2(config2.apiKeyFile), { recursive: true, mode: 448 });
756
+ await writeFile2(config2.apiKeyFile, `${key}
757
+ `, { mode: 384 });
758
+ await chmod(config2.apiKeyFile, 384);
759
+ io.write(
760
+ typeof check === "number" && check >= 200 && check < 300 ? "Capy accepted the key. Saved.\n" : `Saved, but ${config2.product.name} could not check the key with Capy (${check}).
761
+ `
762
+ );
763
+ const machine = await setupMachine(config2, io.machine ?? nodeMachineIo(), io.write);
764
+ return machine.status === "failed" ? 1 : 0;
765
+ };
766
+ var readSecretFromTerminal = (prompt) => {
767
+ const input = process.stdin;
768
+ if (!input.isTTY) {
769
+ return new Promise((resolve3) => {
770
+ let data = "";
771
+ input.setEncoding("utf8");
772
+ input.on("data", (chunk2) => data += chunk2);
773
+ input.on("end", () => resolve3(data.split(/\r?\n/)[0] ?? ""));
774
+ });
775
+ }
776
+ process.stdout.write(prompt);
777
+ return new Promise((resolve3, reject) => {
778
+ let value = "";
779
+ const finish = (error) => {
780
+ input.off("data", onData);
781
+ input.setRawMode(false);
782
+ input.pause();
783
+ process.stdout.write("\n");
784
+ if (error) reject(error);
785
+ else resolve3(value);
786
+ };
787
+ const onData = (chunk2) => {
788
+ for (const char of chunk2) {
789
+ if (char === "\r" || char === "\n") return finish();
790
+ if (char === "") return finish(new Error("Cancelled."));
791
+ if (char === "\x7F" || char === "\b") value = value.slice(0, -1);
792
+ else value += char;
793
+ }
794
+ };
795
+ input.setEncoding("utf8");
796
+ input.setRawMode(true);
797
+ input.resume();
798
+ input.on("data", onData);
799
+ });
800
+ };
801
+
802
+ // src/mcp.ts
803
+ import { resolve as resolve2 } from "node:path";
804
+ import { Cause as Cause2, Context as Context2, Effect as Effect3, Exit, Layer as Layer2, Logger, PlatformError, Predicate, Schema as Schema3, Sink, Stdio, Stream as Stream3 } from "effect";
805
+ import { McpProtocol, McpSchema, McpServer } from "effect/ai";
806
+
807
+ // ../core/src/capy/client.ts
808
+ import { readFile as readFile3 } from "node:fs/promises";
809
+ import { Context, Data, Duration, Effect, Layer, Schema as Schema2, Stream } from "effect";
810
+ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
811
+
812
+ // ../core/src/sse.ts
813
+ var makeSseParser = () => {
814
+ let buffer = "";
815
+ let event = "";
816
+ let data = [];
817
+ let id;
818
+ let sawField = false;
819
+ const dispatch = (out) => {
820
+ if (sawField && data.length > 0) {
821
+ out.push({ event: event === "" ? "message" : event, data: data.join("\n"), ...id === void 0 ? {} : { id } });
822
+ }
823
+ event = "";
824
+ data = [];
825
+ id = void 0;
826
+ sawField = false;
827
+ };
828
+ const line = (raw, out) => {
829
+ if (raw === "") return dispatch(out);
830
+ if (raw.startsWith(":")) return;
831
+ const colon = raw.indexOf(":");
832
+ const field = colon === -1 ? raw : raw.slice(0, colon);
833
+ let value = colon === -1 ? "" : raw.slice(colon + 1);
834
+ if (value.startsWith(" ")) value = value.slice(1);
835
+ switch (field) {
836
+ case "event":
837
+ event = value;
838
+ sawField = true;
839
+ return;
840
+ case "data":
841
+ data.push(value);
842
+ sawField = true;
843
+ return;
844
+ case "id":
845
+ if (!value.includes("\0")) id = value;
846
+ sawField = true;
847
+ return;
848
+ default:
849
+ return;
850
+ }
851
+ };
852
+ const drain = (final) => {
853
+ const out = [];
854
+ for (; ; ) {
855
+ const match = /\r\n|\r|\n/.exec(buffer);
856
+ if (match === null) break;
857
+ if (match[0] === "\r" && match.index === buffer.length - 1 && !final) break;
858
+ line(buffer.slice(0, match.index), out);
859
+ buffer = buffer.slice(match.index + match[0].length);
860
+ }
861
+ if (final) {
862
+ if (buffer !== "") line(buffer, out);
863
+ buffer = "";
864
+ dispatch(out);
865
+ }
866
+ return out;
867
+ };
868
+ let pending = [];
869
+ const flush = () => {
870
+ if (pending.length > 0) {
871
+ buffer += pending.join("");
872
+ pending = [];
873
+ }
874
+ };
875
+ return {
876
+ push: (chunk2) => {
877
+ if (!/[\r\n]/.test(chunk2) && !buffer.endsWith("\r")) {
878
+ pending.push(chunk2);
879
+ return [];
880
+ }
881
+ flush();
882
+ buffer += chunk2;
883
+ return drain(false);
884
+ },
885
+ end: () => {
886
+ flush();
887
+ return drain(true);
888
+ }
889
+ };
890
+ };
891
+
892
+ // ../core/src/capy/events.ts
893
+ import { Option, Schema } from "effect";
894
+ var ThreadStatus = Schema.Literals(["working", "waiting", "idle", "failed", "archived"]);
895
+ var nullable = (schema) => Schema.optionalKey(Schema.NullOr(schema));
896
+ var RawMessage = Schema.Struct({
897
+ id: Schema.String,
898
+ source: Schema.Literals(["user", "assistant", "tool"]),
899
+ text: nullable(Schema.String),
900
+ tool: nullable(Schema.String),
901
+ callId: nullable(Schema.String),
902
+ calls: nullable(Schema.Array(Schema.Struct({ tool: Schema.String, durationMs: nullable(Schema.Unknown) }))),
903
+ model: nullable(Schema.String),
904
+ clientKey: nullable(Schema.String),
905
+ createdAt: nullable(Schema.String),
906
+ attachments: nullable(Schema.Array(Schema.Unknown))
907
+ });
908
+ var present = (key, value) => value === null || value === void 0 ? {} : { [key]: value };
909
+ var decodeMessage = (data) => Option.map(Schema.decodeUnknownOption(RawMessage)(data), (raw) => ({
910
+ id: raw.id,
911
+ source: raw.source,
912
+ ...present("text", raw.text),
913
+ ...present("tool", raw.tool),
914
+ ...present("callId", raw.callId),
915
+ ...present(
916
+ "calls",
917
+ raw.calls?.map((call) => ({
918
+ tool: call.tool,
919
+ ...typeof call.durationMs === "number" && Number.isFinite(call.durationMs) ? { durationMs: call.durationMs } : {}
920
+ }))
921
+ ),
922
+ ...present("model", raw.model),
923
+ ...present("clientKey", raw.clientKey),
924
+ ...present("createdAt", raw.createdAt),
925
+ ...present("attachments", raw.attachments)
926
+ }));
927
+ var Attachment = Schema.Struct({
928
+ file: Schema.Struct({
929
+ fileId: Schema.String,
930
+ name: Schema.String,
931
+ mediaType: Schema.optionalKey(Schema.NullOr(Schema.String)),
932
+ sizeBytes: Schema.optionalKey(Schema.Unknown),
933
+ sourcePath: Schema.optionalKey(Schema.NullOr(Schema.String))
934
+ }),
935
+ title: Schema.optionalKey(Schema.NullOr(Schema.String))
936
+ });
937
+ var messageFiles = (message) => (message.attachments ?? []).flatMap(
938
+ (item) => Option.match(Schema.decodeUnknownOption(Attachment)(item), {
939
+ onNone: () => [],
940
+ onSome: ({ file, title }) => [{
941
+ fileId: file.fileId,
942
+ name: file.name,
943
+ mediaType: file.mediaType ?? void 0,
944
+ sizeBytes: typeof file.sizeBytes === "number" && Number.isFinite(file.sizeBytes) ? file.sizeBytes : void 0,
945
+ sourcePath: file.sourcePath ?? void 0,
946
+ title: title ?? void 0
947
+ }]
948
+ })
949
+ );
950
+ var payloads = {
951
+ status: Schema.Struct({ status: ThreadStatus }),
952
+ run: Schema.Struct({ phase: Schema.Literals(["start", "end"]) }),
953
+ turn: Schema.Struct({
954
+ phase: Schema.Literals(["start", "end"]),
955
+ outcome: Schema.optionalKey(Schema.String)
956
+ }),
957
+ assistant: Schema.Struct({ callId: Schema.String, text: Schema.String }),
958
+ tool_call: Schema.Struct({ callId: Schema.String, name: Schema.String, text: Schema.optionalKey(Schema.String) }),
959
+ error: Schema.Struct({ code: Schema.String, message: Schema.optionalKey(Schema.String) }),
960
+ // Subagent lifecycle. Thread streams send `task` frames unless opened with `frames=subagent`.
961
+ task: Schema.Struct({ taskId: Schema.String, taskPath: Schema.optionalKey(Schema.NullOr(Schema.String)), status: Schema.String }),
962
+ subagent: Schema.Struct({ subagentId: Schema.String, subagentPath: Schema.optionalKey(Schema.NullOr(Schema.String)), status: Schema.String })
963
+ };
964
+ var decode = (schema, data) => Schema.decodeUnknownOption(schema)(data);
965
+ var decodeEvent = (frame) => {
966
+ const unknown = { _tag: "Unknown", event: frame.event };
967
+ let data;
968
+ try {
969
+ data = JSON.parse(frame.data);
970
+ } catch {
971
+ return unknown;
972
+ }
973
+ switch (frame.event) {
974
+ case "status":
975
+ return Option.match(decode(payloads.status, data), {
976
+ onNone: () => unknown,
977
+ onSome: ({ status }) => ({ _tag: "Status", status })
978
+ });
979
+ case "transcript":
980
+ return Option.match(decodeMessage(data), {
981
+ onNone: () => unknown,
982
+ onSome: (message) => ({ _tag: "Transcript", cursor: frame.id, message })
983
+ });
984
+ case "run":
985
+ return Option.match(decode(payloads.run, data), {
986
+ onNone: () => unknown,
987
+ onSome: ({ phase }) => ({ _tag: "Run", phase })
988
+ });
989
+ case "turn":
990
+ return Option.match(decode(payloads.turn, data), {
991
+ onNone: () => unknown,
992
+ onSome: (turn) => ({ _tag: "Turn", phase: turn.phase, outcome: turn.outcome })
993
+ });
994
+ case "assistant":
995
+ return Option.match(decode(payloads.assistant, data), {
996
+ onNone: () => unknown,
997
+ onSome: ({ callId, text }) => ({ _tag: "Assistant", callId, text })
998
+ });
999
+ case "tool_call":
1000
+ return Option.match(decode(payloads.tool_call, data), {
1001
+ onNone: () => unknown,
1002
+ onSome: (call) => ({ _tag: "ToolCall", callId: call.callId, name: call.name, text: call.text ?? "" })
1003
+ });
1004
+ case "error":
1005
+ return Option.match(decode(payloads.error, data), {
1006
+ onNone: () => ({ _tag: "StreamError", code: "internal", message: frame.data }),
1007
+ onSome: (error) => ({ _tag: "StreamError", code: error.code, message: error.message ?? error.code })
1008
+ });
1009
+ case "task":
1010
+ return Option.match(decode(payloads.task, data), {
1011
+ onNone: () => unknown,
1012
+ onSome: (task) => ({ _tag: "Subagent", id: task.taskId, path: task.taskPath ?? void 0, status: task.status })
1013
+ });
1014
+ case "subagent":
1015
+ return Option.match(decode(payloads.subagent, data), {
1016
+ onNone: () => unknown,
1017
+ onSome: (sub) => ({ _tag: "Subagent", id: sub.subagentId, path: sub.subagentPath ?? void 0, status: sub.status })
1018
+ });
1019
+ case "done":
1020
+ return { _tag: "Done" };
1021
+ case "heartbeat":
1022
+ return { _tag: "Heartbeat" };
1023
+ default:
1024
+ return unknown;
1025
+ }
1026
+ };
1027
+
1028
+ // ../core/src/capy/client.ts
1029
+ var CapyApiError = class extends Data.TaggedError("CapyApiError") {
1030
+ };
1031
+ var CapyTransportError = class extends Data.TaggedError("CapyTransportError") {
1032
+ };
1033
+ var CapyConfigError = class extends Data.TaggedError("CapyConfigError") {
1034
+ };
1035
+ var isCapyError = (error) => error instanceof CapyApiError || error instanceof CapyTransportError || error instanceof CapyConfigError;
1036
+ var Model = Schema2.Struct({
1037
+ id: Schema2.String,
1038
+ name: Schema2.String,
1039
+ billing: Schema2.optionalKey(Schema2.String),
1040
+ route: Schema2.optionalKey(Schema2.String),
1041
+ reasoningModes: Schema2.optionalKey(Schema2.Array(Schema2.String))
1042
+ });
1043
+ var Project = Schema2.Struct({
1044
+ id: Schema2.String,
1045
+ name: Schema2.String,
1046
+ repos: Schema2.Array(Schema2.Struct({ repoFullName: Schema2.String }))
1047
+ });
1048
+ var Page = (item) => Schema2.Struct({ items: Schema2.Array(item), cursor: Schema2.optionalKey(Schema2.NullOr(Schema2.String)) });
1049
+ var Usage = Schema2.Struct({
1050
+ totalCredits: Schema2.Number,
1051
+ llmCredits: Schema2.optionalKey(Schema2.Number),
1052
+ imageCredits: Schema2.optionalKey(Schema2.Number),
1053
+ vmCredits: Schema2.optionalKey(Schema2.Number)
1054
+ });
1055
+ var nullable2 = (schema) => Schema2.optionalKey(Schema2.NullOr(schema));
1056
+ var ThreadAsk = Schema2.Struct({ kind: Schema2.String, text: nullable2(Schema2.String) });
1057
+ var Thread = Schema2.Struct({
1058
+ id: Schema2.String,
1059
+ status: ThreadStatus,
1060
+ usage: Schema2.optionalKey(Usage),
1061
+ title: nullable2(Schema2.String),
1062
+ projectId: nullable2(Schema2.String),
1063
+ lastModelId: nullable2(Schema2.String),
1064
+ ask: nullable2(ThreadAsk),
1065
+ needsYou: nullable2(Schema2.Boolean),
1066
+ createdAt: nullable2(Schema2.String),
1067
+ updatedAt: nullable2(Schema2.String),
1068
+ lastActivityAt: nullable2(Schema2.String)
1069
+ });
1070
+ var Receipt = Schema2.Struct({ id: Schema2.String });
1071
+ var UploadTargets = Schema2.Struct({
1072
+ targets: Schema2.Array(Schema2.Struct({ fileId: Schema2.String, url: Schema2.String }))
1073
+ });
1074
+ var MessagePage = Schema2.Struct({
1075
+ items: Schema2.Array(Schema2.Unknown),
1076
+ cursor: Schema2.optionalKey(Schema2.NullOr(Schema2.String))
1077
+ });
1078
+ var Download = Schema2.Struct({ url: Schema2.String, expiresAt: Schema2.optionalKey(Schema2.String) });
1079
+ var MACHINE_SIZES = ["small", "medium", "large", "ultra", "hyper", "bigguy"];
1080
+ var CapyClient = class extends Context.Service()("capy-acp/CapyClient") {
1081
+ };
1082
+ var RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 502, 503, 504]);
1083
+ var MAX_ATTEMPTS = 4;
1084
+ var MAX_RETRY_AFTER_MS = 6e4;
1085
+ var retryDelay = (error, attempt) => {
1086
+ if (attempt >= MAX_ATTEMPTS) return void 0;
1087
+ if (error._tag === "CapyTransportError") return error.decode === true ? void 0 : 500 * 2 ** attempt;
1088
+ if (error._tag === "CapyConfigError" || !RETRYABLE_STATUS.has(error.status)) return void 0;
1089
+ const delay = error.retryAfterMs ?? 1e3 * 2 ** attempt;
1090
+ return delay > MAX_RETRY_AFTER_MS ? void 0 : delay;
1091
+ };
1092
+ var isTransient = (error) => error._tag === "CapyTransportError" && error.decode !== true || error._tag === "CapyApiError" && (error.status === 429 || error.status >= 500);
1093
+ var describeError = (error) => error._tag === "CapyApiError" ? `Capy ${error.tag} (${error.status}): ${error.message}` : error.message;
1094
+ var withRetry = (effect, attempt = 1) => effect.pipe(
1095
+ Effect.catch((error) => {
1096
+ const delay = retryDelay(error, attempt);
1097
+ return delay === void 0 ? Effect.fail(error) : Effect.sleep(Duration.millis(delay)).pipe(Effect.andThen(withRetry(effect, attempt + 1)));
1098
+ })
1099
+ );
1100
+ var apiError = (response) => response.json.pipe(
1101
+ Effect.orElseSucceed(() => ({})),
1102
+ Effect.flatMap((body) => {
1103
+ const record = typeof body === "object" && body !== null ? body : {};
1104
+ const header = Number(response.headers["retry-after"]);
1105
+ const bodySeconds = typeof record.retryAfterSeconds === "number" ? record.retryAfterSeconds : void 0;
1106
+ const seconds = Number.isFinite(header) ? header : bodySeconds;
1107
+ return Effect.fail(
1108
+ new CapyApiError({
1109
+ status: response.status,
1110
+ tag: typeof record._tag === "string" ? record._tag : `http/${response.status}`,
1111
+ message: typeof record.message === "string" ? record.message : `Capy API answered ${response.status}`,
1112
+ retryAfterMs: seconds === void 0 ? void 0 : seconds * 1e3
1113
+ })
1114
+ );
1115
+ })
1116
+ );
1117
+ var readApiKey = (config2) => {
1118
+ const fromEnv = process.env.CAPY_API_KEY?.trim();
1119
+ if (fromEnv) return Effect.succeed(fromEnv);
1120
+ return Effect.tryPromise({
1121
+ try: async () => (await readFile3(config2.apiKeyFile, "utf8")).trim(),
1122
+ catch: () => new CapyConfigError({
1123
+ message: `No Capy API key. Run \`${config2.product.setup}\` in a terminal, or set CAPY_API_KEY, or put the key in ${config2.apiKeyFile} (mode 0600).`
1124
+ })
1125
+ }).pipe(
1126
+ Effect.filterOrFail(
1127
+ (key) => key.length > 0,
1128
+ () => new CapyConfigError({ message: `The Capy API key file ${config2.apiKeyFile} is empty.` })
1129
+ )
1130
+ );
1131
+ };
1132
+ var make = (config2) => Effect.gen(function* () {
1133
+ const base = yield* HttpClient.HttpClient;
1134
+ const http = base.pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl(config2.apiUrl)));
1135
+ const authorize = (request) => readApiKey(config2).pipe(Effect.map((key) => request.pipe(HttpClientRequest.bearerToken(key))));
1136
+ const send = (request) => authorize(request).pipe(
1137
+ Effect.flatMap(
1138
+ (authorized) => http.execute(authorized).pipe(
1139
+ Effect.mapError((cause) => new CapyTransportError({ message: `Capy API request failed: ${cause.message}`, cause }))
1140
+ )
1141
+ ),
1142
+ Effect.flatMap((response) => response.status >= 200 && response.status < 300 ? Effect.succeed(response) : apiError(response))
1143
+ );
1144
+ const json = (schema, request) => withRetry(
1145
+ send(request.pipe(HttpClientRequest.acceptJson)).pipe(
1146
+ Effect.flatMap((response) => response.json),
1147
+ Effect.flatMap((body) => Schema2.decodeUnknownEffect(schema)(body)),
1148
+ Effect.mapError(
1149
+ (error) => error instanceof CapyApiError || error instanceof CapyTransportError || error instanceof CapyConfigError ? error : new CapyTransportError({
1150
+ message: `Unexpected Capy API response: ${String(error)}`,
1151
+ cause: error,
1152
+ // A body that did not arrive whole is worth another try; one that does not match the schema is not.
1153
+ ...error instanceof Schema2.SchemaError ? { decode: true } : {}
1154
+ })
1155
+ ),
1156
+ Effect.timeout(Duration.seconds(30)),
1157
+ Effect.catchTag("TimeoutError", () => Effect.fail(new CapyTransportError({ message: "Capy API request timed out" })))
1158
+ )
1159
+ );
1160
+ const listProjects = Effect.gen(function* () {
1161
+ const projects = [];
1162
+ let cursor = void 0;
1163
+ do {
1164
+ const query = cursor ? `?cursor=${encodeURIComponent(cursor)}` : "";
1165
+ const page = yield* json(Page(Project), HttpClientRequest.get(`/projects${query}`));
1166
+ projects.push(...page.items);
1167
+ cursor = page.cursor;
1168
+ } while (cursor);
1169
+ return projects;
1170
+ });
1171
+ const listMessages = (threadId) => Effect.gen(function* () {
1172
+ const messages = [];
1173
+ let after = void 0;
1174
+ for (; ; ) {
1175
+ const query = after ? `?after=${encodeURIComponent(after)}` : "";
1176
+ const page = yield* json(MessagePage, HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}/messages${query}`));
1177
+ for (const item of page.items) {
1178
+ const message = decodeMessage(item);
1179
+ if (message._tag === "Some") messages.push(message.value);
1180
+ }
1181
+ if (!page.cursor || page.cursor === after) return messages;
1182
+ after = page.cursor;
1183
+ }
1184
+ });
1185
+ const putBytes = (url, file) => withRetry(
1186
+ base.execute(HttpClientRequest.put(url).pipe(HttpClientRequest.bodyUint8Array(file.bytes, file.mediaType))).pipe(
1187
+ Effect.mapError((cause) => new CapyTransportError({ message: `Uploading ${file.name} failed: ${cause.message}`, cause })),
1188
+ Effect.flatMap(
1189
+ (response) => response.status >= 200 && response.status < 300 ? Effect.void : Effect.fail(
1190
+ new CapyApiError({ status: response.status, tag: `upload/${response.status}`, message: `Uploading ${file.name} failed (${response.status})`, retryAfterMs: void 0 })
1191
+ )
1192
+ )
1193
+ )
1194
+ );
1195
+ const uploadFiles = (files) => Effect.gen(function* () {
1196
+ if (files.length === 0) return [];
1197
+ const { targets } = yield* json(
1198
+ UploadTargets,
1199
+ HttpClientRequest.post("/files").pipe(
1200
+ HttpClientRequest.bodyJsonUnsafe({ files: files.map((f) => ({ name: f.name, mediaType: f.mediaType, sizeBytes: f.bytes.byteLength })) })
1201
+ )
1202
+ );
1203
+ if (targets.length !== files.length) {
1204
+ return yield* Effect.fail(new CapyTransportError({ message: `Capy returned ${targets.length} upload targets for ${files.length} files` }));
1205
+ }
1206
+ yield* Effect.forEach(files, (file, i) => putBytes(targets[i].url, file), { concurrency: 4, discard: true });
1207
+ return files.map((file, i) => ({ fileId: targets[i].fileId, name: file.name }));
1208
+ });
1209
+ return CapyClient.of({
1210
+ listModels: json(Page(Model), HttpClientRequest.get("/models")).pipe(Effect.map((page) => page.items)),
1211
+ listProjects,
1212
+ createThread: (body) => json(Thread, HttpClientRequest.post("/threads").pipe(HttpClientRequest.bodyJsonUnsafe(body))),
1213
+ sendMessage: (threadId, body) => json(
1214
+ Receipt,
1215
+ HttpClientRequest.post(`/threads/${encodeURIComponent(threadId)}/message`).pipe(HttpClientRequest.bodyJsonUnsafe(body))
1216
+ ),
1217
+ interrupt: (threadId) => withRetry(send(HttpClientRequest.post(`/threads/${encodeURIComponent(threadId)}/interrupt`))).pipe(Effect.asVoid),
1218
+ getThread: (threadId) => json(Thread, HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}`)),
1219
+ listThreads: (projectId, { limit }) => json(Page(Thread), HttpClientRequest.get(`/threads?projectId=${encodeURIComponent(projectId)}&limit=${limit}`)).pipe(
1220
+ Effect.map((page) => page.items)
1221
+ ),
1222
+ uploadFiles,
1223
+ listMessages,
1224
+ attachmentUrl: (threadId, fileId) => json(
1225
+ Download,
1226
+ HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}/attachments/${encodeURIComponent(fileId)}/download`)
1227
+ ).pipe(Effect.map((download) => download.url)),
1228
+ stream: (threadId, { cursor, untilRun }) => Stream.unwrap(
1229
+ withRetry(
1230
+ send(
1231
+ HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}/stream${untilRun ? "?until=run" : ""}`).pipe(
1232
+ HttpClientRequest.setHeader("accept", "text/event-stream"),
1233
+ cursor === void 0 ? (request) => request : HttpClientRequest.setHeader("last-event-id", cursor)
1234
+ )
1235
+ )
1236
+ ).pipe(
1237
+ Effect.map(
1238
+ (response) => response.stream.pipe(
1239
+ Stream.mapError((cause) => new CapyTransportError({ message: `Capy stream dropped: ${cause.message}`, cause })),
1240
+ Stream.decodeText(),
1241
+ Stream.mapAccum(makeSseParser, (parser, text) => [parser, parser.push(text)], {
1242
+ onHalt: (parser) => parser.end()
1243
+ }),
1244
+ Stream.map(decodeEvent)
1245
+ )
1246
+ )
1247
+ )
1248
+ )
1249
+ });
1250
+ });
1251
+ var layer = (config2) => Layer.effect(CapyClient, make(config2)).pipe(Layer.provide(FetchHttpClient.layer));
1252
+
1253
+ // ../core/src/delegate.ts
1254
+ import { randomUUID } from "node:crypto";
1255
+ import { Cause, Clock, Data as Data2, Duration as Duration2, Effect as Effect2, Option as Option2, Result, Stream as Stream2 } from "effect";
1256
+
1257
+ // ../core/src/pricing.ts
1258
+ var unescape = (cell) => cell.replace(/\\\$/g, "$").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/<br\s*\/?>/g, "; ").trim();
1259
+ var parsePrices = (markdown) => {
1260
+ const prices = /* @__PURE__ */ new Map();
1261
+ for (const line of markdown.split("\n")) {
1262
+ const cells = line.split("|").map((cell) => cell.trim());
1263
+ const idAt = cells.findIndex((cell) => /^`[a-z0-9][\w.-]*\/[\w.-]+`$/i.test(cell));
1264
+ if (idAt < 0 || cells.length < idAt + 4) continue;
1265
+ const input = unescape(cells[idAt + 2]);
1266
+ const output = unescape(cells[idAt + 3]);
1267
+ const firstInput = /\$\d+(?:\.\d+)?/.exec(input)?.[0];
1268
+ const firstOutput = /\$\d+(?:\.\d+)?/.exec(output)?.[0];
1269
+ if (firstInput === void 0 || firstOutput === void 0) continue;
1270
+ const amounts = [...`${input} ${output}`.matchAll(/\$(\d+(?:\.\d+)?)/g)].map((m) => Number(m[1]));
1271
+ prices.set(cells[idAt].slice(1, -1), {
1272
+ input: firstInput,
1273
+ cachedInput: /cached (\$\d+(?:\.\d+)?)/.exec(input)?.[1],
1274
+ output: firstOutput,
1275
+ free: amounts.every((amount) => amount === 0),
1276
+ tiered: input.includes(";") || output.includes(";")
1277
+ });
1278
+ }
1279
+ return prices;
1280
+ };
1281
+ var fetchPrices = async (url, timeoutMs = 3e3) => {
1282
+ const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), headers: { accept: "text/markdown, text/plain" } });
1283
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`);
1284
+ return parsePrices(await response.text());
1285
+ };
1286
+ var modelDescription = (model, price) => {
1287
+ if (model.route !== "capy") return model.billing ? `Billed to: ${model.billing}` : void 0;
1288
+ if (price === void 0) return "Billed to Capy credits.";
1289
+ if (price.free) return "Free: billed to Capy credits at $0.00.";
1290
+ const cached = price.cachedInput === void 0 ? "" : ` (${price.cachedInput} cached)`;
1291
+ return `Billed to Capy credits, per 1M tokens: ${price.input} input${cached}, ${price.output} output${price.tiered ? ", more above a context threshold" : ""}.`;
1292
+ };
1293
+ var formatCredits = (credits) => {
1294
+ const dollars = credits / 1e3;
1295
+ if (dollars > 0 && dollars < 0.01) return "less than $0.01";
1296
+ return `$${dollars.toFixed(2)}`;
1297
+ };
1298
+
1299
+ // ../core/src/translate.ts
1300
+ var initialTurn = (cursor) => ({
1301
+ cursor,
1302
+ status: void 0,
1303
+ active: false,
1304
+ assistant: /* @__PURE__ */ new Map(),
1305
+ settled: /* @__PURE__ */ new Set(),
1306
+ endPending: false,
1307
+ lastAssistantCallId: void 0,
1308
+ tools: /* @__PURE__ */ new Map(),
1309
+ cancelled: false
1310
+ });
1311
+ var READ_TOOLS = /* @__PURE__ */ new Set(["read", "view", "cat", "open"]);
1312
+ var SEARCH_TOOLS = /* @__PURE__ */ new Set(["grep", "glob", "search", "find", "ls", "list"]);
1313
+ var FETCH_TOOLS = /* @__PURE__ */ new Set(["fetch", "web_fetch", "web_search", "browse"]);
1314
+ var toolKind = (names) => {
1315
+ const lower = names.map((name) => name.toLowerCase());
1316
+ if (lower.length > 0 && lower.every((name) => READ_TOOLS.has(name))) return "read";
1317
+ if (lower.length > 0 && lower.every((name) => SEARCH_TOOLS.has(name) || READ_TOOLS.has(name))) return "search";
1318
+ if (lower.length > 0 && lower.every((name) => FETCH_TOOLS.has(name))) return "fetch";
1319
+ if (lower.length > 0 && lower.every((name) => name === "think")) return "think";
1320
+ return "other";
1321
+ };
1322
+ var toolStatus = (message, cancelled) => {
1323
+ if ((message.calls?.length ?? 0) > 0) return "completed";
1324
+ if (message.tool === "execute") return "failed";
1325
+ return cancelled ? "failed" : "completed";
1326
+ };
1327
+ var formatSeconds = (ms) => ms < 1e3 ? `${Math.round(ms)} ms` : `${(ms / 1e3).toFixed(1)} s`;
1328
+ var toolTitle = (message) => {
1329
+ const summary = message.text?.trim() ?? "";
1330
+ if (summary !== "") return summary;
1331
+ const calls = message.calls ?? [];
1332
+ if (calls.length === 0) return message.tool === "execute" ? "Stopped tool call" : message.tool ?? "Tool call";
1333
+ const names = [...new Set(calls.map((call) => call.tool))].join(", ");
1334
+ const total = calls.reduce((sum, call) => sum + (call.durationMs ?? 0), 0);
1335
+ return total > 0 ? `${names} (${formatSeconds(total)})` : names;
1336
+ };
1337
+ var liveTitle = (name, text) => {
1338
+ const summary = text.trim();
1339
+ if (summary !== "") return summary;
1340
+ return name === "execute" ? "Running tools" : name;
1341
+ };
1342
+ var chunk = (text) => ({
1343
+ sessionUpdate: "agent_message_chunk",
1344
+ content: { type: "text", text }
1345
+ });
1346
+ var emitAssistant = (state, callId, text) => {
1347
+ if (text === "") return { state, updates: [] };
1348
+ const previous = state.assistant.get(callId) ?? "";
1349
+ const separate = previous === "" && state.lastAssistantCallId !== void 0 && state.lastAssistantCallId !== callId;
1350
+ const assistant = new Map(state.assistant).set(callId, previous + text);
1351
+ return {
1352
+ state: { ...state, active: true, assistant, lastAssistantCallId: callId },
1353
+ updates: [chunk(separate ? `
1354
+
1355
+ ${text}` : text)]
1356
+ };
1357
+ };
1358
+ var unsettled = (state) => [...state.assistant.keys()].filter((id) => !state.settled.has(id)).length;
1359
+ var turnComplete = (state) => unsettled(state) === 0;
1360
+ var endIfComplete = (step2) => step2.state.endPending && turnComplete(step2.state) ? { ...step2, state: { ...step2.state, endPending: false }, signal: { _tag: "Ended" } } : step2;
1361
+ var onTranscript = (state, cursor, message) => {
1362
+ const base = { ...state, cursor: cursor ?? state.cursor };
1363
+ switch (message.source) {
1364
+ case "user":
1365
+ return { state: { ...base, active: true }, updates: [] };
1366
+ case "assistant": {
1367
+ const callId = message.callId ?? message.id;
1368
+ const text = message.text ?? "";
1369
+ const files = base.settled.has(callId) ? [] : messageFiles(message);
1370
+ const streamed = base.assistant.get(callId) ?? "";
1371
+ const emitted = text.startsWith(streamed) ? emitAssistant(base, callId, text.slice(streamed.length)) : { state: { ...base, active: true }, updates: [] };
1372
+ const state2 = {
1373
+ ...emitted.state,
1374
+ assistant: new Map(emitted.state.assistant).set(callId, emitted.state.assistant.get(callId) ?? text),
1375
+ settled: new Set(emitted.state.settled).add(callId)
1376
+ };
1377
+ return endIfComplete({ state: state2, updates: emitted.updates, ...files.length > 0 ? { files } : {} });
1378
+ }
1379
+ case "tool": {
1380
+ const known = base.tools.get(message.id);
1381
+ if (known?.done === true) return { state: { ...base, active: true }, updates: [] };
1382
+ const names = message.calls?.map((call) => call.tool) ?? (message.tool === void 0 ? [] : [message.tool]);
1383
+ const title = toolTitle(message);
1384
+ const kind = toolKind(names.length > 0 ? names : [message.tool ?? ""]);
1385
+ const status = toolStatus(message, base.cancelled);
1386
+ const tools = new Map(base.tools).set(message.id, { title, kind, done: true });
1387
+ const next = { ...base, active: true, tools };
1388
+ const fields = { toolCallId: message.id, title, kind, status };
1389
+ return {
1390
+ state: next,
1391
+ updates: [known === void 0 ? { sessionUpdate: "tool_call", ...fields } : { sessionUpdate: "tool_call_update", ...fields }]
1392
+ };
1393
+ }
1394
+ }
1395
+ };
1396
+ var subagentCallId = (id) => `capy-subagent-${id}`;
1397
+ var SUBAGENT_STATUS = {
1398
+ draft: "pending",
1399
+ working: "in_progress",
1400
+ waiting: "in_progress",
1401
+ idle: "completed",
1402
+ done: "completed",
1403
+ failed: "failed"
1404
+ };
1405
+ var onSubagent = (state, event) => {
1406
+ const toolCallId = subagentCallId(event.id);
1407
+ const known = state.tools.get(toolCallId);
1408
+ const mapped = SUBAGENT_STATUS[event.status] ?? "in_progress";
1409
+ const ran = known?.ran === true || mapped === "in_progress";
1410
+ const status = event.status === "idle" && !ran ? "pending" : mapped;
1411
+ const done = status === "completed" || status === "failed";
1412
+ if (known?.done === true && done || known?.shown === status) return { state, updates: [] };
1413
+ const title = `Subagent ${event.path ?? event.id}`;
1414
+ const tools = new Map(state.tools).set(toolCallId, { title, kind: "other", done, shown: status, ran });
1415
+ const update = known === void 0 ? { sessionUpdate: "tool_call", toolCallId, title, kind: "other", status } : { sessionUpdate: "tool_call_update", toolCallId, status };
1416
+ return { state: { ...state, tools }, updates: [update] };
1417
+ };
1418
+ var step = (state, event) => {
1419
+ switch (event._tag) {
1420
+ case "Assistant":
1421
+ return emitAssistant(state, event.callId, event.text);
1422
+ case "ToolCall": {
1423
+ if (state.tools.has(event.callId)) return { state, updates: [] };
1424
+ const title = liveTitle(event.name, event.text);
1425
+ const kind = toolKind([event.name]);
1426
+ return {
1427
+ state: { ...state, active: true, tools: new Map(state.tools).set(event.callId, { title, kind, done: false }) },
1428
+ updates: [{ sessionUpdate: "tool_call", toolCallId: event.callId, title, kind, status: "in_progress" }]
1429
+ };
1430
+ }
1431
+ case "Transcript":
1432
+ return onTranscript(state, event.cursor, event.message);
1433
+ case "Status": {
1434
+ const next = { ...state, status: event.status, active: state.active || event.status === "working" };
1435
+ if (event.status === "idle" && next.active) {
1436
+ return turnComplete(next) ? { state: next, updates: [], signal: { _tag: "Ended" } } : { state: { ...next, endPending: true }, updates: [] };
1437
+ }
1438
+ if (event.status === "failed" && next.active) return { state: next, updates: [], signal: { _tag: "Failed" } };
1439
+ if (event.status === "waiting" && next.active) return { state: next, updates: [], signal: { _tag: "Waiting" } };
1440
+ if (event.status === "archived") return { state: next, updates: [], signal: { _tag: "Archived" } };
1441
+ return { state: next, updates: [] };
1442
+ }
1443
+ case "Subagent":
1444
+ return onSubagent(state, event);
1445
+ case "StreamError":
1446
+ return { state, updates: [], signal: { _tag: "StreamError", code: event.code, message: event.message } };
1447
+ case "Done":
1448
+ return { state, updates: [], signal: { _tag: "StreamDone" } };
1449
+ case "Run":
1450
+ case "Turn":
1451
+ case "Heartbeat":
1452
+ case "Unknown":
1453
+ return { state, updates: [] };
1454
+ }
1455
+ };
1456
+
1457
+ // ../core/src/delegate.ts
1458
+ var DelegateError = class extends Data2.TaggedError("DelegateError") {
1459
+ };
1460
+ var titleOf = (text) => {
1461
+ const line = text.split("\n").find((l) => l.trim() !== "")?.trim() ?? "capy-acp session";
1462
+ return line.length > 80 ? `${line.slice(0, 77)}\u2026` : line;
1463
+ };
1464
+ var MAX_REPLY = 8e3;
1465
+ var EVENT_ID = /^[0-9A-HJKMNP-TV-Z]{26}$/;
1466
+ var PICKUP_MS = 2 * 6e4;
1467
+ var MAX_IDLE_RECHECKS = 10;
1468
+ var MAX_FAILURES = 12;
1469
+ var END_GRACE_MS = 1e4;
1470
+ var backoff = (attempt) => Duration2.millis(Math.min(3e4, 250 * 2 ** attempt));
1471
+ var RETRY_MS = 3e4;
1472
+ var TRY_AGAIN = "Try again.";
1473
+ var lowerFirst = (text) => text.charAt(0).toLowerCase() + text.slice(1);
1474
+ var actionable = (problem, next) => ({
1475
+ ...outsideChat(problem),
1476
+ nextAction: next ?? problem.nextAction ?? { kind: "ask_human", say: `Ask the person to ${lowerFirst(problem.title)}. ${problem.detail}` }
1477
+ });
1478
+ var fail = (problem) => Effect2.fail(new DelegateError({ problem }));
1479
+ var noKey = (keyFile, product) => ({
1480
+ title: "Add your Capy API key",
1481
+ detail: `${product.name} needs ${SHARED_KEY}, and found none.`,
1482
+ steps: [
1483
+ "Create a key in the Capy app under Settings, then API.",
1484
+ `Run \`${product.setup}\` in a terminal and paste the key (it goes to ${keyFile}). Or set \`CAPY_API_KEY\` in ${product.env}.`,
1485
+ TRY_AGAIN
1486
+ ],
1487
+ nextAction: {
1488
+ kind: "ask_human",
1489
+ say: `Ask the person to run \`${product.setup}\` in a terminal, or to set CAPY_API_KEY in ${product.env}.`
1490
+ }
1491
+ });
1492
+ var badKey = (detail, product) => ({
1493
+ title: "Replace your Capy API key",
1494
+ detail: `Capy did not accept the API key (${detail}).`,
1495
+ steps: ["Create a new key in the Capy app under Settings, then API.", `Run \`${product.setup}\` and paste it.`, TRY_AGAIN],
1496
+ nextAction: {
1497
+ kind: "ask_human",
1498
+ say: `Ask the person to create a new Capy API key (Capy app, Settings, then API) and to run \`${product.setup}\` with it.`
1499
+ }
1500
+ });
1501
+ var capyUnreachable = (apiUrl, detail, retryAfterMs = RETRY_MS) => ({
1502
+ title: "Capy could not be reached",
1503
+ detail: `${detail}.`,
1504
+ steps: [`Check the network connection to ${apiUrl}.`, `Try again in ${Math.ceil(retryAfterMs / 1e3)} seconds.`],
1505
+ nextAction: { kind: "retry", afterMs: retryAfterMs }
1506
+ });
1507
+ var threadNotFound = (threadId, product) => ({
1508
+ title: "Check the thread id",
1509
+ detail: `Capy has no thread ${threadId} that this API key can see.`,
1510
+ steps: [`List recent threads (\`${product.threads}\`, or the list_threads tool) and use an id from there.`],
1511
+ nextAction: { kind: "run_command", command: product.threads }
1512
+ });
1513
+ var projectList = (projects) => projects.map((p) => `${p.name} (${p.id})`).join(", ");
1514
+ var projectNotFound = (name, projects) => ({
1515
+ title: "Choose a Capy project",
1516
+ detail: `No Capy project has the id or name "${name}".`,
1517
+ steps: [
1518
+ projects.length === 0 ? "Create a project at https://capy.ai/settings/projects." : `Use one of these projects: ${projectList(projects)}.`,
1519
+ TRY_AGAIN
1520
+ ],
1521
+ nextAction: projects.length === 0 ? { kind: "ask_human", say: "Ask the person to create a Capy project for this repository at https://capy.ai/settings/projects." } : { kind: "use_option", option: "project", why: `Use one of these projects: ${projectList(projects)}.` }
1522
+ });
1523
+ var modelRejected = (detail) => ({
1524
+ title: "Choose another model",
1525
+ detail: `Capy did not accept the model (${detail}).`,
1526
+ steps: ["Pick a model id from the list_models tool, or from https://capy.ai/settings/models. Or leave the model out to use the default.", TRY_AGAIN],
1527
+ nextAction: { kind: "use_option", option: "model", why: "Capy did not accept this model. Use an id from list_models, or leave model out." }
1528
+ });
1529
+ var deviceNotFound = (deviceId, product) => ({
1530
+ title: "Check the Capy device id",
1531
+ detail: `Capy has no device ${deviceId} that this API key can use.`,
1532
+ steps: [
1533
+ `Run \`${product.doctor}\` on the computer that runs Capy (the desktop app or \`capy dock\`). It prints the device id.`,
1534
+ "Set `CAPY_DEVICE_ID` to that id, or pass it as the device option.",
1535
+ TRY_AGAIN
1536
+ ],
1537
+ nextAction: {
1538
+ kind: "ask_human",
1539
+ say: `Ask the person for the id of a Capy device that is running. \`${product.doctor}\` on that computer prints it.`
1540
+ }
1541
+ });
1542
+ var reasoningNeedsModel = () => ({
1543
+ title: "Pass a model with the reasoning level",
1544
+ detail: "A reasoning level belongs to a model, and no model was given.",
1545
+ steps: ["Pass model too (`--model` on the command line), with an id from list_models, or leave reasoning out to use the default model.", TRY_AGAIN],
1546
+ nextAction: { kind: "use_option", option: "model", why: "reasoning needs a model. Pass a model id from list_models, or leave reasoning out." }
1547
+ });
1548
+ var machineSizeNeedsCloud = () => ({
1549
+ title: "Use a machine size only for a cloud thread",
1550
+ detail: "A machine size applies to Capy cloud machines, and this thread would run on a Capy device.",
1551
+ steps: ['Pass where "cloud" (`--where cloud`) to run on a cloud machine, or leave the machine size out.'],
1552
+ nextAction: { kind: "use_option", option: "where", why: 'machineSize needs where "cloud" (which costs machine credits). Or leave machineSize out.' }
1553
+ });
1554
+ var repoChoice = (project) => project.repos.map((r) => r.repoFullName).join(", ");
1555
+ var chooseRepo = (project, asked) => ({
1556
+ title: "Choose a repository",
1557
+ detail: asked === void 0 ? `The Capy project ${project.name} has ${project.repos.length} repositories, and the worktree needs one of them.` : `The Capy project ${project.name} does not include ${asked}.`,
1558
+ steps: [
1559
+ project.repos.length === 0 ? `Add a repository to ${project.name} at https://capy.ai/settings/projects.` : `Pass repo as one of: ${repoChoice(project)}.`,
1560
+ TRY_AGAIN
1561
+ ],
1562
+ nextAction: project.repos.length === 0 ? { kind: "ask_human", say: `Ask the person to add the repository to the Capy project ${project.name} at https://capy.ai/settings/projects.` } : { kind: "use_option", option: "repo", why: `Use one of: ${repoChoice(project)}.` }
1563
+ });
1564
+ var chooseProject = (projects, cause) => ({
1565
+ title: "Choose a Capy project",
1566
+ detail: `${cause.detail} A thread that does not run in a linked folder needs a Capy project.`,
1567
+ steps: [
1568
+ projects.length === 0 ? "Create a project at https://capy.ai/settings/projects." : `Pass project as one of: ${projectList(projects)}.`,
1569
+ TRY_AGAIN
1570
+ ],
1571
+ nextAction: projects.length === 0 ? { kind: "ask_human", say: "Ask the person to create a Capy project for this repository at https://capy.ai/settings/projects." } : { kind: "use_option", option: "project", why: `Use one of these projects: ${projectList(projects)}.` }
1572
+ });
1573
+ var updateNeeded = (detail, product) => ({
1574
+ title: `Update ${product.name}`,
1575
+ detail: `Capy sent a response that ${product.name} ${product.version} cannot read (${detail}). Trying again gives the same answer.`,
1576
+ steps: [
1577
+ `Run the newest ${product.name} with the same arguments: \`${product.latest}\`.${product.kind === "mcp" ? " Restart the MCP server with it." : ""}`,
1578
+ "If the newest version fails the same way, report it at https://github.com/yazcaleb/capy-acp/issues with the message above."
1579
+ ],
1580
+ nextAction: {
1581
+ kind: "ask_human",
1582
+ say: `Ask the person to update ${product.name} (\`${product.latest}\`) and restart it: Capy sent a response that this version cannot read.`
1583
+ }
1584
+ });
1585
+ var passFolder = (folder, cause, product) => ({
1586
+ title: "Pass the repository folder",
1587
+ detail: `${cause.detail} ${product.name} looked there because no folder was given.`,
1588
+ steps: ["Pass folder (`--folder` on the command line) as the absolute path of the repository you work in.", TRY_AGAIN],
1589
+ nextAction: {
1590
+ kind: "use_option",
1591
+ option: "folder",
1592
+ why: `${folder} is not a git repository with a GitHub remote. Pass the absolute path of the repository you are working in.`
1593
+ }
1594
+ });
1595
+ var CLOUD_OPTION = 'Or run it on a Capy cloud machine: where "cloud" (`--where cloud` on the command line). Machine time there costs Capy credits.';
1596
+ var noDeviceTarget = (cause, product) => {
1597
+ const local = actionable(cause);
1598
+ return {
1599
+ title: "Choose where Capy runs this thread",
1600
+ detail: `No Capy device can run it. On this computer: ${local.detail}`,
1601
+ steps: [
1602
+ `Run Capy on this computer with this folder linked. ${local.steps.join(" ")}`.trim(),
1603
+ `Or use a Capy device on another computer: set \`CAPY_DEVICE_ID\` (or pass the device option) to its id, which \`${product.doctor}\` prints on that computer, and pass project (and repo when the project has several repositories).`,
1604
+ CLOUD_OPTION
1605
+ ],
1606
+ nextAction: {
1607
+ kind: "ask_human",
1608
+ say: "Ask the person where Capy should run this: " + (cause.title === NO_DEVICE_TITLE ? `set up Capy on this computer by running \`${product.setup}\` in a terminal in this folder, ` : "link this folder in Capy on this computer, ") + 'give a Capy device id and project, or allow a Capy cloud machine (where "cloud"), which costs Capy credits.'
1609
+ }
1610
+ };
1611
+ };
1612
+ var toProblem = (config2, error, context = {}) => {
1613
+ if (error instanceof DelegateError) return error.problem;
1614
+ const known = problemOf(error);
1615
+ if (known !== void 0) return actionable(known);
1616
+ if (!isCapyError(error)) {
1617
+ const detail = error instanceof Error ? error.message : String(error);
1618
+ return {
1619
+ title: `${config2.product.name} hit an unexpected error`,
1620
+ detail,
1621
+ steps: [TRY_AGAIN],
1622
+ nextAction: { kind: "ask_human", say: `Tell the person that ${config2.product.name} failed: ${detail}` }
1623
+ };
1624
+ }
1625
+ if (error._tag === "CapyConfigError") return noKey(config2.apiKeyFile, config2.product);
1626
+ if (error._tag === "CapyTransportError" && error.decode === true) return updateNeeded(describeError(error), config2.product);
1627
+ if (error._tag === "CapyTransportError" || isTransient(error)) {
1628
+ const after = error._tag === "CapyApiError" ? error.retryAfterMs : void 0;
1629
+ return capyUnreachable(config2.apiUrl, describeError(error), after ?? RETRY_MS);
1630
+ }
1631
+ if (error.status === 401) return badKey(describeError(error), config2.product);
1632
+ if (error.tag === "capy/ThreadNotFound" && context.threadId !== void 0) return threadNotFound(context.threadId, config2.product);
1633
+ if (error.tag === "ModelSelection.Rejected") return modelRejected(error.message);
1634
+ if (context.deviceId !== void 0 && /device not found/i.test(error.message)) return deviceNotFound(context.deviceId, config2.product);
1635
+ return {
1636
+ title: "Capy refused the request",
1637
+ detail: `${describeError(error)}.`,
1638
+ steps: ["Check the request against the message above.", TRY_AGAIN],
1639
+ nextAction: { kind: "ask_human", say: `Tell the person that Capy refused the request: ${describeError(error)}.` }
1640
+ };
1641
+ };
1642
+ var webOrigin = (apiUrl) => {
1643
+ try {
1644
+ return new URL(apiUrl).hostname === "api.capy.ai" ? "https://capy.ai" : void 0;
1645
+ } catch {
1646
+ return void 0;
1647
+ }
1648
+ };
1649
+ var threadUrl = (origin, threadId) => origin === void 0 ? void 0 : `${origin}/thread/${encodeURIComponent(threadId)}`;
1650
+ var CLOUD_COST = "Machine time costs Capy credits, even when the model runs on your subscription.";
1651
+ var capReply = (text) => text.length <= MAX_REPLY ? text : `${text.slice(0, MAX_REPLY)}
1652
+
1653
+ [Cut here: the reply has ${text.length - MAX_REPLY} more characters. Read the whole reply in Capy.]`;
1654
+ var PR_LINKS = [
1655
+ /https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)/g,
1656
+ /https:\/\/capy\.ai\/pull\/([\w.-]+)\/([\w.-]+)\/(\d+)/g
1657
+ ];
1658
+ var pullRequestLinks = (messages) => {
1659
+ const found = /* @__PURE__ */ new Map();
1660
+ for (const message of messages) {
1661
+ if (message.source !== "assistant" || message.text === void 0) continue;
1662
+ const hits = PR_LINKS.flatMap((pattern) => [...message.text.matchAll(pattern)]).sort((a, b) => a.index - b.index);
1663
+ for (const [, owner, repo, number] of hits) {
1664
+ const name = `${owner}/${repo}`;
1665
+ const key = `${name.toLowerCase()}#${number}`;
1666
+ if (!found.has(key)) found.set(key, { url: `https://github.com/${name}/pull/${number}`, repo: name, number: Number(number) });
1667
+ }
1668
+ }
1669
+ return [...found.values()];
1670
+ };
1671
+ var threadUsage = (thread) => thread.usage === void 0 ? void 0 : {
1672
+ totalCredits: thread.usage.totalCredits,
1673
+ llmCredits: thread.usage.llmCredits,
1674
+ vmCredits: thread.usage.vmCredits,
1675
+ imageCredits: thread.usage.imageCredits,
1676
+ cost: formatCredits(thread.usage.totalCredits)
1677
+ };
1678
+ var needsPerson = (thread) => thread.ask != null || thread.needsYou === true;
1679
+ var threadReport = (thread, messages, context) => {
1680
+ const reply = messages.findLast((m) => m.source === "assistant" && (m.text ?? "").trim() !== "")?.text?.trim();
1681
+ return {
1682
+ id: thread.id,
1683
+ title: thread.title ?? void 0,
1684
+ status: thread.status,
1685
+ where: context.target?.where,
1686
+ deviceId: context.target?.deviceId,
1687
+ projectId: thread.projectId ?? void 0,
1688
+ model: thread.lastModelId ?? void 0,
1689
+ lastReply: reply === void 0 ? void 0 : capReply(reply),
1690
+ pullRequests: pullRequestLinks(messages),
1691
+ asks: thread.ask == null ? [] : [{ kind: thread.ask.kind, text: thread.ask.text ?? void 0 }],
1692
+ needsYou: needsPerson(thread),
1693
+ usage: threadUsage(thread),
1694
+ url: threadUrl(context.origin, thread.id),
1695
+ note: context.target?.note
1696
+ };
1697
+ };
1698
+ var threadRow = (thread, projectName, origin) => ({
1699
+ id: thread.id,
1700
+ title: thread.title ?? void 0,
1701
+ status: thread.status,
1702
+ projectId: thread.projectId ?? void 0,
1703
+ projectName,
1704
+ model: thread.lastModelId ?? void 0,
1705
+ lastActivityAt: thread.lastActivityAt ?? thread.updatedAt ?? thread.createdAt ?? void 0,
1706
+ needsYou: needsPerson(thread),
1707
+ url: threadUrl(origin, thread.id)
1708
+ });
1709
+ var STATUS_LINES = {
1710
+ working: "Capy is working",
1711
+ waiting: "Capy is waiting",
1712
+ idle: "Capy is done",
1713
+ failed: "Capy reported that the run failed",
1714
+ archived: "The thread is archived"
1715
+ };
1716
+ var activityOf = (before, event, result) => {
1717
+ const out = [];
1718
+ if (event._tag === "Status" && event.status !== before.status && (event.status !== "idle" || before.active)) {
1719
+ out.push({ kind: "activity", text: STATUS_LINES[event.status] });
1720
+ }
1721
+ for (const update of result.updates) {
1722
+ if (update.sessionUpdate === "agent_message_chunk") {
1723
+ if (update.content.type === "text" && update.content.text !== "") out.push({ kind: "reply", text: update.content.text });
1724
+ continue;
1725
+ }
1726
+ if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") continue;
1727
+ const title = update.title ?? result.state.tools.get(update.toolCallId)?.title ?? "a tool call";
1728
+ if (update.toolCallId.startsWith(subagentCallId(""))) {
1729
+ const verb = update.status === "completed" ? "finished" : update.status === "failed" ? "failed" : update.status === "in_progress" ? "started" : void 0;
1730
+ if (verb !== void 0) out.push({ kind: "activity", text: `${title} ${verb}` });
1731
+ } else if (update.status === "completed") {
1732
+ out.push({ kind: "activity", text: `ran ${title}` });
1733
+ } else if (update.status === "failed") {
1734
+ out.push({ kind: "activity", text: `stopped: ${title}` });
1735
+ }
1736
+ }
1737
+ return out;
1738
+ };
1739
+ var effectiveReasoning = (reasoning, modes) => modes.includes(reasoning) ? reasoning : modes.at(-1);
1740
+ var isNotLinked = (error) => error._tag === "CapyApiError" && /does not link a folder/i.test(error.message);
1741
+ var remoteWorktree = (deviceId, projectId, repo) => ({
1742
+ projectId,
1743
+ target: {
1744
+ where: "worktree",
1745
+ deviceId,
1746
+ note: `Capy works in a new git worktree of ${repo} on the Capy device ${deviceId}, started from the GitHub remote. Nothing on this computer changes.`
1747
+ },
1748
+ device: { deviceId, workspace: { kind: "worktree", repos: [repo], startFromOrigin: true } },
1749
+ machineSize: void 0,
1750
+ notLinked: void 0
1751
+ });
1752
+ var cloudPlacement = (projectId, machineSize) => ({
1753
+ projectId,
1754
+ target: {
1755
+ where: "cloud",
1756
+ deviceId: void 0,
1757
+ note: `Capy runs this thread on a ${machineSize === void 0 ? "cloud machine of the project's size" : `${machineSize} cloud machine`}. ${CLOUD_COST}`
1758
+ },
1759
+ device: void 0,
1760
+ machineSize,
1761
+ notLinked: void 0
1762
+ });
1763
+ var answered = (messages, sent) => {
1764
+ const mine = sent.clientKey === void 0 ? 0 : messages.findIndex((m) => m.source === "user" && m.clientKey === sent.clientKey);
1765
+ return mine >= 0 && messages.slice(mine).some((m) => m.source === "assistant");
1766
+ };
1767
+ var makeDelegate = (config2) => {
1768
+ const origin = webOrigin(config2.apiUrl);
1769
+ const known = /* @__PURE__ */ new Map();
1770
+ const remember = (threadId, entry) => known.set(threadId, { ...known.get(threadId), ...entry });
1771
+ const problem = (context = {}) => (error) => new DelegateError({ problem: toProblem(config2, error, context) });
1772
+ const findProject = (projects, name) => Option2.fromNullishOr(projects.find((p) => p.id === name) ?? projects.find((p) => p.name === name));
1773
+ const local = (read) => Effect2.tryPromise({ try: read, catch: problem() });
1774
+ const place = (input) => Effect2.gen(function* () {
1775
+ const capy = yield* CapyClient;
1776
+ const folder = input.folder ?? process.cwd();
1777
+ const choice = input.where ?? "auto";
1778
+ if (input.machineSize !== void 0 && choice !== "cloud") return yield* fail(machineSizeNeedsCloud());
1779
+ const projects = yield* capy.listProjects.pipe(Effect2.mapError(problem()));
1780
+ let chosen;
1781
+ if (input.project !== void 0) {
1782
+ const found = findProject(projects, input.project);
1783
+ if (Option2.isNone(found)) return yield* fail(projectNotFound(input.project, projects));
1784
+ chosen = found.value;
1785
+ }
1786
+ const scoped = chosen === void 0 ? projects : [chosen];
1787
+ if (choice === "cloud" && chosen !== void 0) return cloudPlacement(chosen.id, input.machineSize);
1788
+ const git = yield* local(() => readGit(folder));
1789
+ const defaultNotRepo = input.folder !== void 0 ? void 0 : git.gitRoot === void 0 ? notGit(folder) : git.repos.length === 0 ? noGitHubRemote(git.gitRoot) : void 0;
1790
+ const fromRemote = () => resolveWorkspace({ cwd: folder, ...git, linked: [], projects: scoped, mode: "linked", allowWorktreeFallback: false });
1791
+ if (choice === "cloud") {
1792
+ const resolution = fromRemote();
1793
+ if (resolution._tag === "Unresolved") return yield* fail(chooseProject(projects, resolution.problem));
1794
+ return cloudPlacement(resolution.value.projectId, input.machineSize);
1795
+ }
1796
+ const device = yield* Effect2.result(local(() => readDevice(config2)));
1797
+ const linked = yield* local(() => readLinkedFolders(config2));
1798
+ if (choice === "here") {
1799
+ if (input.device === void 0 && Result.isFailure(device)) return yield* fail(actionable(device.failure.problem));
1800
+ const deviceId = input.device ?? (Result.isSuccess(device) ? device.success.id : "");
1801
+ const kind = Result.isSuccess(device) && device.success.id === deviceId ? device.success.kind : void 0;
1802
+ const resolution = resolveWorkspace({ cwd: folder, ...git, linked, projects: scoped, mode: "linked", allowWorktreeFallback: false, device: kind, product: config2.product });
1803
+ if (resolution._tag === "Unresolved") {
1804
+ return yield* fail(defaultNotRepo === void 0 ? actionable(resolution.problem) : passFolder(folder, defaultNotRepo, config2.product));
1805
+ }
1806
+ const { projectId, workspace } = resolution.value;
1807
+ const root = workspace.kind === "linked" ? workspace.root : folder;
1808
+ return {
1809
+ projectId,
1810
+ target: { where: "here", deviceId, note: `Capy edits ${root} in place.` },
1811
+ device: { deviceId, workspace },
1812
+ machineSize: void 0,
1813
+ notLinked: resolution.value.notLinked
1814
+ };
1815
+ }
1816
+ let cause;
1817
+ if (Result.isFailure(device)) {
1818
+ cause = device.failure.problem;
1819
+ } else if (input.device !== void 0 && input.device !== device.success.id) {
1820
+ cause = { title: "Use the device you named", detail: `The device ${input.device} is not this computer's.`, steps: [] };
1821
+ } else {
1822
+ const resolution = resolveWorkspace({
1823
+ cwd: folder,
1824
+ ...git,
1825
+ linked,
1826
+ projects: scoped,
1827
+ mode: "worktree",
1828
+ allowWorktreeFallback: true,
1829
+ device: device.success.kind
1830
+ });
1831
+ if (resolution._tag === "Resolved") {
1832
+ return {
1833
+ projectId: resolution.value.projectId,
1834
+ target: {
1835
+ where: "worktree",
1836
+ deviceId: device.success.id,
1837
+ note: "Capy works in its own git worktree on this computer (under ~/.capy/worktrees by default), not in your folder."
1838
+ },
1839
+ device: { deviceId: device.success.id, workspace: { kind: "worktree" } },
1840
+ machineSize: void 0,
1841
+ notLinked: void 0
1842
+ };
1843
+ }
1844
+ cause = resolution.problem;
1845
+ }
1846
+ const remoteId = input.device ?? config2.deviceIdOverride;
1847
+ if (remoteId === void 0) return yield* fail(defaultNotRepo === void 0 ? noDeviceTarget(cause, config2.product) : passFolder(folder, defaultNotRepo, config2.product));
1848
+ let project = chosen;
1849
+ let repo = input.repo?.toLowerCase();
1850
+ if (project === void 0) {
1851
+ const resolution = fromRemote();
1852
+ if (resolution._tag === "Unresolved") return yield* fail(chooseProject(projects, resolution.problem));
1853
+ project = projects.find((p) => p.id === resolution.value.projectId);
1854
+ repo ??= resolution.value.repo;
1855
+ }
1856
+ const names = project.repos.map((r) => r.repoFullName);
1857
+ repo ??= git.repos.find((r) => names.some((name) => name.toLowerCase() === r));
1858
+ const repoName = repo === void 0 ? names.length === 1 ? names[0] : void 0 : names.find((name) => name.toLowerCase() === repo);
1859
+ if (repoName === void 0) return yield* fail(chooseRepo(project, input.repo));
1860
+ return remoteWorktree(remoteId, project.id, repoName);
1861
+ });
1862
+ const modelFor = (input) => Effect2.gen(function* () {
1863
+ const modelId = input.model;
1864
+ if (modelId === void 0) return input.reasoning === void 0 ? void 0 : yield* fail(reasoningNeedsModel());
1865
+ if (input.reasoning !== void 0) return { modelId, reasoningMode: input.reasoning };
1866
+ const models = yield* CapyClient.use((capy) => capy.listModels).pipe(Effect2.orElseSucceed(() => []));
1867
+ const reasoningMode = effectiveReasoning(config2.defaultReasoning, models.find((m) => m.id === modelId)?.reasoningModes ?? []);
1868
+ return reasoningMode === void 0 ? { modelId } : { modelId, reasoningMode };
1869
+ });
1870
+ const report = (threadId) => Effect2.gen(function* () {
1871
+ const capy = yield* CapyClient;
1872
+ const [thread, messages] = yield* Effect2.all([capy.getThread(threadId), capy.listMessages(threadId)], { concurrency: 2 });
1873
+ return threadReport(thread, messages, { target: known.get(threadId)?.target, origin });
1874
+ }).pipe(Effect2.mapError(problem({ threadId })));
1875
+ const start = (input) => Effect2.gen(function* () {
1876
+ const capy = yield* CapyClient;
1877
+ const placement = yield* place(input);
1878
+ const model = yield* modelFor(input);
1879
+ const deviceId = placement.device?.deviceId;
1880
+ const thread = yield* capy.createThread({
1881
+ requestId: randomUUID(),
1882
+ projectId: placement.projectId,
1883
+ title: input.title ?? titleOf(input.task),
1884
+ message: input.task,
1885
+ ...model === void 0 ? {} : { model },
1886
+ ...placement.device === void 0 ? {} : { device: placement.device },
1887
+ ...placement.machineSize === void 0 ? {} : { machineSize: placement.machineSize }
1888
+ }).pipe(
1889
+ Effect2.mapError(
1890
+ (error) => placement.notLinked !== void 0 && isNotLinked(error) ? new DelegateError({ problem: actionable(placement.notLinked) }) : problem(deviceId === void 0 ? {} : { deviceId })(error)
1891
+ )
1892
+ );
1893
+ remember(thread.id, { target: placement.target, sent: { clientKey: void 0, at: yield* Clock.currentTimeMillis } });
1894
+ return threadReport(thread, [], { target: placement.target, origin });
1895
+ });
1896
+ const send = (threadId, text, options = {}) => Effect2.gen(function* () {
1897
+ const capy = yield* CapyClient;
1898
+ const clientKey = randomUUID();
1899
+ yield* capy.sendMessage(threadId, { text, clientKey, delivery: options.interrupt === true ? "interrupt" : "queue" }).pipe(
1900
+ Effect2.mapError(problem({ threadId }))
1901
+ );
1902
+ remember(threadId, { sent: { clientKey, at: yield* Clock.currentTimeMillis } });
1903
+ return yield* report(threadId).pipe(
1904
+ Effect2.catch((error) => {
1905
+ const target = known.get(threadId)?.target;
1906
+ const unread = `Capy has the message, but ${config2.product.name} could not read the thread afterwards (${error.problem.title}: ${error.problem.detail.replace(/\.$/, "")}). Do not send the message again; follow the thread for the reply.`;
1907
+ return Effect2.succeed({
1908
+ ...threadReport({ id: threadId, status: "working" }, [], { target, origin }),
1909
+ note: target === void 0 ? unread : `${target.note} ${unread}`
1910
+ });
1911
+ })
1912
+ );
1913
+ });
1914
+ const stop = (threadId) => Effect2.gen(function* () {
1915
+ const capy = yield* CapyClient;
1916
+ yield* capy.interrupt(threadId).pipe(Effect2.mapError(problem({ threadId })));
1917
+ return yield* report(threadId);
1918
+ });
1919
+ const list = (options = {}) => Effect2.gen(function* () {
1920
+ const capy = yield* CapyClient;
1921
+ const limit = Math.max(1, Math.min(100, Math.floor(options.limit ?? 20)));
1922
+ const projects = yield* capy.listProjects.pipe(Effect2.mapError(problem()));
1923
+ let scoped = projects;
1924
+ if (options.project !== void 0) {
1925
+ const chosen = findProject(projects, options.project);
1926
+ if (Option2.isNone(chosen)) return yield* fail(projectNotFound(options.project, projects));
1927
+ scoped = [chosen.value];
1928
+ } else if (options.folder !== void 0) {
1929
+ const git = yield* local(() => readGit(options.folder));
1930
+ const resolution = resolveWorkspace({ cwd: options.folder, ...git, linked: [], projects, mode: "linked", allowWorktreeFallback: false });
1931
+ if (resolution._tag === "Resolved") scoped = projects.filter((p) => p.id === resolution.value.projectId);
1932
+ }
1933
+ const pages = yield* Effect2.forEach(
1934
+ scoped,
1935
+ (project) => capy.listThreads(project.id, { limit }).pipe(Effect2.map((threads) => threads.map((t) => threadRow(t, project.name, origin)))),
1936
+ { concurrency: 4 }
1937
+ ).pipe(Effect2.mapError(problem()));
1938
+ return pages.flat().sort((a, b) => (b.lastActivityAt ?? "").localeCompare(a.lastActivityAt ?? "")).slice(0, limit);
1939
+ });
1940
+ const wait = (threadId, options) => Effect2.gen(function* () {
1941
+ const capy = yield* CapyClient;
1942
+ const emit = (activity) => {
1943
+ const result2 = options.onActivity?.(activity);
1944
+ return Effect2.isEffect(result2) ? result2 : Effect2.void;
1945
+ };
1946
+ const messages = yield* capy.listMessages(threadId).pipe(Effect2.mapError(problem({ threadId })));
1947
+ const cursor = messages.findLast((m) => m.source !== "tool" && EVENT_ID.test(m.id))?.id;
1948
+ const sent = known.get(threadId)?.sent;
1949
+ const now = yield* Clock.currentTimeMillis;
1950
+ const pickupBy = messages.length === 0 ? now + PICKUP_MS : sent !== void 0 && now - sent.at < PICKUP_MS && !answered(messages, sent) ? sent.at + PICKUP_MS : void 0;
1951
+ let state = initialTurn(cursor);
1952
+ let received = 0;
1953
+ let failures = 0;
1954
+ let emptyReads = 0;
1955
+ let idleRechecks = 0;
1956
+ let notStarted = false;
1957
+ const apply = (event) => Effect2.gen(function* () {
1958
+ if (event._tag !== "Heartbeat") received++;
1959
+ const before = state;
1960
+ const result2 = step(state, event);
1961
+ state = result2.state;
1962
+ yield* Effect2.forEach(activityOf(before, event, result2), emit, { discard: true });
1963
+ return result2.signal;
1964
+ });
1965
+ const readOnce = (live) => {
1966
+ let endedAt;
1967
+ return capy.stream(threadId, { cursor: state.cursor, untilRun: !live }).pipe(
1968
+ Stream2.mapEffect(apply),
1969
+ Stream2.takeUntil((signal) => {
1970
+ if (signal?._tag === "Ended") endedAt ??= Date.now();
1971
+ if (signal?._tag === "Failed" || signal?._tag === "Archived") return true;
1972
+ if (live) return signal !== void 0 && signal._tag !== "Waiting";
1973
+ return endedAt !== void 0 && Date.now() - endedAt > END_GRACE_MS;
1974
+ }),
1975
+ Stream2.runDrain
1976
+ );
1977
+ };
1978
+ const recover = (error) => {
1979
+ const badCursor = error._tag === "CapyApiError" && error.status === 400 && /cursor/i.test(error.message);
1980
+ if (badCursor && state.cursor !== void 0) {
1981
+ state = { ...state, cursor: void 0 };
1982
+ return Effect2.void;
1983
+ }
1984
+ if (!isTransient(error) || ++failures > MAX_FAILURES) return Effect2.fail(problem({ threadId })(error));
1985
+ return Effect2.sleep(backoff(failures));
1986
+ };
1987
+ const follow = Effect2.gen(function* () {
1988
+ let live = false;
1989
+ for (; ; ) {
1990
+ const seen = received;
1991
+ const read = yield* Effect2.result(readOnce(live));
1992
+ if (received > seen) failures = 0;
1993
+ if (Result.isFailure(read)) {
1994
+ yield* recover(read.failure);
1995
+ continue;
1996
+ }
1997
+ const checked = yield* Effect2.result(capy.getThread(threadId));
1998
+ if (Result.isFailure(checked)) {
1999
+ yield* recover(checked.failure);
2000
+ continue;
2001
+ }
2002
+ const thread = checked.success;
2003
+ live = false;
2004
+ switch (thread.status) {
2005
+ case "failed":
2006
+ case "archived":
2007
+ return;
2008
+ case "idle":
2009
+ if (state.active) {
2010
+ if (turnComplete(state)) return;
2011
+ if (++idleRechecks > MAX_IDLE_RECHECKS) return;
2012
+ yield* Effect2.sleep(Duration2.seconds(1));
2013
+ break;
2014
+ }
2015
+ if (pickupBy === void 0) return;
2016
+ if ((yield* Clock.currentTimeMillis) >= pickupBy) {
2017
+ const latest = yield* Effect2.result(capy.listMessages(threadId));
2018
+ notStarted = !(Result.isSuccess(latest) && sent !== void 0 && answered(latest.success, sent));
2019
+ return;
2020
+ }
2021
+ yield* Effect2.sleep(backoff(Math.min(++idleRechecks, 3)));
2022
+ break;
2023
+ case "waiting":
2024
+ if (needsPerson(thread)) return;
2025
+ live = true;
2026
+ // falls through
2027
+ case "working":
2028
+ emptyReads = received > seen ? 0 : emptyReads + 1;
2029
+ if (emptyReads > 0) yield* Effect2.sleep(backoff(Math.min(emptyReads, 4)));
2030
+ break;
2031
+ }
2032
+ }
2033
+ });
2034
+ const finished = yield* follow.pipe(Effect2.timeoutOption(Duration2.millis(Math.max(0, options.timeoutMs))));
2035
+ if (state.active) remember(threadId, { sent: void 0 });
2036
+ const result = yield* report(threadId);
2037
+ return notStarted ? { ...result, lastReply: void 0, timedOut: false, notStarted } : { ...result, timedOut: Option2.isNone(finished), notStarted };
2038
+ });
2039
+ return { start, report, wait, send, stop, list };
2040
+ };
2041
+
2042
+ // src/version.ts
2043
+ import { readFileSync } from "node:fs";
2044
+ var AGENT_NAME = "capy-mcp-server";
2045
+ var AGENT_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
2046
+ var PRODUCT = {
2047
+ name: AGENT_NAME,
2048
+ kind: "mcp",
2049
+ env: "this MCP server's env (the `env` of its entry in the MCP client's config)",
2050
+ version: AGENT_VERSION,
2051
+ setup: "npx -y capy-mcp-server --setup",
2052
+ // The server has no doctor and no thread list of its own; capy-cli has both, with the same API key.
2053
+ // forTools (mcp.ts) points a calling agent at list_threads instead of this command.
2054
+ doctor: "npx -y capy-cli doctor",
2055
+ threads: "npx -y capy-cli threads",
2056
+ latest: "npx -y capy-mcp-server@latest"
2057
+ };
2058
+
2059
+ // src/mcp.ts
2060
+ var SERVER_NAME = "capy";
2061
+ var HELP = `${AGENT_NAME} ${AGENT_VERSION}: an MCP server named "capy", so agents such as Claude Code, Codex and Cursor
2062
+ can start Capy coding-agent threads, wait for them and read their results.
2063
+ A community project. Not made, endorsed or supported by Capy.
2064
+
2065
+ Usage:
2066
+ npx -y capy-mcp-server Start the MCP server on stdio. Your MCP client runs this.
2067
+ npx -y capy-mcp-server --setup Save ${SHARED_KEY}, and set up a Capy device.
2068
+ npx -y capy-mcp-server --version
2069
+ npx -y capy-mcp-server --help
2070
+
2071
+ Add it to an agent, for example:
2072
+ claude mcp add capy -- npx -y capy-mcp-server
2073
+
2074
+ It reads the key from CAPY_API_KEY, else from ~/.config/capy-acp/api-key.
2075
+ Docs: https://github.com/yazcaleb/capy-acp/tree/main/packages/mcp#readme
2076
+ `;
2077
+ var INSTRUCTIONS = `Capy runs coding-agent threads on a Capy device (a computer that runs the Capy desktop app or \`capy dock\`) or on a Capy cloud machine. Use these tools to hand work to Capy and to come back for the result.
2078
+
2079
+ Delegate to Capy when the work is independent of what you do now, when it is long, when several tasks can run in parallel, when it should end in a pull request, or when it should keep going after this session ends. Do small edits that you need right away yourself.
2080
+
2081
+ By default (where "auto"), start_thread runs the task in a new git worktree of the repository on a Capy device. It does not edit your files, so you can keep working in the folder while Capy works. where "here" edits the folder in place: use it only when the person asks for it. where "cloud" runs on a Capy cloud machine, and machine time costs Capy credits: use it only when the person allows it.
2082
+
2083
+ After start_thread or send_message, call wait_for_thread with the thread id. Do not call get_thread in a loop. wait_for_thread returns when the run ends, when Capy needs a person, or when its timeout passes. After a timeout the thread keeps running, so call wait_for_thread again. When a result has needsYou true or asks, ask the person and pass the answer to send_message.
2084
+
2085
+ Every error result has a nextAction: run_command (run that exact command), ask_human (ask the person exactly that), retry (wait afterMs milliseconds, then call again), or use_option (call again with another value for that option).`;
2086
+ var WHERE_CHOICES = ["auto", "worktree", "here", "cloud"];
2087
+ var described = (schema, description) => schema.annotate({ description });
2088
+ var optional = (schema, description) => Schema3.optionalKey(described(schema, description));
2089
+ var Text = Schema3.String.check(Schema3.isMinLength(1));
2090
+ var ThreadId = described(Text, "The thread id that start_thread or list_threads returned, such as jam_01K...");
2091
+ var StartInput = Schema3.Struct({
2092
+ task: described(
2093
+ Text,
2094
+ "What Capy should do, written as for a capable engineer: the goal, where in the code, and how to check the result. Say whether Capy should open a pull request."
2095
+ ),
2096
+ folder: optional(
2097
+ Text,
2098
+ "The absolute path of a folder in the git repository to work on. Default: this MCP server's working folder, which is often not your repository, so pass it whenever you work in a repository."
2099
+ ),
2100
+ where: optional(
2101
+ Schema3.Literals(WHERE_CHOICES),
2102
+ 'Where Capy runs. "auto" (default) and "worktree": a new git worktree on a Capy device, which never edits your folder. "here": edits the folder in place, only when the person asks. "cloud": a Capy cloud machine, whose time costs Capy credits, only when the person allows it.'
2103
+ ),
2104
+ project: optional(Text, "A Capy project id or exact name. Default: the project of the folder's GitHub remote."),
2105
+ repo: optional(Text, `A repository "owner/name", for a worktree on a Capy device on another computer. Default: the folder's repository, else the project's only one.`),
2106
+ device: optional(Text, "A Capy device id, to run on a Capy device on another computer. Default: CAPY_DEVICE_ID, else this computer's device."),
2107
+ machineSize: optional(
2108
+ Schema3.Literals(MACHINE_SIZES),
2109
+ `Cloud machine size, for where "cloud" only. Default: the project's machine size. Bigger machines cost more credits.`
2110
+ ),
2111
+ model: optional(Text, "A model id from list_models. Default: the default model of the Capy account that owns the API key, else the organization's."),
2112
+ reasoning: optional(Text, "A reasoning mode of the model, such as low, medium or high (see list_models). Needs model. Default: high, or the model's highest."),
2113
+ title: optional(Text, "The thread title. Default: the start of the task.")
2114
+ });
2115
+ var WaitInput = Schema3.Struct({
2116
+ threadId: ThreadId,
2117
+ timeoutSeconds: optional(
2118
+ Schema3.Int.check(Schema3.isBetween({ minimum: 1, maximum: 600 })),
2119
+ "How long to wait before returning with timedOut true, from 1 to 600. Default: 120. The thread keeps running after the timeout."
2120
+ )
2121
+ });
2122
+ var ThreadInput = Schema3.Struct({ threadId: ThreadId });
2123
+ var SendInput = Schema3.Struct({
2124
+ threadId: ThreadId,
2125
+ text: described(Text, "The message: an answer to Capy's question, or follow-up work."),
2126
+ interrupt: optional(Schema3.Boolean, "true stops the current run and starts on this message now. Default: false, the message waits until the current run ends.")
2127
+ });
2128
+ var ListInput = Schema3.Struct({
2129
+ project: optional(Text, "Only threads of this Capy project (id or exact name)."),
2130
+ folder: optional(Text, "Only threads of the Capy project of this folder's repository."),
2131
+ limit: optional(Schema3.Int.check(Schema3.isBetween({ minimum: 1, maximum: 100 })), "How many threads, from 1 to 100. Default: 20.")
2132
+ });
2133
+ var NoInput = Schema3.Struct({});
2134
+ var inputSchemaOf = (schema) => {
2135
+ const { additionalProperties: _, ...json } = Schema3.toJsonSchemaDocument(schema).schema;
2136
+ return json.type === "object" ? json : { type: "object", properties: {} };
2137
+ };
2138
+ var nextActionText = (next) => {
2139
+ switch (next.kind) {
2140
+ case "run_command":
2141
+ return `Run \`${next.command}\`.`;
2142
+ case "ask_human":
2143
+ return next.say;
2144
+ case "retry":
2145
+ return `Try again in ${Math.ceil(next.afterMs / 1e3)} seconds.`;
2146
+ case "use_option":
2147
+ return `Call again with another ${next.option}. ${next.why}`;
2148
+ }
2149
+ };
2150
+ var problemText = (problem) => [
2151
+ `${problem.title}. ${problem.detail}`,
2152
+ ...problem.steps.map((step2, i) => `${i + 1}. ${step2}`),
2153
+ `Next: ${nextActionText(problem.nextAction)}`
2154
+ ].join("\n");
2155
+ var forTools = (problem) => problem.nextAction.kind === "run_command" && problem.nextAction.command === PRODUCT.threads ? { ...problem, nextAction: { kind: "use_option", option: "threadId", why: "Use an id from list_threads." } } : problem;
2156
+ var errorResult = (failure) => {
2157
+ const problem = forTools(failure);
2158
+ return new McpSchema.CallToolResult({
2159
+ isError: true,
2160
+ content: [{ type: "text", text: problemText(problem) }],
2161
+ structuredContent: { error: { title: problem.title, detail: problem.detail, steps: problem.steps }, nextAction: problem.nextAction }
2162
+ });
2163
+ };
2164
+ var okResult = (answer) => new McpSchema.CallToolResult({
2165
+ isError: false,
2166
+ content: [{ type: "text", text: answer.text }],
2167
+ structuredContent: JSON.parse(JSON.stringify(answer.structured))
2168
+ });
2169
+ var invalidInput = (tool, error) => {
2170
+ const option = /at \["([^"]+)"\]/.exec(error.message)?.[1] ?? "arguments";
2171
+ return {
2172
+ title: "Fix the tool arguments",
2173
+ detail: `The ${tool} arguments do not match its input schema: ${error.message.replace(/\s+/g, " ").trim()}.`,
2174
+ steps: [`Call ${tool} again with arguments that match its input schema.`],
2175
+ nextAction: { kind: "use_option", option, why: error.message.replace(/\s+/g, " ").trim() }
2176
+ };
2177
+ };
2178
+ var statusLine = (report) => `Thread ${report.id}${report.title === void 0 ? "" : ` "${report.title}"`} is ${report.status}.`;
2179
+ var waitNext = (id) => `Call wait_for_thread with threadId "${id}" to follow the run.`;
2180
+ var nextStep = (report, timedOut, notStarted) => {
2181
+ if (notStarted) {
2182
+ return `Capy has not started on the message yet, and it stays in the queue. Check that the Capy device runs (or the cloud machine starts), then call wait_for_thread with threadId "${report.id}" again. Do not send the message again.`;
2183
+ }
2184
+ if (report.needsYou || report.asks.length > 0) return `Ask the person what Capy needs, then pass the answer to send_message with threadId "${report.id}".`;
2185
+ if (timedOut) return `The wait timed out and the thread keeps running. ${waitNext(report.id)}`;
2186
+ switch (report.status) {
2187
+ case "working":
2188
+ case "waiting":
2189
+ return waitNext(report.id);
2190
+ case "idle":
2191
+ return "The run is done. Review the last reply and any pull request. For more work on it, call send_message.";
2192
+ case "failed":
2193
+ return "The run failed. Read the last reply, then call send_message to try again or to change course.";
2194
+ case "archived":
2195
+ return "The thread is archived. Start a new thread for more work.";
2196
+ }
2197
+ };
2198
+ var reportText = (report, options = {}) => {
2199
+ const lines = [options.lead ?? (options.notStarted === true ? `Thread ${report.id}: Capy has not started on the message yet.` : statusLine(report))];
2200
+ if (report.note !== void 0) lines.push(report.note);
2201
+ if (report.model !== void 0) lines.push(`Model: ${report.model}.`);
2202
+ for (const ask of report.asks) lines.push(`Capy needs a person (${ask.kind})${ask.text === void 0 ? "." : `: ${ask.text}`}`);
2203
+ if (report.needsYou && report.asks.length === 0) lines.push("Capy needs a person to look at the thread.");
2204
+ if (report.pullRequests.length > 0) lines.push(`Pull requests: ${report.pullRequests.map((pr) => pr.url).join(", ")}`);
2205
+ if (report.usage !== void 0) lines.push(`Credits used so far: ${report.usage.cost}.`);
2206
+ if (report.url !== void 0) lines.push(`Open in Capy: ${report.url}`);
2207
+ lines.push(`Next: ${options.next ?? nextStep(report, options.timedOut === true, options.notStarted === true)}`);
2208
+ if (report.lastReply !== void 0) lines.push("", "Last reply from Capy:", report.lastReply);
2209
+ return lines.join("\n");
2210
+ };
2211
+ var rowsText = (rows) => rows.length === 0 ? "No Capy threads found." : rows.map(
2212
+ (row) => [
2213
+ `${row.id} [${row.status}${row.needsYou ? ", needs a person" : ""}]`,
2214
+ row.title ?? "(no title)",
2215
+ row.projectName === void 0 ? void 0 : `project ${row.projectName}`,
2216
+ row.lastActivityAt === void 0 ? void 0 : `last activity ${row.lastActivityAt}`
2217
+ ].filter((part) => part !== void 0).join(" \xB7 ")
2218
+ ).join("\n");
2219
+ var DEFAULT_MODEL_NOTE = "Leave model out to use the default model of the Capy account that owns the API key (its own default, else the organization's).";
2220
+ var modelRows = (models, prices) => models.map((m) => ({
2221
+ id: m.id,
2222
+ name: m.name,
2223
+ route: m.route,
2224
+ billing: m.billing,
2225
+ reasoningModes: m.reasoningModes ?? [],
2226
+ price: modelDescription(m, prices.get(m.id))
2227
+ }));
2228
+ var modelsText = (rows) => rows.length === 0 ? "Capy lists no models for this API key." : rows.map(
2229
+ (m) => [
2230
+ `${m.id}: ${m.name}`,
2231
+ m.reasoningModes.length === 0 ? void 0 : `reasoning ${m.reasoningModes.join("/")}`,
2232
+ m.price
2233
+ ].filter((part) => part !== void 0).join(" \xB7 ")
2234
+ ).join("\n");
2235
+ var REPLY_CHUNK = 300;
2236
+ var progressToken = McpSchema.McpRequestContext.useSync(({ requestMetadata }) => {
2237
+ const token = Predicate.hasProperty(requestMetadata, "progressToken") ? requestMetadata.progressToken : void 0;
2238
+ return typeof token === "string" || typeof token === "number" ? token : void 0;
2239
+ });
2240
+ var registrations = (config2) => Layer2.effectDiscard(
2241
+ Effect3.gen(function* () {
2242
+ const server = yield* McpServer.McpServer;
2243
+ const capy = yield* Effect3.context();
2244
+ const delegate = makeDelegate(config2);
2245
+ let prices;
2246
+ const register = (spec) => server.addTool({
2247
+ tool: new McpSchema.Tool({
2248
+ name: spec.name,
2249
+ title: spec.title,
2250
+ description: spec.description,
2251
+ inputSchema: inputSchemaOf(spec.input),
2252
+ annotations: {
2253
+ title: spec.title,
2254
+ readOnlyHint: spec.hints.readOnly,
2255
+ destructiveHint: spec.hints.destructive,
2256
+ idempotentHint: spec.hints.idempotent,
2257
+ openWorldHint: true
2258
+ }
2259
+ }),
2260
+ annotations: Context2.empty(),
2261
+ handle: (payload) => Schema3.decodeUnknownEffect(spec.input)(payload ?? {}, { errors: "all", onExcessProperty: "ignore" }).pipe(
2262
+ Effect3.mapError((error) => new DelegateError({ problem: invalidInput(spec.name, error) })),
2263
+ Effect3.flatMap(spec.run),
2264
+ Effect3.map(okResult),
2265
+ // Typed failures and defects become results; an interruption (a cancelled call) stays one.
2266
+ Effect3.catch((error) => Effect3.succeed(errorResult(toProblem(config2, error)))),
2267
+ Effect3.catchDefect((defect) => Effect3.succeed(errorResult(toProblem(config2, defect)))),
2268
+ Effect3.provideContext(capy)
2269
+ )
2270
+ });
2271
+ yield* register({
2272
+ name: "start_thread",
2273
+ title: "Start a Capy thread",
2274
+ description: `Start a Capy thread on a coding task and return at once, without waiting for the result. By default (where "auto") Capy works in a new git worktree of the folder's repository on a Capy device, so your files do not change. Returns the thread report: id, status, where it runs, and a link to the thread in Capy. Next, call wait_for_thread with the id. Cost: the run uses the chosen model, on Capy credits or the person's own subscription. where "cloud" also costs Capy credits for machine time.`,
2275
+ input: StartInput,
2276
+ hints: { readOnly: false, destructive: false, idempotent: false },
2277
+ run: (input) => (
2278
+ // Without a folder, delegate uses the working folder and knows that none was given.
2279
+ delegate.start({ ...input, folder: input.folder === void 0 ? void 0 : resolve2(input.folder) }).pipe(
2280
+ Effect3.map((report) => ({
2281
+ text: reportText(report, { lead: `Started Capy thread ${report.id}${report.title === void 0 ? "" : ` "${report.title}"`}.`, next: waitNext(report.id) }),
2282
+ structured: report
2283
+ }))
2284
+ )
2285
+ )
2286
+ });
2287
+ yield* register({
2288
+ name: "wait_for_thread",
2289
+ title: "Wait for a Capy thread",
2290
+ description: "Wait until a Capy thread's run ends, then return its report: status, last reply, pull requests, what Capy needs from a person (asks, needsYou) and credits used. Returns early when Capy needs a person, the run fails, or the thread is archived. When timeoutSeconds passes first, it returns timedOut true and the thread keeps running: call it again. Sends progress notifications with short activity lines when the call has a progress token. Cancelling the call stops the wait, never the thread. Changes nothing. If your client ends tool calls sooner than timeoutSeconds, pass a smaller timeoutSeconds.",
2291
+ input: WaitInput,
2292
+ hints: { readOnly: true, destructive: false, idempotent: true },
2293
+ run: (input) => Effect3.gen(function* () {
2294
+ const token = yield* progressToken;
2295
+ let progress = 0;
2296
+ let reply = "";
2297
+ const notify = (message) => token === void 0 ? Effect3.void : server.notifications["notifications/progress"]({ progressToken: token, progress: ++progress, message }).pipe(Effect3.ignore);
2298
+ const flush = () => {
2299
+ const text = reply.replace(/\s+/g, " ").trim();
2300
+ reply = "";
2301
+ return text === "" ? Effect3.void : notify(`Capy: ${text}`);
2302
+ };
2303
+ const onActivity = (activity) => {
2304
+ if (activity.kind === "activity") return Effect3.andThen(flush(), notify(activity.text));
2305
+ reply += activity.text;
2306
+ return reply.length >= REPLY_CHUNK || activity.text.includes("\n") ? flush() : Effect3.void;
2307
+ };
2308
+ const result = yield* delegate.wait(input.threadId, { timeoutMs: (input.timeoutSeconds ?? 120) * 1e3, onActivity });
2309
+ yield* flush();
2310
+ return { text: reportText(result, { timedOut: result.timedOut, notStarted: result.notStarted }), structured: result };
2311
+ })
2312
+ });
2313
+ yield* register({
2314
+ name: "get_thread",
2315
+ title: "Read a Capy thread",
2316
+ description: "Read a Capy thread's report now, without waiting: status, last reply, pull requests, what Capy needs from a person (asks, needsYou), credits used, and a link. Changes nothing. To wait for a run to end, call wait_for_thread instead of calling this in a loop.",
2317
+ input: ThreadInput,
2318
+ hints: { readOnly: true, destructive: false, idempotent: true },
2319
+ run: (input) => delegate.report(input.threadId).pipe(Effect3.map((report) => ({ text: reportText(report), structured: report })))
2320
+ });
2321
+ yield* register({
2322
+ name: "send_message",
2323
+ title: "Message a Capy thread",
2324
+ description: "Send a message to a Capy thread: an answer to Capy's question, or follow-up work. By default the message waits until the current run ends; interrupt true stops the current run and starts on the message now. Returns the thread report; then call wait_for_thread. Cost: the message starts a Capy run, which uses the thread's model.",
2325
+ input: SendInput,
2326
+ hints: { readOnly: false, destructive: false, idempotent: false },
2327
+ run: (input) => delegate.send(input.threadId, input.text, { interrupt: input.interrupt }).pipe(
2328
+ Effect3.map((report) => ({ text: reportText(report, { lead: `Sent the message to thread ${report.id}.`, next: waitNext(report.id) }), structured: report }))
2329
+ )
2330
+ });
2331
+ yield* register({
2332
+ name: "stop_thread",
2333
+ title: "Stop a Capy thread's run",
2334
+ description: "Stop a Capy thread's current run. This interrupts the work in progress. The thread keeps its transcript and takes new messages. Returns the thread report. Use it when the person asks, or when the run clearly works on the wrong thing.",
2335
+ input: ThreadInput,
2336
+ hints: { readOnly: false, destructive: false, idempotent: true },
2337
+ run: (input) => delegate.stop(input.threadId).pipe(
2338
+ Effect3.map((report) => ({
2339
+ text: reportText(report, { lead: `Stopped the current run of thread ${report.id}.`, next: "To give Capy new instructions, call send_message." }),
2340
+ structured: report
2341
+ }))
2342
+ )
2343
+ });
2344
+ yield* register({
2345
+ name: "list_threads",
2346
+ title: "List Capy threads",
2347
+ description: "List recent Capy threads, newest first: id, title, status, project, model, last activity, whether Capy needs a person, and a link. Filter by project (id or exact name), or by the project of a folder's repository. Without either, it lists threads of every project. Changes nothing.",
2348
+ input: ListInput,
2349
+ hints: { readOnly: true, destructive: false, idempotent: true },
2350
+ run: (input) => delegate.list({ project: input.project, folder: input.folder === void 0 ? void 0 : resolve2(input.folder), limit: input.limit }).pipe(Effect3.map((threads) => ({ text: rowsText(threads), structured: { threads } })))
2351
+ });
2352
+ yield* register({
2353
+ name: "list_models",
2354
+ title: "List Capy models",
2355
+ description: `List the models Capy can run a thread with: id, name, billing route (route "capy" bills Capy credits; other routes bill the person's own subscription), reasoning modes, and a price note when Capy's docs list one. Pass an id as model to start_thread. Changes nothing.`,
2356
+ input: NoInput,
2357
+ hints: { readOnly: true, destructive: false, idempotent: true },
2358
+ run: () => Effect3.gen(function* () {
2359
+ const models = yield* CapyClient.use((client) => client.listModels).pipe(Effect3.mapError((error) => new DelegateError({ problem: toProblem(config2, error) })));
2360
+ const table = yield* Effect3.promise(
2361
+ () => prices ??= config2.pricingUrl === "" ? Promise.resolve(/* @__PURE__ */ new Map()) : fetchPrices(config2.pricingUrl).catch(() => /* @__PURE__ */ new Map())
2362
+ );
2363
+ const rows = modelRows(models, table);
2364
+ return { text: `${modelsText(rows)}
2365
+
2366
+ ${DEFAULT_MODEL_NOTE}`, structured: { models: rows, note: DEFAULT_MODEL_NOTE } };
2367
+ })
2368
+ });
2369
+ })
2370
+ );
2371
+ var PROTOCOLS = [McpProtocol.v2025_11_25, McpProtocol.v2025_06_18, McpProtocol.v2025_03_26, McpProtocol.v2024_11_05];
2372
+ var serverLayer = (config2, capy = layer(config2)) => McpServer.layerStdio({
2373
+ name: SERVER_NAME,
2374
+ version: AGENT_VERSION,
2375
+ instructions: INSTRUCTIONS,
2376
+ protocols: PROTOCOLS,
2377
+ registrations: registrations(config2).pipe(Layer2.provide(capy))
2378
+ });
2379
+ var stdioError = (method) => (cause) => PlatformError.systemError({ _tag: "Unknown", module: "Stdio", method, description: String(cause), cause });
2380
+ var write = (stream) => () => Sink.forEach(
2381
+ (chunk2) => Effect3.callback((resume) => {
2382
+ stream.write(chunk2, (error) => resume(error == null ? Effect3.void : Effect3.fail(stdioError("write")(error))));
2383
+ })
2384
+ );
2385
+ var nodeStdio = Layer2.succeed(
2386
+ Stdio.Stdio,
2387
+ Stdio.make({
2388
+ args: Effect3.sync(() => process.argv.slice(2)),
2389
+ stdin: Stream3.fromAsyncIterable(process.stdin, stdioError("stdin")),
2390
+ stdout: write(process.stdout),
2391
+ stderr: write(process.stderr)
2392
+ })
2393
+ );
2394
+ var runMcpServer = async (config2) => {
2395
+ if (process.stdin.isTTY) {
2396
+ process.stderr.write(`${HELP}
2397
+ This command is an MCP server on stdio: add it to your MCP client. It is waiting for MCP messages on stdin; press Ctrl+C to stop.
2398
+ `);
2399
+ }
2400
+ const server = Layer2.launch(serverLayer(config2).pipe(Layer2.provide(nodeStdio))).pipe(Effect3.provideService(Logger.LogToStderr, true));
2401
+ const exit = await Effect3.runPromiseExit(server);
2402
+ if (Exit.isFailure(exit) && !Cause2.hasInterruptsOnly(exit.cause)) throw Cause2.squash(exit.cause);
2403
+ };
2404
+
2405
+ // src/bin.ts
2406
+ var [command2] = process.argv.slice(2);
2407
+ var config = () => readConfig(process.env, PRODUCT);
2408
+ if (command2 === "--version" || command2 === "-v") {
2409
+ process.stdout.write(`${AGENT_NAME} ${AGENT_VERSION}
2410
+ `);
2411
+ process.exit(0);
2412
+ }
2413
+ if (command2 === "--help" || command2 === "-h") {
2414
+ process.stdout.write(HELP);
2415
+ process.exit(0);
2416
+ }
2417
+ if (command2 === "--setup") {
2418
+ const io = { readSecret: readSecretFromTerminal, write: (text) => void process.stdout.write(text), fetch };
2419
+ const code = await runSetup(config(), io).catch((error) => (process.stdout.write(`${String(error)}
2420
+ `), 1));
2421
+ if (code === 0) process.stdout.write("Next: add the server to your agent, for example `claude mcp add capy -- npx -y capy-mcp-server`.\n");
2422
+ process.exit(code);
2423
+ }
2424
+ if (command2 !== void 0) {
2425
+ process.stderr.write(`Unknown option: ${command2}
2426
+
2427
+ ${HELP}`);
2428
+ process.exit(2);
2429
+ }
2430
+ await runMcpServer(config());
2431
+ //# sourceMappingURL=bin.js.map