capy-acp 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +184 -2
- package/dist/agent.js +468 -0
- package/dist/agent.js.map +1 -0
- package/dist/bin.js +74 -0
- package/dist/bin.js.map +1 -0
- package/dist/capy/client.js +174 -0
- package/dist/capy/client.js.map +1 -0
- package/dist/capy/events.js +140 -0
- package/dist/capy/events.js.map +1 -0
- package/dist/changes.js +218 -0
- package/dist/changes.js.map +1 -0
- package/dist/config.js +41 -0
- package/dist/config.js.map +1 -0
- package/dist/doctor.js +102 -0
- package/dist/doctor.js.map +1 -0
- package/dist/pricing.js +60 -0
- package/dist/pricing.js.map +1 -0
- package/dist/problems.js +108 -0
- package/dist/problems.js.map +1 -0
- package/dist/prompt.js +101 -0
- package/dist/prompt.js.map +1 -0
- package/dist/setup.js +92 -0
- package/dist/setup.js.map +1 -0
- package/dist/sse.js +95 -0
- package/dist/sse.js.map +1 -0
- package/dist/store.js +85 -0
- package/dist/store.js.map +1 -0
- package/dist/translate.js +309 -0
- package/dist/translate.js.map +1 -0
- package/dist/turn.js +319 -0
- package/dist/turn.js.map +1 -0
- package/dist/version.js +5 -0
- package/dist/version.js.map +1 -0
- package/dist/workspace.js +164 -0
- package/dist/workspace.js.map +1 -0
- package/package.json +48 -4
package/dist/changes.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Observes what a Capy thread changes on disk, so ACP clients can show real diffs.
|
|
3
|
+
*
|
|
4
|
+
* Capy's stream names the tools a call ran but never the files or their contents (docs/capy-api-notes.md, ask
|
|
5
|
+
* 3). The thread works on this machine, in the folder the client has open (linked mode) or in its
|
|
6
|
+
* own git worktree, so the adapter can see the changes itself: it records the working tree when a turn
|
|
7
|
+
* starts, then diffs it as tool calls start and finish. Strictly read only: `git status`, `git rev-parse`,
|
|
8
|
+
* `git diff --name-only`, `git cat-file`, directory listings and plain file reads. Git LFS smudging is
|
|
9
|
+
* skipped, so a diff never downloads.
|
|
10
|
+
*
|
|
11
|
+
* Attribution is by time (see turn.ts): a change is credited to the tool call that ran when it happened.
|
|
12
|
+
*/
|
|
13
|
+
import { execFile } from "node:child_process";
|
|
14
|
+
import { createHash } from "node:crypto";
|
|
15
|
+
import { lstat, readdir, readFile, readlink } from "node:fs/promises";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { promisify } from "node:util";
|
|
18
|
+
import { Effect } from "effect";
|
|
19
|
+
const exec = promisify(execFile);
|
|
20
|
+
/** Above this a file is reported by path only: diffs this large don't help anyone in a chat view. */
|
|
21
|
+
export const MAX_PREVIEW_BYTES = 256 * 1024;
|
|
22
|
+
/** A turn that touches more files than this (a dependency install, a generator) reports the first ones. */
|
|
23
|
+
export const MAX_TRACKED_FILES = 500;
|
|
24
|
+
const MAX_GIT_OUTPUT = 64 * 1024 * 1024;
|
|
25
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
26
|
+
const toContent = (bytes) => {
|
|
27
|
+
const hash = createHash("sha256").update(bytes).digest("hex");
|
|
28
|
+
if (bytes.length > MAX_PREVIEW_BYTES || bytes.subarray(0, 8192).includes(0))
|
|
29
|
+
return { hash, text: undefined };
|
|
30
|
+
try {
|
|
31
|
+
return { hash, text: utf8.decode(bytes) };
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return { hash, text: undefined };
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
/** Above this a file is compared by size and modification time instead of being read. */
|
|
38
|
+
const MAX_READ_BYTES = 16 * 1024 * 1024;
|
|
39
|
+
/**
|
|
40
|
+
* A working-tree entry as git would see it. A symlink is its target path (what git stores), never
|
|
41
|
+
* the file it points at, which may be outside the folder. Special files and very large files are
|
|
42
|
+
* compared by metadata only and never shown.
|
|
43
|
+
*/
|
|
44
|
+
const readEntry = async (path) => {
|
|
45
|
+
const info = await lstat(path);
|
|
46
|
+
if (info.isSymbolicLink())
|
|
47
|
+
return toContent(Buffer.from(await readlink(path)));
|
|
48
|
+
if (info.isDirectory())
|
|
49
|
+
return undefined;
|
|
50
|
+
if (!info.isFile() || info.size > MAX_READ_BYTES) {
|
|
51
|
+
return { hash: `stat:${info.mode}:${info.size}:${info.mtimeMs}`, text: undefined };
|
|
52
|
+
}
|
|
53
|
+
return toContent(await readFile(path));
|
|
54
|
+
};
|
|
55
|
+
/** Thrown inside the tracker for reads that failed for a reason other than "not there". */
|
|
56
|
+
class Unreadable {
|
|
57
|
+
path;
|
|
58
|
+
_tag = "Unreadable";
|
|
59
|
+
constructor(path) {
|
|
60
|
+
this.path = path;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export const makeChangeTracker = (root, onError = () => { }) => trackFolder(root, onError);
|
|
64
|
+
/** A folder tracker, plus `fromHead`: a baseline for a folder known to have been clean at its HEAD. */
|
|
65
|
+
const trackFolder = (root, onError) => {
|
|
66
|
+
let head;
|
|
67
|
+
let known = new Map();
|
|
68
|
+
/** Set when a baseline could not be taken; the turn then reports no changes rather than wrong ones. */
|
|
69
|
+
let disabled = false;
|
|
70
|
+
const git = (args) => Effect.tryPromise({
|
|
71
|
+
try: () => exec("git", ["-C", root, ...args], {
|
|
72
|
+
encoding: "buffer",
|
|
73
|
+
maxBuffer: MAX_GIT_OUTPUT,
|
|
74
|
+
timeout: 15_000,
|
|
75
|
+
env: { ...process.env, GIT_LFS_SKIP_SMUDGE: "1" }
|
|
76
|
+
}),
|
|
77
|
+
catch: (error) => error
|
|
78
|
+
}).pipe(Effect.map(({ stdout }) => stdout));
|
|
79
|
+
const readHead = git(["rev-parse", "--verify", "--quiet", "HEAD"]).pipe(Effect.map((out) => out.toString("utf8").trim() || undefined),
|
|
80
|
+
// A repository with no commits yet has no HEAD.
|
|
81
|
+
Effect.orElseSucceed(() => undefined));
|
|
82
|
+
/** Paths git reports as changed or untracked (ignored files excluded), relative to the root. */
|
|
83
|
+
const dirtyPaths = git(["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"]).pipe(Effect.map((out) => out
|
|
84
|
+
.toString("utf8")
|
|
85
|
+
.split("\0")
|
|
86
|
+
.filter((entry) => entry.length > 3)
|
|
87
|
+
.map((entry) => entry.slice(3))));
|
|
88
|
+
const committedPaths = (from, to) => git(["diff", "--name-only", "-z", "--no-renames", from, to]).pipe(Effect.map((out) => out.toString("utf8").split("\0").filter((path) => path.length > 0)));
|
|
89
|
+
const catFile = (mode, commit, path) => git(["cat-file", mode, `${commit}:${path}`]).pipe(Effect.map(toContent), Effect.orElseSucceed(() => undefined));
|
|
90
|
+
/**
|
|
91
|
+
* The file as committed at `commit` and as it most likely sat on disk, or undefined when it isn't in
|
|
92
|
+
* that commit. `--filters` applies the checkout conversions (Git for Windows' CRLF line endings,
|
|
93
|
+
* `.gitattributes` eol and smudge filters). Git also counts an LF copy as clean under `core.autocrlf`,
|
|
94
|
+
* so when only the raw blob's line endings match the working file's, the raw blob it is.
|
|
95
|
+
*/
|
|
96
|
+
const readCommitted = (commit, path, working) => Effect.gen(function* () {
|
|
97
|
+
if (commit === undefined)
|
|
98
|
+
return undefined;
|
|
99
|
+
const checkedOut = yield* catFile("--filters", commit, path);
|
|
100
|
+
const crlf = (content) => content?.text?.includes("\r\n");
|
|
101
|
+
if (working?.text === undefined || checkedOut?.text === undefined || crlf(checkedOut) === crlf(working))
|
|
102
|
+
return checkedOut;
|
|
103
|
+
const raw = yield* catFile("blob", commit, path);
|
|
104
|
+
return crlf(raw) === crlf(working) ? raw : checkedOut;
|
|
105
|
+
});
|
|
106
|
+
const readWorking = (path) => Effect.tryPromise({
|
|
107
|
+
try: () => readEntry(join(root, path)),
|
|
108
|
+
catch: (error) => error
|
|
109
|
+
}).pipe(Effect.catch((error) => {
|
|
110
|
+
const code = error?.code;
|
|
111
|
+
// Gone, or a directory (a submodule or nested repository): nothing to diff.
|
|
112
|
+
return code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR" ? Effect.succeed(undefined) : Effect.fail(new Unreadable(path));
|
|
113
|
+
}));
|
|
114
|
+
const baseline = Effect.gen(function* () {
|
|
115
|
+
disabled = false;
|
|
116
|
+
head = yield* readHead;
|
|
117
|
+
const dirty = (yield* dirtyPaths).slice(0, MAX_TRACKED_FILES);
|
|
118
|
+
const contents = yield* Effect.forEach(dirty, (path) => readWorking(path).pipe(Effect.map((content) => [path, content])), {
|
|
119
|
+
concurrency: 8
|
|
120
|
+
});
|
|
121
|
+
known = new Map(contents);
|
|
122
|
+
}).pipe(Effect.catch((error) => Effect.sync(() => {
|
|
123
|
+
// Without a baseline, every pre-existing edit would later look like the agent's.
|
|
124
|
+
head = undefined;
|
|
125
|
+
known = new Map();
|
|
126
|
+
onError(`change tracking is off for this turn: ${describe(error)}`);
|
|
127
|
+
disabled = true;
|
|
128
|
+
})));
|
|
129
|
+
const fromHead = Effect.gen(function* () {
|
|
130
|
+
disabled = false;
|
|
131
|
+
head = yield* readHead;
|
|
132
|
+
known = new Map();
|
|
133
|
+
});
|
|
134
|
+
const collect = Effect.gen(function* () {
|
|
135
|
+
if (disabled)
|
|
136
|
+
return [];
|
|
137
|
+
const nextHead = yield* readHead;
|
|
138
|
+
const candidates = new Set([...known.keys(), ...(yield* dirtyPaths)]);
|
|
139
|
+
// A commit inside the turn makes its files clean again; find them through the commit range.
|
|
140
|
+
if (head !== undefined && nextHead !== undefined && nextHead !== head) {
|
|
141
|
+
for (const path of yield* committedPaths(head, nextHead))
|
|
142
|
+
candidates.add(path);
|
|
143
|
+
}
|
|
144
|
+
const paths = [...candidates].sort().slice(0, MAX_TRACKED_FILES);
|
|
145
|
+
const changes = yield* Effect.forEach(paths, (path) => Effect.gen(function* () {
|
|
146
|
+
const after = yield* readWorking(path);
|
|
147
|
+
const before = known.has(path) ? known.get(path) : yield* readCommitted(head, path, after);
|
|
148
|
+
known.set(path, after);
|
|
149
|
+
return before?.hash === after?.hash ? [] : [toChange(root, path, before, after)];
|
|
150
|
+
}).pipe(Effect.catch(() => Effect.succeed([]))), { concurrency: 8 });
|
|
151
|
+
head = nextHead;
|
|
152
|
+
return changes.flat();
|
|
153
|
+
}).pipe(Effect.catch((error) => Effect.sync(() => {
|
|
154
|
+
onError(`could not read changes in ${root}: ${describe(error)}`);
|
|
155
|
+
return [];
|
|
156
|
+
})));
|
|
157
|
+
return { baseline, collect, fromHead };
|
|
158
|
+
};
|
|
159
|
+
/**
|
|
160
|
+
* Tracks the git worktree that Capy makes for a thread in worktree mode: `<worktree folder>/<threadId>/<folder>`,
|
|
161
|
+
* where the folder is the repository name (seen with the desktop app and `capy dock`). The API does not say
|
|
162
|
+
* where a thread works (docs/capy-api-notes.md, ask 4). Since Capy 0.9.2 a user can choose the worktree
|
|
163
|
+
* folder, so the thread's folder comes from the worktree list in `device/workspaces.json` (`createdJamId`),
|
|
164
|
+
* and else from the default `<capyHome>/worktrees/<threadId>`. Capy makes the worktree clean at the base commit
|
|
165
|
+
* for the thread's first message, so a worktree found during a turn starts from its HEAD. If the folder is not
|
|
166
|
+
* there, the turn shows no diffs.
|
|
167
|
+
*/
|
|
168
|
+
export const makeWorktreeTracker = (capyHome, repo, threadId, onError = () => { }) => {
|
|
169
|
+
let folder;
|
|
170
|
+
const find = Effect.promise(async () => {
|
|
171
|
+
const id = threadId();
|
|
172
|
+
if (id === undefined)
|
|
173
|
+
return undefined;
|
|
174
|
+
const listed = await readFile(join(capyHome, "device", "workspaces.json"), "utf8").then((text) => JSON.parse(text).worktrees, () => undefined);
|
|
175
|
+
const entry = listed?.find((w) => w.createdJamId === id && typeof w.root === "string");
|
|
176
|
+
const dir = typeof entry?.root === "string" ? entry.root : join(capyHome, "worktrees", id);
|
|
177
|
+
const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
178
|
+
const names = entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name);
|
|
179
|
+
const name = repo.split("/").at(-1)?.toLowerCase();
|
|
180
|
+
const match = names.find((n) => n.toLowerCase() === name) ?? (names.length === 1 ? names[0] : undefined);
|
|
181
|
+
return match === undefined ? undefined : join(dir, match);
|
|
182
|
+
});
|
|
183
|
+
return {
|
|
184
|
+
baseline: Effect.gen(function* () {
|
|
185
|
+
if (folder !== undefined)
|
|
186
|
+
return yield* folder.baseline;
|
|
187
|
+
const root = yield* find;
|
|
188
|
+
if (root === undefined)
|
|
189
|
+
return;
|
|
190
|
+
folder = trackFolder(root, onError);
|
|
191
|
+
yield* folder.baseline;
|
|
192
|
+
}),
|
|
193
|
+
collect: Effect.gen(function* () {
|
|
194
|
+
if (folder === undefined) {
|
|
195
|
+
const root = yield* find;
|
|
196
|
+
if (root === undefined)
|
|
197
|
+
return [];
|
|
198
|
+
folder = trackFolder(root, onError);
|
|
199
|
+
yield* folder.fromHead;
|
|
200
|
+
}
|
|
201
|
+
return yield* folder.collect;
|
|
202
|
+
})
|
|
203
|
+
};
|
|
204
|
+
};
|
|
205
|
+
const describe = (error) => (error instanceof Error ? error.message.split("\n")[0] : String(error));
|
|
206
|
+
const toChange = (root, relativePath, before, after) => {
|
|
207
|
+
const operation = before === undefined ? "add" : after === undefined ? "delete" : "modify";
|
|
208
|
+
const previewable = (before === undefined || before.text !== undefined) && (after === undefined || after.text !== undefined);
|
|
209
|
+
return {
|
|
210
|
+
path: join(root, relativePath),
|
|
211
|
+
relativePath,
|
|
212
|
+
operation,
|
|
213
|
+
previewable,
|
|
214
|
+
...(previewable && before?.text !== undefined ? { oldText: before.text } : {}),
|
|
215
|
+
...(previewable && after?.text !== undefined ? { newText: after.text } : {})
|
|
216
|
+
};
|
|
217
|
+
};
|
|
218
|
+
//# sourceMappingURL=changes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"changes.js","sourceRoot":"","sources":["../src/changes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAA;AAC7C,OAAO,EAAE,UAAU,EAAE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;QACX,GAAG,CAAC,WAAW,IAAI,MAAM,EAAE,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC9E,GAAG,CAAC,WAAW,IAAI,KAAK,EAAE,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC7E,CAAA;AACH,CAAC,CAAA","sourcesContent":["/**\n * Observes what a Capy thread changes on disk, so ACP clients can show real diffs.\n *\n * Capy's stream names the tools a call ran but never the files or their contents (docs/capy-api-notes.md, ask\n * 3). The thread works on this machine, in the folder the client has open (linked mode) or in its\n * own git worktree, so the adapter can see the changes itself: it records the working tree when a turn\n * starts, then diffs it as tool calls start and finish. Strictly read only: `git status`, `git rev-parse`,\n * `git diff --name-only`, `git cat-file`, directory listings and plain file reads. Git LFS smudging is\n * skipped, so a diff never downloads.\n *\n * Attribution is by time (see turn.ts): a change is credited to the tool call that ran when it happened.\n */\nimport { execFile } from \"node:child_process\"\nimport { createHash } from \"node:crypto\"\nimport { lstat, readdir, readFile, readlink } from \"node:fs/promises\"\nimport { join } from \"node:path\"\nimport { promisify } from \"node:util\"\nimport { Effect } from \"effect\"\n\nconst exec = promisify(execFile)\n\nexport interface FileChange {\n /** Absolute path. */\n readonly path: string\n /** Path relative to the folder root, for titles. */\n readonly relativePath: string\n readonly operation: \"add\" | \"modify\" | \"delete\"\n /** Text before the change; absent for added files and for files that cannot be previewed. */\n readonly oldText?: string\n /** Text after the change; absent for deleted files and for files that cannot be previewed. */\n readonly newText?: string\n /** False for binary or very large files: clients get the path but no diff. */\n readonly previewable: boolean\n}\n\nexport interface ChangeTracker {\n /** Records the folder's current state. Call when a turn starts. */\n readonly baseline: Effect.Effect<void>\n /** Changes since the baseline or the previous collect. Never fails: a broken read yields no changes. */\n readonly collect: Effect.Effect<ReadonlyArray<FileChange>>\n}\n\n/** Above this a file is reported by path only: diffs this large don't help anyone in a chat view. */\nexport const MAX_PREVIEW_BYTES = 256 * 1024\n/** A turn that touches more files than this (a dependency install, a generator) reports the first ones. */\nexport const MAX_TRACKED_FILES = 500\nconst MAX_GIT_OUTPUT = 64 * 1024 * 1024\n\n/** A file's content at one point in time; `undefined` means the file did not exist. */\ninterface Content {\n readonly hash: string\n readonly text: string | undefined\n}\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: true })\n\nconst toContent = (bytes: Buffer): Content => {\n const hash = createHash(\"sha256\").update(bytes).digest(\"hex\")\n if (bytes.length > MAX_PREVIEW_BYTES || bytes.subarray(0, 8192).includes(0)) return { hash, text: undefined }\n try {\n return { hash, text: utf8.decode(bytes) }\n } catch {\n return { hash, text: undefined }\n }\n}\n\n/** Above this a file is compared by size and modification time instead of being read. */\nconst MAX_READ_BYTES = 16 * 1024 * 1024\n\n/**\n * A working-tree entry as git would see it. A symlink is its target path (what git stores), never\n * the file it points at, which may be outside the folder. Special files and very large files are\n * compared by metadata only and never shown.\n */\nconst readEntry = async (path: string): Promise<Content | undefined> => {\n const info = await lstat(path)\n if (info.isSymbolicLink()) return toContent(Buffer.from(await readlink(path)))\n if (info.isDirectory()) return undefined\n if (!info.isFile() || info.size > MAX_READ_BYTES) {\n return { hash: `stat:${info.mode}:${info.size}:${info.mtimeMs}`, text: undefined }\n }\n return toContent(await readFile(path))\n}\n\n/** Thrown inside the tracker for reads that failed for a reason other than \"not there\". */\nclass Unreadable {\n readonly _tag = \"Unreadable\"\n constructor(readonly path: string) {}\n}\n\nexport const makeChangeTracker = (root: string, onError: (message: string) => void = () => {}): ChangeTracker =>\n trackFolder(root, onError)\n\n/** A folder tracker, plus `fromHead`: a baseline for a folder known to have been clean at its HEAD. */\nconst trackFolder = (root: string, onError: (message: string) => void): ChangeTracker & { readonly fromHead: Effect.Effect<void> } => {\n let head: string | undefined\n let known = new Map<string, Content | undefined>()\n /** Set when a baseline could not be taken; the turn then reports no changes rather than wrong ones. */\n let disabled = false\n\n const git = (args: ReadonlyArray<string>) =>\n Effect.tryPromise({\n try: () =>\n exec(\"git\", [\"-C\", root, ...args], {\n encoding: \"buffer\",\n maxBuffer: MAX_GIT_OUTPUT,\n timeout: 15_000,\n env: { ...process.env, GIT_LFS_SKIP_SMUDGE: \"1\" }\n }),\n catch: (error) => error\n }).pipe(Effect.map(({ stdout }) => stdout))\n\n const readHead = git([\"rev-parse\", \"--verify\", \"--quiet\", \"HEAD\"]).pipe(\n Effect.map((out) => out.toString(\"utf8\").trim() || undefined),\n // A repository with no commits yet has no HEAD.\n Effect.orElseSucceed(() => undefined)\n )\n\n /** Paths git reports as changed or untracked (ignored files excluded), relative to the root. */\n const dirtyPaths = git([\"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\", \"--no-renames\"]).pipe(\n Effect.map((out) =>\n out\n .toString(\"utf8\")\n .split(\"\\0\")\n .filter((entry) => entry.length > 3)\n .map((entry) => entry.slice(3))\n )\n )\n\n const committedPaths = (from: string, to: string) =>\n git([\"diff\", \"--name-only\", \"-z\", \"--no-renames\", from, to]).pipe(\n Effect.map((out) => out.toString(\"utf8\").split(\"\\0\").filter((path) => path.length > 0))\n )\n\n const catFile = (mode: \"--filters\" | \"blob\", commit: string, path: string): Effect.Effect<Content | undefined> =>\n git([\"cat-file\", mode, `${commit}:${path}`]).pipe(\n Effect.map(toContent),\n Effect.orElseSucceed(() => undefined)\n )\n\n /**\n * The file as committed at `commit` and as it most likely sat on disk, or undefined when it isn't in\n * that commit. `--filters` applies the checkout conversions (Git for Windows' CRLF line endings,\n * `.gitattributes` eol and smudge filters). Git also counts an LF copy as clean under `core.autocrlf`,\n * so when only the raw blob's line endings match the working file's, the raw blob it is.\n */\n const readCommitted = (commit: string | undefined, path: string, working: Content | undefined) =>\n Effect.gen(function*() {\n if (commit === undefined) return undefined\n const checkedOut = yield* catFile(\"--filters\", commit, path)\n const crlf = (content: Content | undefined) => content?.text?.includes(\"\\r\\n\")\n if (working?.text === undefined || checkedOut?.text === undefined || crlf(checkedOut) === crlf(working)) return checkedOut\n const raw = yield* catFile(\"blob\", commit, path)\n return crlf(raw) === crlf(working) ? raw : checkedOut\n })\n\n const readWorking = (path: string): Effect.Effect<Content | undefined, Unreadable> =>\n Effect.tryPromise({\n try: () => readEntry(join(root, path)),\n catch: (error) => error\n }).pipe(\n Effect.catch((error) => {\n const code = (error as NodeJS.ErrnoException | undefined)?.code\n // Gone, or a directory (a submodule or nested repository): nothing to diff.\n return code === \"ENOENT\" || code === \"ENOTDIR\" || code === \"EISDIR\" ? Effect.succeed(undefined) : Effect.fail(new Unreadable(path))\n })\n )\n\n const baseline = Effect.gen(function*() {\n disabled = false\n head = yield* readHead\n const dirty = (yield* dirtyPaths).slice(0, MAX_TRACKED_FILES)\n const contents = yield* Effect.forEach(dirty, (path) => readWorking(path).pipe(Effect.map((content) => [path, content] as const)), {\n concurrency: 8\n })\n known = new Map(contents)\n }).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n // Without a baseline, every pre-existing edit would later look like the agent's.\n head = undefined\n known = new Map()\n onError(`change tracking is off for this turn: ${describe(error)}`)\n disabled = true\n })\n )\n )\n\n const fromHead = Effect.gen(function*() {\n disabled = false\n head = yield* readHead\n known = new Map()\n })\n\n const collect = Effect.gen(function*() {\n if (disabled) return []\n const nextHead = yield* readHead\n const candidates = new Set([...known.keys(), ...(yield* dirtyPaths)])\n // A commit inside the turn makes its files clean again; find them through the commit range.\n if (head !== undefined && nextHead !== undefined && nextHead !== head) {\n for (const path of yield* committedPaths(head, nextHead)) candidates.add(path)\n }\n const paths = [...candidates].sort().slice(0, MAX_TRACKED_FILES)\n const changes = yield* Effect.forEach(\n paths,\n (path) =>\n Effect.gen(function*() {\n const after = yield* readWorking(path)\n const before = known.has(path) ? known.get(path) : yield* readCommitted(head, path, after)\n known.set(path, after)\n return before?.hash === after?.hash ? [] : [toChange(root, path, before, after)]\n }).pipe(Effect.catch(() => Effect.succeed([] as Array<FileChange>))),\n { concurrency: 8 }\n )\n head = nextHead\n return changes.flat()\n }).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n onError(`could not read changes in ${root}: ${describe(error)}`)\n return [] as Array<FileChange>\n })\n )\n )\n\n return { baseline, collect, fromHead }\n}\n\n/**\n * Tracks the git worktree that Capy makes for a thread in worktree mode: `<worktree folder>/<threadId>/<folder>`,\n * where the folder is the repository name (seen with the desktop app and `capy dock`). The API does not say\n * where a thread works (docs/capy-api-notes.md, ask 4). Since Capy 0.9.2 a user can choose the worktree\n * folder, so the thread's folder comes from the worktree list in `device/workspaces.json` (`createdJamId`),\n * and else from the default `<capyHome>/worktrees/<threadId>`. Capy makes the worktree clean at the base commit\n * for the thread's first message, so a worktree found during a turn starts from its HEAD. If the folder is not\n * there, the turn shows no diffs.\n */\nexport const makeWorktreeTracker = (\n capyHome: string,\n repo: string,\n threadId: () => string | undefined,\n onError: (message: string) => void = () => {}\n): ChangeTracker => {\n let folder: ReturnType<typeof trackFolder> | undefined\n\n const find = Effect.promise(async () => {\n const id = threadId()\n if (id === undefined) return undefined\n const listed = await readFile(join(capyHome, \"device\", \"workspaces.json\"), \"utf8\").then(\n (text) => (JSON.parse(text) as { worktrees?: ReadonlyArray<{ root?: unknown; createdJamId?: unknown }> }).worktrees,\n () => undefined\n )\n const entry = listed?.find((w) => w.createdJamId === id && typeof w.root === \"string\")\n const dir = typeof entry?.root === \"string\" ? entry.root : join(capyHome, \"worktrees\", id)\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])\n const names = entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(\".\")).map((entry) => entry.name)\n const name = repo.split(\"/\").at(-1)?.toLowerCase()\n const match = names.find((n) => n.toLowerCase() === name) ?? (names.length === 1 ? names[0] : undefined)\n return match === undefined ? undefined : join(dir, match)\n })\n\n return {\n baseline: Effect.gen(function*() {\n if (folder !== undefined) return yield* folder.baseline\n const root = yield* find\n if (root === undefined) return\n folder = trackFolder(root, onError)\n yield* folder.baseline\n }),\n collect: Effect.gen(function*() {\n if (folder === undefined) {\n const root = yield* find\n if (root === undefined) return []\n folder = trackFolder(root, onError)\n yield* folder.fromHead\n }\n return yield* folder.collect\n })\n }\n}\n\nconst describe = (error: unknown) => (error instanceof Error ? error.message.split(\"\\n\")[0] : String(error))\n\nconst toChange = (root: string, relativePath: string, before: Content | undefined, after: Content | undefined): FileChange => {\n const operation = before === undefined ? \"add\" : after === undefined ? \"delete\" : \"modify\"\n const previewable = (before === undefined || before.text !== undefined) && (after === undefined || after.text !== undefined)\n return {\n path: join(root, relativePath),\n relativePath,\n operation,\n previewable,\n ...(previewable && before?.text !== undefined ? { oldText: before.text } : {}),\n ...(previewable && after?.text !== undefined ? { newText: after.text } : {})\n }\n}\n"]}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adapter settings, read from the environment the ACP client launches us with.
|
|
3
|
+
* T3 Code passes per-instance environment overrides, so every knob is an env var.
|
|
4
|
+
*/
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { join, posix, win32 } from "node:path";
|
|
7
|
+
const flag = (value) => value === "1" || value === "true";
|
|
8
|
+
/**
|
|
9
|
+
* Where the Capy desktop app keeps its files: Electron's per-user app data folder plus "Capy", which
|
|
10
|
+
* is what the packaged app sets. Only the Linux location has been checked on a machine;
|
|
11
|
+
* `CAPY_DESKTOP_CONFIG_DIR` overrides it (a nightly build uses "Capy Nightly").
|
|
12
|
+
*/
|
|
13
|
+
export const desktopConfigDir = (env, home, platform = process.platform) => {
|
|
14
|
+
const { join } = platform === "win32" ? win32 : posix;
|
|
15
|
+
if (platform === "darwin")
|
|
16
|
+
return join(home, "Library", "Application Support", "Capy");
|
|
17
|
+
if (platform === "win32")
|
|
18
|
+
return join(env.APPDATA ?? join(home, "AppData", "Roaming"), "Capy");
|
|
19
|
+
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Capy");
|
|
20
|
+
};
|
|
21
|
+
export const readConfig = (env = process.env) => {
|
|
22
|
+
const home = homedir();
|
|
23
|
+
const waiting = Number(env.CAPY_ACP_WAITING_LIMIT_MS ?? 10 * 60_000);
|
|
24
|
+
return {
|
|
25
|
+
apiUrl: (env.CAPY_API_URL ?? "https://api.capy.ai/api/v1").replace(/\/+$/, ""),
|
|
26
|
+
apiKeyFile: env.CAPY_API_KEY_FILE ?? join(home, ".config", "capy-acp", "api-key"),
|
|
27
|
+
pricingUrl: env.CAPY_ACP_PRICING_URL ?? "https://docs.capy.ai/models-and-pricing.md",
|
|
28
|
+
defaultModel: env.CAPY_ACP_MODEL ?? "anthropic/claude-opus-5-5",
|
|
29
|
+
defaultReasoning: env.CAPY_ACP_REASONING ?? "high",
|
|
30
|
+
workspaceMode: env.CAPY_ACP_WORKSPACE === "worktree" ? "worktree" : "linked",
|
|
31
|
+
allowWorktreeFallback: flag(env.CAPY_ACP_ALLOW_WORKTREE_FALLBACK),
|
|
32
|
+
waitingLimitMs: Number.isFinite(waiting) && waiting >= 0 ? waiting : 10 * 60_000,
|
|
33
|
+
forwardHostInstructions: flag(env.CAPY_ACP_FORWARD_HOST_INSTRUCTIONS),
|
|
34
|
+
deviceIdOverride: env.CAPY_DEVICE_ID,
|
|
35
|
+
capyDesktopConfigDir: env.CAPY_DESKTOP_CONFIG_DIR ?? desktopConfigDir(env, home),
|
|
36
|
+
capyHome: env.CAPY_HOME ?? join(home, ".capy"),
|
|
37
|
+
stateDir: env.CAPY_ACP_STATE_DIR ?? join(env.XDG_STATE_HOME ?? join(home, ".local", "state"), "capy-acp", "sessions"),
|
|
38
|
+
attachmentsDir: env.CAPY_ACP_ATTACHMENTS_DIR ?? join(env.XDG_CACHE_HOME ?? join(home, ".cache"), "capy-acp", "attachments")
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","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ment overrides, so every knob is an env var.\n */\nimport { homedir } from \"node:os\"\nimport { join, posix, win32 } from \"node:path\"\n\nexport interface AdapterConfig {\n readonly apiUrl: string\n /** File holding the API key, used when `CAPY_API_KEY` is unset. Never logged. */\n readonly apiKeyFile: string\n /** The docs page with the model price table; empty turns prices off. */\n readonly pricingUrl: string\n readonly defaultModel: string\n readonly defaultReasoning: string\n /** `linked` edits the folder the client opened; `worktree` gives each session a fresh Capy worktree. */\n readonly workspaceMode: \"linked\" | \"worktree\"\n /** Run unlinked clones in a worktree cut from another linked folder of the same repo. */\n readonly allowWorktreeFallback: boolean\n /** How long a prompt stays open while the thread is `waiting` on a background command. */\n readonly waitingLimitMs: number\n readonly forwardHostInstructions: boolean\n readonly deviceIdOverride: string | undefined\n readonly capyDesktopConfigDir: string\n readonly capyHome: string\n /** Where session records live (session → Capy thread), for `session/load` and `session/resume`. */\n readonly stateDir: string\n /** Where files from a thread's first prompt are saved for the device agent to read. */\n readonly attachmentsDir: string\n}\n\nconst flag = (value: string | undefined) => value === \"1\" || value === \"true\"\n\n/**\n * Where the Capy desktop app keeps its files: Electron's per-user app data folder plus \"Capy\", which\n * is what the packaged app sets. Only the Linux location has been checked on a machine;\n * `CAPY_DESKTOP_CONFIG_DIR` overrides it (a nightly build uses \"Capy Nightly\").\n */\nexport const desktopConfigDir = (env: NodeJS.ProcessEnv, home: string, platform: NodeJS.Platform = process.platform): string => {\n const { join } = platform === \"win32\" ? win32 : posix\n if (platform === \"darwin\") return join(home, \"Library\", \"Application Support\", \"Capy\")\n if (platform === \"win32\") return join(env.APPDATA ?? join(home, \"AppData\", \"Roaming\"), \"Capy\")\n return join(env.XDG_CONFIG_HOME ?? join(home, \".config\"), \"Capy\")\n}\n\nexport const readConfig = (env: NodeJS.ProcessEnv = process.env): AdapterConfig => {\n const home = homedir()\n const waiting = Number(env.CAPY_ACP_WAITING_LIMIT_MS ?? 10 * 60_000)\n return {\n apiUrl: (env.CAPY_API_URL ?? \"https://api.capy.ai/api/v1\").replace(/\\/+$/, \"\"),\n apiKeyFile: env.CAPY_API_KEY_FILE ?? join(home, \".config\", \"capy-acp\", \"api-key\"),\n pricingUrl: env.CAPY_ACP_PRICING_URL ?? \"https://docs.capy.ai/models-and-pricing.md\",\n defaultModel: env.CAPY_ACP_MODEL ?? \"anthropic/claude-opus-5-5\",\n defaultReasoning: env.CAPY_ACP_REASONING ?? \"high\",\n workspaceMode: env.CAPY_ACP_WORKSPACE === \"worktree\" ? \"worktree\" : \"linked\",\n allowWorktreeFallback: flag(env.CAPY_ACP_ALLOW_WORKTREE_FALLBACK),\n waitingLimitMs: Number.isFinite(waiting) && waiting >= 0 ? waiting : 10 * 60_000,\n forwardHostInstructions: flag(env.CAPY_ACP_FORWARD_HOST_INSTRUCTIONS),\n deviceIdOverride: env.CAPY_DEVICE_ID,\n capyDesktopConfigDir: env.CAPY_DESKTOP_CONFIG_DIR ?? desktopConfigDir(env, home),\n capyHome: env.CAPY_HOME ?? join(home, \".capy\"),\n stateDir: env.CAPY_ACP_STATE_DIR ?? join(env.XDG_STATE_HOME ?? join(home, \".local\", \"state\"), \"capy-acp\", \"sessions\"),\n attachmentsDir: env.CAPY_ACP_ATTACHMENTS_DIR ?? join(env.XDG_CACHE_HOME ?? join(home, \".cache\"), \"capy-acp\", \"attachments\")\n }\n}\n"]}
|
package/dist/doctor.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `capy-acp --doctor [folder]`: checks each part of the setup that a prompt needs, in the order a prompt
|
|
3
|
+
* needs them, and prints the fix for each problem. Read only: it saves nothing and starts no thread.
|
|
4
|
+
*/
|
|
5
|
+
import { describeError, isCapyError } from "./capy/client.js";
|
|
6
|
+
import { noApiKey, problemOf, rejectedApiKey, toText, unreachable } from "./problems.js";
|
|
7
|
+
import { savedApiKey } from "./setup.js";
|
|
8
|
+
import { AGENT_VERSION } from "./version.js";
|
|
9
|
+
import { readDevice, readGit, readLinkedFolders, resolveWorkspace, samePath } from "./workspace.js";
|
|
10
|
+
/** True when version `a` is older than `b`. Both are plain `major.minor.patch`. */
|
|
11
|
+
const older = (a, b) => {
|
|
12
|
+
const parts = (v) => v.split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
13
|
+
const [x, y] = [parts(a), parts(b)];
|
|
14
|
+
for (let i = 0; i < 3; i++)
|
|
15
|
+
if ((x[i] ?? 0) !== (y[i] ?? 0))
|
|
16
|
+
return (x[i] ?? 0) < (y[i] ?? 0);
|
|
17
|
+
return false;
|
|
18
|
+
};
|
|
19
|
+
const message = (error) => isCapyError(error) ? describeError(error) : error instanceof Error ? error.message : String(error);
|
|
20
|
+
/** Returns the exit code: 0 when nothing needs a fix. */
|
|
21
|
+
export const runDoctor = async (config, folder, io) => {
|
|
22
|
+
let problems = 0;
|
|
23
|
+
const ok = (text) => io.write(` ok ${text}\n`);
|
|
24
|
+
const note = (text) => io.write(` note ${text}\n`);
|
|
25
|
+
const fail = (problem) => {
|
|
26
|
+
problems++;
|
|
27
|
+
io.write(` FAIL ${toText(problem, " ")}\n`);
|
|
28
|
+
};
|
|
29
|
+
io.write(`capy-acp ${AGENT_VERSION} doctor: ${folder}\n\n`);
|
|
30
|
+
const latest = await io.latestVersion().catch(() => undefined);
|
|
31
|
+
if (latest === undefined)
|
|
32
|
+
note(`capy-acp ${AGENT_VERSION}. npm could not be reached to check for a newer version.`);
|
|
33
|
+
else if (older(AGENT_VERSION, latest))
|
|
34
|
+
note(`capy-acp ${AGENT_VERSION}, and npm has ${latest}. \`npx -y capy-acp@latest\` runs the newest version.`);
|
|
35
|
+
else
|
|
36
|
+
ok(latest === AGENT_VERSION ? `capy-acp ${AGENT_VERSION}, the newest version on npm.` : `capy-acp ${AGENT_VERSION} (npm has ${latest}).`);
|
|
37
|
+
const major = Number(io.nodeVersion.replace(/^v/, "").split(".")[0]);
|
|
38
|
+
if (major >= 22)
|
|
39
|
+
ok(`Node ${io.nodeVersion}`);
|
|
40
|
+
else
|
|
41
|
+
fail({ title: "Update Node", detail: `capy-acp needs Node 22 or later, and this is Node ${io.nodeVersion}.`, steps: ["Install Node 22 or later."] });
|
|
42
|
+
let projects;
|
|
43
|
+
const key = await savedApiKey(config);
|
|
44
|
+
const source = process.env.CAPY_API_KEY?.trim() ? "CAPY_API_KEY" : config.apiKeyFile;
|
|
45
|
+
if (key === undefined) {
|
|
46
|
+
fail(noApiKey(config.apiKeyFile));
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
try {
|
|
50
|
+
projects = await io.listProjects();
|
|
51
|
+
ok(`API key from ${source}. Capy accepted it and shows ${projects.length} project${projects.length === 1 ? "" : "s"}.`);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
const rejected = isCapyError(error) && error._tag === "CapyApiError" && (error.status === 401 || error.status === 403);
|
|
55
|
+
fail(rejected ? rejectedApiKey(`${message(error)}, from ${source}`) : unreachable(config.apiUrl, message(error)));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const device = await readDevice(config).then((found) => {
|
|
59
|
+
const runner = found.kind === "dock" ? "`capy dock`" : found.kind === "desktop" ? "the Capy desktop app" : "the Capy desktop app or `capy dock`";
|
|
60
|
+
ok(`Capy device ${found.id}. Keep ${runner} running while you work.`);
|
|
61
|
+
return found;
|
|
62
|
+
}, (error) => {
|
|
63
|
+
fail(problemOf(error) ?? { title: "Check the Capy device", detail: message(error), steps: [] });
|
|
64
|
+
return undefined;
|
|
65
|
+
});
|
|
66
|
+
const [git, linked] = await Promise.all([readGit(folder), readLinkedFolders(config)]);
|
|
67
|
+
if (projects === undefined) {
|
|
68
|
+
note("The folder check needs an API key that Capy accepts.");
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
const resolution = resolveWorkspace({
|
|
72
|
+
cwd: folder,
|
|
73
|
+
...git,
|
|
74
|
+
linked,
|
|
75
|
+
projects,
|
|
76
|
+
mode: config.workspaceMode,
|
|
77
|
+
allowWorktreeFallback: config.allowWorktreeFallback,
|
|
78
|
+
device: device?.kind
|
|
79
|
+
});
|
|
80
|
+
if (resolution._tag === "Unresolved") {
|
|
81
|
+
fail(resolution.problem);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
const { repo, projectName, workspace, notLinked } = resolution.value;
|
|
85
|
+
ok(`${git.gitRoot}: ${repo}, in the Capy project "${projectName}".`);
|
|
86
|
+
const gitRoot = git.gitRoot ?? folder;
|
|
87
|
+
const listed = linked.some((f) => samePath(f.realRoot ?? f.root, gitRoot) || samePath(f.root, gitRoot));
|
|
88
|
+
if (workspace.kind === "worktree")
|
|
89
|
+
ok(resolution.value.note ?? "Capy works in a new worktree for each session.");
|
|
90
|
+
else if (listed)
|
|
91
|
+
ok("The folder is linked to this device. Capy edits it in place.");
|
|
92
|
+
else
|
|
93
|
+
note(`The local list of linked folders does not show this folder. Capy checks it when the first thread starts. If Capy refuses it:\n ${toText(notLinked, " ")}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
io.write(problems === 0
|
|
97
|
+
? "\nReady. In your ACP client, add an agent with the command `npx` and the arguments `-y capy-acp`.\n" +
|
|
98
|
+
"Steps for each client: https://github.com/yazcaleb/capy-acp#setup\n"
|
|
99
|
+
: `\n${problems === 1 ? "1 problem" : `${problems} problems`} to fix. Then run \`npx -y capy-acp --doctor\` again.\n`);
|
|
100
|
+
return problems === 0 ? 0 : 1;
|
|
101
|
+
};
|
|
102
|
+
//# sourceMappingURL=doctor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"doctor.js","sourceRoot":"","sources":["../src/doctor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAE7D,OAAO,EAAE,QAAQ,EAAgB,SAAS,EAAE,cAAc,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AACtG,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAC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,EAAE,WAAW,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,UAAU,CAAC,KAAK,CAAA;YACpE,EAAE,CAAC,GAAG,GAAG,CAAC,OAAO,KAAK,IAAI,0BAA0B,WAAW,IAAI,CAAC,CAAA;YACpE,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO,IAAI,MAAM,CAAA;YACrC,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAA;YACvG,IAAI,SAAS,CAAC,IAAI,KAAK,UAAU;gBAAE,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,IAAI,gDAAgD,CAAC,CAAA;iBAC3G,IAAI,MAAM;gBAAE,EAAE,CAAC,8DAA8D,CAAC,CAAA;;gBAC9E,IAAI,CAAC,yIAAyI,MAAM,CAAC,SAAS,EAAE,UAAU,CAAC,EAAE,CAAC,CAAA;QACrL,CAAC;IACH,CAAC;IAED,EAAE,CAAC,KAAK,CACN,QAAQ,KAAK,CAAC;QACZ,CAAC,CAAC,qGAAqG;YACnG,qEAAqE;QACzE,CAAC,CAAC,KAAK,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,GAAG,QAAQ,WAAW,yDAAyD,CACxH,CAAA;IACD,OAAO,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAC/B,CAAC,CAAA","sourcesContent":["/**\n * `capy-acp --doctor [folder]`: checks each part of the setup that a prompt needs, in the order a prompt\n * needs them, and prints the fix for each problem. Read only: it saves nothing and starts no thread.\n */\nimport { describeError, isCapyError } from \"./capy/client.js\"\nimport type { AdapterConfig } from \"./config.js\"\nimport { noApiKey, type Problem, problemOf, rejectedApiKey, toText, unreachable } from \"./problems.js\"\nimport { savedApiKey } from \"./setup.js\"\nimport { AGENT_VERSION } from \"./version.js\"\nimport { type Device, type ProjectSummary, readDevice, readGit, readLinkedFolders, resolveWorkspace, samePath } from \"./workspace.js\"\n\nexport interface DoctorIo {\n readonly write: (text: string) => void\n /** The projects that the API key can see. */\n readonly listProjects: () => Promise<ReadonlyArray<ProjectSummary>>\n readonly nodeVersion: string\n /** The newest capy-acp on npm, or undefined when npm cannot be reached. */\n readonly latestVersion: () => Promise<string | undefined>\n}\n\n/** True when version `a` is older than `b`. Both are plain `major.minor.patch`. */\nconst older = (a: string, b: string) => {\n const parts = (v: string) => v.split(\".\").map((n) => Number.parseInt(n, 10) || 0)\n const [x, y] = [parts(a), parts(b)]\n for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0)\n return false\n}\n\nconst message = (error: unknown) =>\n isCapyError(error) ? describeError(error) : error instanceof Error ? error.message : String(error)\n\n/** Returns the exit code: 0 when nothing needs a fix. */\nexport const runDoctor = async (config: AdapterConfig, folder: string, io: DoctorIo): Promise<number> => {\n let problems = 0\n const ok = (text: string) => io.write(` ok ${text}\\n`)\n const note = (text: string) => io.write(` note ${text}\\n`)\n const fail = (problem: Problem) => {\n problems++\n io.write(` FAIL ${toText(problem, \" \")}\\n`)\n }\n io.write(`capy-acp ${AGENT_VERSION} doctor: ${folder}\\n\\n`)\n\n const latest = await io.latestVersion().catch(() => undefined)\n if (latest === undefined) note(`capy-acp ${AGENT_VERSION}. npm could not be reached to check for a newer version.`)\n else if (older(AGENT_VERSION, latest)) note(`capy-acp ${AGENT_VERSION}, and npm has ${latest}. \\`npx -y capy-acp@latest\\` runs the newest version.`)\n else ok(latest === AGENT_VERSION ? `capy-acp ${AGENT_VERSION}, the newest version on npm.` : `capy-acp ${AGENT_VERSION} (npm has ${latest}).`)\n\n const major = Number(io.nodeVersion.replace(/^v/, \"\").split(\".\")[0])\n if (major >= 22) ok(`Node ${io.nodeVersion}`)\n else fail({ title: \"Update Node\", detail: `capy-acp needs Node 22 or later, and this is Node ${io.nodeVersion}.`, steps: [\"Install Node 22 or later.\"] })\n\n let projects: ReadonlyArray<ProjectSummary> | undefined\n const key = await savedApiKey(config)\n const source = process.env.CAPY_API_KEY?.trim() ? \"CAPY_API_KEY\" : config.apiKeyFile\n if (key === undefined) {\n fail(noApiKey(config.apiKeyFile))\n } else {\n try {\n projects = await io.listProjects()\n ok(`API key from ${source}. Capy accepted it and shows ${projects.length} project${projects.length === 1 ? \"\" : \"s\"}.`)\n } catch (error) {\n const rejected = isCapyError(error) && error._tag === \"CapyApiError\" && (error.status === 401 || error.status === 403)\n fail(rejected ? rejectedApiKey(`${message(error)}, from ${source}`) : unreachable(config.apiUrl, message(error)))\n }\n }\n\n const device: Device | undefined = await readDevice(config).then(\n (found) => {\n const runner = found.kind === \"dock\" ? \"`capy dock`\" : found.kind === \"desktop\" ? \"the Capy desktop app\" : \"the Capy desktop app or `capy dock`\"\n ok(`Capy device ${found.id}. Keep ${runner} running while you work.`)\n return found\n },\n (error: unknown) => {\n fail(problemOf(error) ?? { title: \"Check the Capy device\", detail: message(error), steps: [] })\n return undefined\n }\n )\n\n const [git, linked] = await Promise.all([readGit(folder), readLinkedFolders(config)])\n if (projects === undefined) {\n note(\"The folder check needs an API key that Capy accepts.\")\n } else {\n const resolution = resolveWorkspace({\n cwd: folder,\n ...git,\n linked,\n projects,\n mode: config.workspaceMode,\n allowWorktreeFallback: config.allowWorktreeFallback,\n device: device?.kind\n })\n if (resolution._tag === \"Unresolved\") {\n fail(resolution.problem)\n } else {\n const { repo, projectName, workspace, notLinked } = resolution.value\n ok(`${git.gitRoot}: ${repo}, in the Capy project \"${projectName}\".`)\n const gitRoot = git.gitRoot ?? folder\n const listed = linked.some((f) => samePath(f.realRoot ?? f.root, gitRoot) || samePath(f.root, gitRoot))\n if (workspace.kind === \"worktree\") ok(resolution.value.note ?? \"Capy works in a new worktree for each session.\")\n else if (listed) ok(\"The folder is linked to this device. Capy edits it in place.\")\n else note(`The local list of linked folders does not show this folder. Capy checks it when the first thread starts. If Capy refuses it:\\n ${toText(notLinked, \" \")}`)\n }\n }\n\n io.write(\n problems === 0\n ? \"\\nReady. In your ACP client, add an agent with the command `npx` and the arguments `-y capy-acp`.\\n\" +\n \"Steps for each client: https://github.com/yazcaleb/capy-acp#setup\\n\"\n : `\\n${problems === 1 ? \"1 problem\" : `${problems} problems`} to fix. Then run \\`npx -y capy-acp --doctor\\` again.\\n`\n )\n return problems === 0 ? 0 : 1\n}\n"]}
|
package/dist/pricing.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
const unescape = (cell) => cell.replace(/\\\$/g, "$").replace(/>/g, ">").replace(/</g, "<").replace(/<br\s*\/?>/g, "; ").trim();
|
|
2
|
+
/** Reads `| **Name** | `id` | context | input | output | ... |` rows of the docs price table. */
|
|
3
|
+
export const parsePrices = (markdown) => {
|
|
4
|
+
const prices = new Map();
|
|
5
|
+
for (const line of markdown.split("\n")) {
|
|
6
|
+
const cells = line.split("|").map((cell) => cell.trim());
|
|
7
|
+
const idAt = cells.findIndex((cell) => /^`[a-z0-9][\w.-]*\/[\w.-]+`$/i.test(cell));
|
|
8
|
+
if (idAt < 0 || cells.length < idAt + 4)
|
|
9
|
+
continue;
|
|
10
|
+
const input = unescape(cells[idAt + 2]);
|
|
11
|
+
const output = unescape(cells[idAt + 3]);
|
|
12
|
+
const firstInput = /\$\d+(?:\.\d+)?/.exec(input)?.[0];
|
|
13
|
+
const firstOutput = /\$\d+(?:\.\d+)?/.exec(output)?.[0];
|
|
14
|
+
if (firstInput === undefined || firstOutput === undefined)
|
|
15
|
+
continue;
|
|
16
|
+
const amounts = [...`${input} ${output}`.matchAll(/\$(\d+(?:\.\d+)?)/g)].map((m) => Number(m[1]));
|
|
17
|
+
prices.set(cells[idAt].slice(1, -1), {
|
|
18
|
+
input: firstInput,
|
|
19
|
+
cachedInput: /cached (\$\d+(?:\.\d+)?)/.exec(input)?.[1],
|
|
20
|
+
output: firstOutput,
|
|
21
|
+
free: amounts.every((amount) => amount === 0),
|
|
22
|
+
tiered: input.includes(";") || output.includes(";")
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
return prices;
|
|
26
|
+
};
|
|
27
|
+
export const fetchPrices = async (url, timeoutMs = 3_000) => {
|
|
28
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), headers: { accept: "text/markdown, text/plain" } });
|
|
29
|
+
if (!response.ok)
|
|
30
|
+
throw new Error(`${url} answered ${response.status}`);
|
|
31
|
+
return parsePrices(await response.text());
|
|
32
|
+
};
|
|
33
|
+
/** Subscription models keep their name. Models on Capy credits show their price, or "free". */
|
|
34
|
+
export const modelLabel = (model, price) => {
|
|
35
|
+
if (model.route !== "capy")
|
|
36
|
+
return model.name;
|
|
37
|
+
if (price === undefined)
|
|
38
|
+
return `${model.name} · Capy credits`;
|
|
39
|
+
if (price.free)
|
|
40
|
+
return `${model.name} · free`;
|
|
41
|
+
return `${model.name} · ${price.tiered ? "from " : ""}${price.input}/${price.output} per 1M`;
|
|
42
|
+
};
|
|
43
|
+
export const modelDescription = (model, price) => {
|
|
44
|
+
if (model.route !== "capy")
|
|
45
|
+
return model.billing ? `Billed to: ${model.billing}` : undefined;
|
|
46
|
+
if (price === undefined)
|
|
47
|
+
return "Billed to Capy credits.";
|
|
48
|
+
if (price.free)
|
|
49
|
+
return "Free: billed to Capy credits at $0.00.";
|
|
50
|
+
const cached = price.cachedInput === undefined ? "" : ` (${price.cachedInput} cached)`;
|
|
51
|
+
return `Billed to Capy credits, per 1M tokens: ${price.input} input${cached}, ${price.output} output${price.tiered ? ", more above a context threshold" : ""}.`;
|
|
52
|
+
};
|
|
53
|
+
/** Capy counts credits in thousandths of a dollar: the Capy app shows `totalCredits / 1000` as USD. */
|
|
54
|
+
export const formatCredits = (credits) => {
|
|
55
|
+
const dollars = credits / 1000;
|
|
56
|
+
if (dollars > 0 && dollars < 0.01)
|
|
57
|
+
return "less than $0.01";
|
|
58
|
+
return `$${dollars.toFixed(2)}`;
|
|
59
|
+
};
|
|
60
|
+
//# sourceMappingURL=pricing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pricing.js","sourceRoot":"","sources":["../src/pricing.ts"],"names":[],"mappings":"AAmBA,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAE,EAAE,CAChC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC,IAAI,EAAE,CAAA;AAE5G,iGAAiG;AACjG,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,QAAgB,EAA8B,EAAE;IAC1E,MAAM,MAAM,GAAG,IAAI,GAAG,EAAiB,CAAA;IACvC,KAAK,MAAM,IAAI,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACxC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAA;QACxD,MAAM,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,+BAA+B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;QAClF,IAAI,IAAI,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,IAAI,GAAG,CAAC;YAAE,SAAQ;QACjD,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAE,CAAC,CAAA;QACxC,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAE,CAAC,CA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,CAAC,KAAK,SAAS,MAAM,KAAK,KAAK,CAAC,MAAM,UAAU,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,kCAAkC,CAAC,CAAC,CAAC,EAAE,GAAG,CAAA;AACjK,CAAC,CAAA;AAED,uGAAuG;AACvG,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,OAAe,EAAU,EAAE;IACvD,MAAM,OAAO,GAAG,OAAO,GAAG,IAAI,CAAA;IAC9B,IAAI,OAAO,GAAG,CAAC,IAAI,OAAO,GAAG,IAAI;QAAE,OAAO,iBAAiB,CAAA;IAC3D,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAA;AACjC,CAAC,CAAA","sourcesContent":["/**\n * Model prices and credit amounts, for the model picker and the cost notice after a turn.\n *\n * `GET /models` gives a model's route but no price, so the adapter reads the price table of the public\n * docs page \"Models & pricing\" (one request per process, with a short timeout). If the page cannot be\n * read or its table changes, models on Capy credits keep the plain \"Capy credits\" label.\n */\nimport type { Model } from \"./capy/client.js\"\n\n/** Prices per 1M tokens, as the docs print them, for example `$0.30`. */\nexport interface Price {\n readonly input: string\n readonly cachedInput: string | undefined\n readonly output: string\n readonly free: boolean\n /** The docs give more than one price tier (by context length); `input` and `output` are the first. */\n readonly tiered: boolean\n}\n\nconst unescape = (cell: string) =>\n cell.replace(/\\\\\\$/g, \"$\").replace(/>/g, \">\").replace(/</g, \"<\").replace(/<br\\s*\\/?>/g, \"; \").trim()\n\n/** Reads `| **Name** | `id` | context | input | output | ... |` rows of the docs price table. */\nexport const parsePrices = (markdown: string): ReadonlyMap<string, Price> => {\n const prices = new Map<string, Price>()\n for (const line of markdown.split(\"\\n\")) {\n const cells = line.split(\"|\").map((cell) => cell.trim())\n const idAt = cells.findIndex((cell) => /^`[a-z0-9][\\w.-]*\\/[\\w.-]+`$/i.test(cell))\n if (idAt < 0 || cells.length < idAt + 4) continue\n const input = unescape(cells[idAt + 2]!)\n const output = unescape(cells[idAt + 3]!)\n const firstInput = /\\$\\d+(?:\\.\\d+)?/.exec(input)?.[0]\n const firstOutput = /\\$\\d+(?:\\.\\d+)?/.exec(output)?.[0]\n if (firstInput === undefined || firstOutput === undefined) continue\n const amounts = [...`${input} ${output}`.matchAll(/\\$(\\d+(?:\\.\\d+)?)/g)].map((m) => Number(m[1]))\n prices.set(cells[idAt]!.slice(1, -1), {\n input: firstInput,\n cachedInput: /cached (\\$\\d+(?:\\.\\d+)?)/.exec(input)?.[1],\n output: firstOutput,\n free: amounts.every((amount) => amount === 0),\n tiered: input.includes(\";\") || output.includes(\";\")\n })\n }\n return prices\n}\n\nexport const fetchPrices = async (url: string, timeoutMs = 3_000): Promise<ReadonlyMap<string, Price>> => {\n const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), headers: { accept: \"text/markdown, text/plain\" } })\n if (!response.ok) throw new Error(`${url} answered ${response.status}`)\n return parsePrices(await response.text())\n}\n\n/** Subscription models keep their name. Models on Capy credits show their price, or \"free\". */\nexport const modelLabel = (model: Pick<Model, \"name\" | \"route\">, price: Price | undefined): string => {\n if (model.route !== \"capy\") return model.name\n if (price === undefined) return `${model.name} · Capy credits`\n if (price.free) return `${model.name} · free`\n return `${model.name} · ${price.tiered ? \"from \" : \"\"}${price.input}/${price.output} per 1M`\n}\n\nexport const modelDescription = (model: Pick<Model, \"billing\" | \"route\">, price: Price | undefined): string | undefined => {\n if (model.route !== \"capy\") return model.billing ? `Billed to: ${model.billing}` : undefined\n if (price === undefined) return \"Billed to Capy credits.\"\n if (price.free) return \"Free: billed to Capy credits at $0.00.\"\n const cached = price.cachedInput === undefined ? \"\" : ` (${price.cachedInput} cached)`\n return `Billed to Capy credits, per 1M tokens: ${price.input} input${cached}, ${price.output} output${price.tiered ? \", more above a context threshold\" : \"\"}.`\n}\n\n/** Capy counts credits in thousandths of a dollar: the Capy app shows `totalCredits / 1000` as USD. */\nexport const formatCredits = (credits: number): string => {\n const dollars = credits / 1000\n if (dollars > 0 && dollars < 0.01) return \"less than $0.01\"\n return `$${dollars.toFixed(2)}`\n}\n"]}
|