capy-acp 0.1.0 → 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/dist/changes.js CHANGED
@@ -1,19 +1,18 @@
1
1
  /**
2
- * Observes what a Capy thread changes in a linked folder, so ACP clients can show real diffs.
2
+ * Observes what a Capy thread changes on disk, so ACP clients can show real diffs.
3
3
  *
4
- * Capy's stream names the tools a call ran but never the files or their contents (docs/capy-api-notes.md, API
5
- * gap 4). In linked mode the thread edits the folder the client has open, so the adapter can see
6
- * the changes itself: it records the working tree when a turn starts, then diffs it after each
7
- * tool call. Strictly read only: `git status`, `git rev-parse`, `git diff --name-only`,
8
- * `git cat-file` and plain file reads. Git LFS smudging is skipped, so a diff never downloads.
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.
9
10
  *
10
- * Attribution is by time: a change is credited to the tool call that just finished. Edits the
11
- * user makes in the same folder during a turn are credited the same way; that is the honest limit
12
- * of observing from outside.
11
+ * Attribution is by time (see turn.ts): a change is credited to the tool call that ran when it happened.
13
12
  */
14
13
  import { execFile } from "node:child_process";
15
14
  import { createHash } from "node:crypto";
16
- import { lstat, readFile, readlink } from "node:fs/promises";
15
+ import { lstat, readdir, readFile, readlink } from "node:fs/promises";
17
16
  import { join } from "node:path";
18
17
  import { promisify } from "node:util";
19
18
  import { Effect } from "effect";
@@ -61,7 +60,9 @@ class Unreadable {
61
60
  this.path = path;
62
61
  }
63
62
  }
64
- export const makeChangeTracker = (root, onError = () => { }) => {
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) => {
65
66
  let head;
66
67
  let known = new Map();
67
68
  /** Set when a baseline could not be taken; the turn then reports no changes rather than wrong ones. */
@@ -125,6 +126,11 @@ export const makeChangeTracker = (root, onError = () => { }) => {
125
126
  onError(`change tracking is off for this turn: ${describe(error)}`);
126
127
  disabled = true;
127
128
  })));
129
+ const fromHead = Effect.gen(function* () {
130
+ disabled = false;
131
+ head = yield* readHead;
132
+ known = new Map();
133
+ });
128
134
  const collect = Effect.gen(function* () {
129
135
  if (disabled)
130
136
  return [];
@@ -148,7 +154,53 @@ export const makeChangeTracker = (root, onError = () => { }) => {
148
154
  onError(`could not read changes in ${root}: ${describe(error)}`);
149
155
  return [];
150
156
  })));
151
- return { baseline, collect };
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
+ };
152
204
  };
153
205
  const describe = (error) => (error instanceof Error ? error.message.split("\n")[0] : String(error));
154
206
  const toChange = (root, relativePath, before, after) => {
@@ -163,36 +215,4 @@ const toChange = (root, relativePath, before, after) => {
163
215
  ...(previewable && after?.text !== undefined ? { newText: after.text } : {})
164
216
  };
165
217
  };
166
- /**
167
- * Folds later changes into earlier ones per path: the first `before` and the last `after` win.
168
- * Used when changes found at the end of a turn join a tool call that already reported some,
169
- * because an ACP `content` update replaces the previous content rather than appending to it.
170
- */
171
- export const mergeChanges = (earlier, later) => {
172
- const byPath = new Map(earlier.map((change) => [change.path, change]));
173
- for (const change of later) {
174
- const first = byPath.get(change.path);
175
- if (first === undefined) {
176
- byPath.set(change.path, change);
177
- continue;
178
- }
179
- const existedBefore = first.operation !== "add";
180
- const existsAfter = change.operation !== "delete";
181
- if (!existedBefore && !existsAfter) {
182
- // Created and deleted within the same turn: nothing left to show.
183
- byPath.delete(change.path);
184
- continue;
185
- }
186
- const previewable = first.previewable && change.previewable;
187
- byPath.set(change.path, {
188
- path: change.path,
189
- relativePath: change.relativePath,
190
- operation: !existedBefore ? "add" : !existsAfter ? "delete" : "modify",
191
- previewable,
192
- ...(previewable && first.oldText !== undefined ? { oldText: first.oldText } : {}),
193
- ...(previewable && change.newText !== undefined ? { newText: change.newText } : {})
194
- });
195
- }
196
- return [...byPath.values()];
197
- };
198
218
  //# sourceMappingURL=changes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"changes.js","sourceRoot":"","sources":["../src/changes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAA;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAC5D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AACrC,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAE/B,MAAM,IAAI,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAA;AAuBhC,qGAAqG;AACrG,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,GAAG,IAAI,CAAA;AAC3C,2GAA2G;AAC3G,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,CAAA;AACpC,MAAM,cAAc,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAA;AAQvC,MAAM,IAAI,GAAG,IAAI,WAAW,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA;AAEtD,MAAM,SAAS,GAAG,CAAC,KAAa,EAAW,EAAE;IAC3C,MAAM,IAAI,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IAC7D,IAAI,KAAK,CAAC,MAAM,GAAG,iBAAiB,IAAI,KAAK,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,QAAQ,CAA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C,QAAQ,CAAC,CAAC,CAAC,QAAQ;YACtE,WAAW;YACX,GAAG,CAAC,WAAW,IAAI,KAAK,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACjF,GAAG,CAAC,WAAW,IAAI,MAAM,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACpF,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,CAAA;AAC7B,CAAC,CAAA","sourcesContent":["/**\n * Observes what a Capy thread changes in a linked folder, 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, API\n * gap 4). In linked mode the thread edits the folder the client has open, so the adapter can see\n * the changes itself: it records the working tree when a turn starts, then diffs it after each\n * tool call. Strictly read only: `git status`, `git rev-parse`, `git diff --name-only`,\n * `git cat-file` and plain file reads. Git LFS smudging is skipped, so a diff never downloads.\n *\n * Attribution is by time: a change is credited to the tool call that just finished. Edits the\n * user makes in the same folder during a turn are credited the same way; that is the honest limit\n * of observing from outside.\n */\nimport { execFile } from \"node:child_process\"\nimport { createHash } from \"node:crypto\"\nimport { lstat, 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 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 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 }\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\n/**\n * Folds later changes into earlier ones per path: the first `before` and the last `after` win.\n * Used when changes found at the end of a turn join a tool call that already reported some,\n * because an ACP `content` update replaces the previous content rather than appending to it.\n */\nexport const mergeChanges = (earlier: ReadonlyArray<FileChange>, later: ReadonlyArray<FileChange>): ReadonlyArray<FileChange> => {\n const byPath = new Map(earlier.map((change) => [change.path, change]))\n for (const change of later) {\n const first = byPath.get(change.path)\n if (first === undefined) {\n byPath.set(change.path, change)\n continue\n }\n const existedBefore = first.operation !== \"add\"\n const existsAfter = change.operation !== \"delete\"\n if (!existedBefore && !existsAfter) {\n // Created and deleted within the same turn: nothing left to show.\n byPath.delete(change.path)\n continue\n }\n const previewable = first.previewable && change.previewable\n byPath.set(change.path, {\n path: change.path,\n relativePath: change.relativePath,\n operation: !existedBefore ? \"add\" : !existsAfter ? \"delete\" : \"modify\",\n previewable,\n ...(previewable && first.oldText !== undefined ? { oldText: first.oldText } : {}),\n ...(previewable && change.newText !== undefined ? { newText: change.newText } : {})\n })\n }\n return [...byPath.values()]\n}\n"]}
1
+ {"version":3,"file":"changes.js","sourceRoot":"","sources":["../src/changes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,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;QAC9B,YAAY;QACZ,SAAS;QACT,WAAW;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 CHANGED
@@ -6,8 +6,9 @@ import { homedir } from "node:os";
6
6
  import { join, posix, win32 } from "node:path";
7
7
  const flag = (value) => value === "1" || value === "true";
8
8
  /**
9
- * Where the Capy desktop app keeps its files: Electron's per-user app data folder. Only the Linux
10
- * location has been seen in practice; `CAPY_DESKTOP_CONFIG_DIR` overrides it.
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").
11
12
  */
12
13
  export const desktopConfigDir = (env, home, platform = process.platform) => {
13
14
  const { join } = platform === "win32" ? win32 : posix;
@@ -23,6 +24,7 @@ export const readConfig = (env = process.env) => {
23
24
  return {
24
25
  apiUrl: (env.CAPY_API_URL ?? "https://api.capy.ai/api/v1").replace(/\/+$/, ""),
25
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",
26
28
  defaultModel: env.CAPY_ACP_MODEL ?? "anthropic/claude-opus-5-5",
27
29
  defaultReasoning: env.CAPY_ACP_REASONING ?? "high",
28
30
  workspaceMode: env.CAPY_ACP_WORKSPACE === "worktree" ? "worktree" : "linked",
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AACjC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AAwB9C,MAAM,IAAI,GAAG,CAAC,KAAyB,EAAE,EAAE,CAAC,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,MAAM,CAAA;AAE7E;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAsB,EAAE,IAAY,EAAE,QAAQ,GAAoB,OAAO,CAAC,QAAQ,EAAU,EAAE;IAC7H,MAAM,EAAE,IAAI,EAAE,GAAG,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAA;IACrD,IAAI,QAAQ,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,qBAAqB,EAAE,MAAM,CAAC,CAAA;IACtF,IAAI,QAAQ,KAAK,OAAO;QAAE,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,SAAS,CAAC,EAAE,MAAM,CAAC,CAAA;IAC9F,OAAO,IAAI,CAAC,GAAG,CAAC,eAAe,IAAI,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,EAAE,MAAM,CAAC,CAAA;AACnE,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,GAAG,GAAsB,OAAO,CAAC,GAAG,EAAiB,EAAE;IAChF,MAAM,IAAI,GAAG,OAAO,EAAE,CAAA;IACtB,MAAM,OAA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QAAQ,CAAC,EAAE,UAAU,EAAE,aAAa,CAAC;KAC5H,CAAA;AACH,CAAC,CAAA","sourcesContent":["/**\n * Adapter settings, read from the environment the ACP client launches us with.\n * T3 Code passes per-instance environment 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 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. Only the Linux\n * location has been seen in practice; `CAPY_DESKTOP_CONFIG_DIR` overrides it.\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 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"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AACjC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AA0B9C,MAAM,IAAI,GAAG,CAAC,KAAyB,EAAE,EAAE,CAAC,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,MAAM,CAAA;AAE7E;;;;GAIG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAsB,EAAE,IAAY,EAAE,QAAQ,GAAoB,OAAO,CAAC,QAAQ,EAAU,EAAE;IA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,GAAG,CAAC,gCAAgC,CAAC;QACjE,cAAc,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,MAAM;QAChF,uBAAuB,EAAE,IAAI,CAAC,GAAG,CAAC,kCAAkC,CAAC;QACrE,gBAAgB,EAAE,GAAG,CAAC,cAAc;QACpC,oBAAoB,EAAE,GAAG,CAAC,uBAAuB,IAAI,gBAAgB,CAAC,GAAG,EAAE,IAAI,CAAC;QAChF,QAAQ,EAAE,GAAG,CAAC,SAAS,IAAI,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC;QAC9C,QAAQ,EAAE,GAAG,CAAC,kBAAkB,IAAI,IAAI,CAAC,GAAG,CAAC,cAAc,IAAI,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAO,CAAC,EAAE,UAAU,EAAE,UAAU,CAAC;QACrH,cAAc,EAAE,GAAG,CAAC,wBAAwB,IAAI,IAAI,CAAC,GAAG,CAAC,cAAc,IAAI,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,UAAU,EAAE,aAAa,CAAC;KAC5H,CAAA;AACH,CAAC,CAAA","sourcesContent":["/**\n * Adapter settings, read from the environment the ACP client launches us with.\n * T3 Code passes per-instance environment 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,EA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,CAAC,OAAO,CAAC,CAAA;QAC1B,CAAC;aAAM,CAAC;YACN,MAAM,EAAE,IAAI,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"]}
@@ -0,0 +1,60 @@
1
+ const unescape = (cell) => cell.replace(/\\\$/g, "$").replace(/&gt;/g, ">").replace(/&lt;/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,OAA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,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(/&gt;/g, \">\").replace(/&lt;/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"]}
@@ -0,0 +1,108 @@
1
+ /** An Error that carries a Problem, for code paths that throw. */
2
+ export class ProblemError extends Error {
3
+ problem;
4
+ constructor(problem) {
5
+ super(`${problem.title}. ${problem.detail}`);
6
+ this.problem = problem;
7
+ }
8
+ }
9
+ export const problemOf = (error) => (error instanceof ProblemError ? error.problem : undefined);
10
+ export const toMarkdown = (problem) => [`**${problem.title}**`, problem.detail, problem.steps.map((step, i) => `${i + 1}. ${step}`).join("\n")]
11
+ .filter((part) => part !== "")
12
+ .join("\n\n");
13
+ export const toText = (problem, indent = "") => [`${problem.title}. ${problem.detail}`, ...problem.steps.map((step, i) => `${indent}${i + 1}. ${step}`)].join("\n");
14
+ const RETRY = "Send your message again.";
15
+ const NEW_SESSION = "Start a new chat in that folder. A session keeps the folder that it opened with.";
16
+ export const noApiKey = (keyFile) => ({
17
+ title: "Add your Capy API key",
18
+ detail: "capy-acp needs a Capy API key to start Capy threads.",
19
+ steps: [
20
+ "Create a key in the Capy app under Settings, then API.",
21
+ `Run \`npx -y capy-acp --setup\` in a terminal and paste the key (it goes to ${keyFile}). If your editor offers Sign in for this agent, that runs the same command. You can also set \`CAPY_API_KEY\` in the agent's environment.`,
22
+ RETRY
23
+ ]
24
+ });
25
+ export const rejectedApiKey = (detail) => ({
26
+ title: "Replace your Capy API key",
27
+ detail: `Capy did not accept the API key (${detail}).`,
28
+ steps: ["Create a new key in the Capy app under Settings, then API.", "Run `npx -y capy-acp --setup` and paste it.", RETRY]
29
+ });
30
+ export const unreachable = (apiUrl, detail) => ({
31
+ title: "Capy could not be reached",
32
+ detail: `${detail}.`,
33
+ steps: [`Check the network connection to ${apiUrl}.`, RETRY]
34
+ });
35
+ export const noDevice = (files) => ({
36
+ title: "Start Capy on this computer",
37
+ detail: "Capy threads run on this computer, and capy-acp found no Capy device here.",
38
+ steps: [
39
+ "Open the Capy desktop app and sign in, or run `capy dock` on a computer without a screen.",
40
+ RETRY,
41
+ `capy-acp 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.`
42
+ ]
43
+ });
44
+ export const unreadableDeviceFile = (file, detail) => ({
45
+ title: "Check the Capy desktop app",
46
+ detail: `capy-acp could not read the device file ${file} (${detail}).`,
47
+ steps: ["Restart the Capy desktop app, or set `CAPY_DEVICE_ID` to the id of this computer's Capy device.", RETRY]
48
+ });
49
+ export const manyOrganizations = (count) => ({
50
+ title: "Choose a Capy organization",
51
+ detail: `This computer is paired with ${count} Capy organizations, so capy-acp cannot tell which device to use.`,
52
+ steps: ["Set `CAPY_DEVICE_ID` in the agent's environment to the device id of the organization that you want.", RETRY]
53
+ });
54
+ const isT3Scratch = (folder) => {
55
+ const parts = folder.split(/[\\/]+/);
56
+ return parts.some((part, i) => part === ".t3" && parts[i + 1] === "scratch");
57
+ };
58
+ export const notGit = (folder) => isT3Scratch(folder)
59
+ ? {
60
+ title: "Open a project to use Capy",
61
+ detail: "T3 Code started this chat without a project. Capy threads run on a GitHub repository from one of your Capy projects.",
62
+ steps: ["In T3 Code, add a project for a clone of that repository.", "Start a new chat in that project."]
63
+ }
64
+ : {
65
+ title: "Open a repository to use Capy",
66
+ detail: `${folder} is not in a git repository. Capy threads run on a GitHub repository from one of your Capy projects.`,
67
+ steps: ["Open a clone of that repository in your editor.", NEW_SESSION]
68
+ };
69
+ export const noGitHubRemote = (gitRoot) => ({
70
+ title: "Add the GitHub remote",
71
+ detail: `${gitRoot} has no git remote that names a GitHub repository, so capy-acp cannot find its Capy project.`,
72
+ steps: ["Add the remote, for example `git remote add origin git@github.com:owner/repo.git`.", RETRY]
73
+ });
74
+ export const notInProject = (repos) => ({
75
+ title: `Add ${repos[0]} to a Capy project`,
76
+ detail: `No Capy project includes ${repos.join(" or ")}.`,
77
+ steps: ["Open https://capy.ai/settings/projects and add the repository to a project.", RETRY]
78
+ });
79
+ const linkSteps = (input) => {
80
+ // Only the device itself can link a local folder: the desktop app, or `capy dock dirs add`. The
81
+ // web app cannot. `capy://app/<path>` opens that page of the desktop app (checked in 0.10.0).
82
+ 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}.`;
83
+ const dock = [
84
+ "Stop `capy dock`. Caution: this also stops the Capy threads that run on this computer.",
85
+ `Run \`capy dock dirs add ${input.root}\`, then start \`capy dock\` again.`
86
+ ];
87
+ if (input.device === "desktop")
88
+ return [desktop];
89
+ if (input.device === "dock")
90
+ return dock;
91
+ return [`With the desktop app: ${desktop}`, `With \`capy dock\`: ${dock.join(" ")}`];
92
+ };
93
+ export const notLinked = (input) => input.sameRepoRoot === undefined
94
+ ? {
95
+ title: "Link this folder to Capy",
96
+ detail: `Capy runs threads only in folders that are linked to this computer, and ${input.root} is not linked.`,
97
+ steps: [...linkSteps(input), RETRY]
98
+ }
99
+ : {
100
+ title: `Use the folder that Capy links for ${input.repo}`,
101
+ detail: `On this computer, Capy links ${input.repo} at ${input.sameRepoRoot}, not at ${input.root}.`,
102
+ steps: [
103
+ `Open ${input.sameRepoRoot} in your editor, and start a new chat there.`,
104
+ `Or link ${input.root} instead. ${linkSteps(input).join(" ")} Then send your message again.`,
105
+ `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}.`
106
+ ]
107
+ };
108
+ //# sourceMappingURL=problems.js.map