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/README.md CHANGED
@@ -7,34 +7,35 @@ capy-acp runs [Capy](https://capy.ai) coding-agent threads from an [Agent Client
7
7
  folder that you open, with your tools. Device threads use no Capy machine time. The model runs on your connected subscription,
8
8
  unless you select a model that Capy bills to credits.
9
9
 
10
- capy-acp is an independent project. Capy did not make it. Version 0.1 has these test results:
11
-
12
- - Linux x64: Capy desktop app 0.6.0, T3 Code 0.1.12, Node 22.
13
- - macOS 26 arm64: `capy dock` 0.7.2, Node 26, an ACP test client.
14
- - Windows Server 2022 x64: `capy dock` 0.7.2, Node 24, an ACP test client.
15
-
16
- Read [Limitations](#limitations) before you use it.
10
+ capy-acp is an independent project. Capy did not make it. Read [Limitations](#limitations) and [Tests](#tests) before you use
11
+ it.
17
12
 
18
13
  ## What the client shows
19
14
 
20
15
  - The reply from Capy, streamed as Capy writes it.
21
16
  - One item for each Capy tool call. The title gives the tools and the time, for example `bash, write (1.2 s)`.
22
17
  - A diff of each file that a tool call changed, for example `Edited README.md and scripts/greet.sh`. The Capy stream does not
23
- give paths or contents. After each tool call, the adapter reads the changes from your folder with git (read only). Edits that
24
- you made before the prompt do not count.
18
+ give paths or contents. The adapter reads the changes with git (read only), in your folder or in the Capy worktree of the
19
+ thread. It looks when a tool call starts and when it ends. Edits that you made before the prompt do not count. A change that
20
+ occurs while no Capy tool call can write, for example your own edit between two calls, gets its own item:
21
+ `Edited notes.md outside a Capy tool call`.
25
22
  - Images, audio and other files that you attach. They go to Capy with the message, and Capy models see attached images.
26
23
  - Files that Capy attaches to a reply, as links. A file that Capy made on this machine links to its local path. Other files link
27
24
  to a Capy download URL, which expires.
28
25
  - Capy subagents, as items that show their status: pending, running, completed or failed.
26
+ - The models of your Capy account. A model that Capy bills to credits shows its price, for example
27
+ `Inkling 2 Small · $0.30/$1.00 per 1M`, or `Particle-1 · free`. After a turn that used Capy credits, a notice gives the
28
+ amount.
29
29
 
30
30
  The adapter also does these things:
31
31
 
32
- - Cancel stops the Capy thread. A follow-up message continues the same thread.
32
+ - Cancel stops the Capy thread. The call that the cancel stopped shows as failed, and calls that finished before it show as
33
+ completed. A follow-up message continues the same thread.
33
34
  - Sessions stay available after a restart. `session/load` replays the thread transcript, and `session/resume` connects again
34
35
  without a replay. `session/list` lists the saved sessions. The next prompt continues the same Capy thread.
35
36
  - If the connection drops, the adapter connects again and continues from the last event. It shows each event one time.
36
- - If the setup has a problem, the reply tells you how to fix it. Examples are a missing API key, a folder that is not linked,
37
- or a repository that is not in a Capy project. Fix the problem and send the message again. You do not need a new session or a
37
+ - If the setup has a problem, the reply tells you how to fix it. Examples are a key that Capy rejects, a folder that is not
38
+ linked, or a repository that is not in a Capy project. (Without a key, the client shows the agent as signed out.) Fix the problem and send the message again. You do not need a new session or a
38
39
  restart.
39
40
 
40
41
  ## Permissions
@@ -47,13 +48,17 @@ message or in `AGENTS.md`, or change the Capy settings. The Capy docs say that C
47
48
 
48
49
  - Node 22 or later.
49
50
  - A Capy device on this machine. Sign in to the Capy desktop app, or run the headless `capy dock`.
50
- - A GitHub repository in a Capy project, cloned with an `origin` remote.
51
- - The folder of that clone, linked to this device. Use one of these:
52
- - Capy settings: Projects, then your project, then Project folders.
53
- - Scan a folder in the Capy desktop app.
54
- - `capy dock dirs add <path>`, while the dock is stopped.
51
+ - A clone of a GitHub repository that is in a Capy project. Any git remote of the clone can name the repository.
52
+ - The folder of that clone, linked to this device. Only the device can link a folder, so the Capy website cannot do it:
53
+ - Desktop app: open the project in Settings, then Projects (`capy://app/settings/projects/<project id>` opens it), set it
54
+ up on this computer, and choose the folder. Scan a folder also works.
55
+ - `capy dock`: stop the dock, run `capy dock dirs add <path>`, and start the dock again. Stopping the dock stops the Capy
56
+ threads that run on this computer.
57
+
58
+ If Capy links another clone of the same repository on this computer, the first reply names that folder.
55
59
  - A Capy API key. Create one in the Capy app under Settings, then API. To save it, run `npx -y capy-acp --setup`. The command
56
- checks the key with Capy and writes it to `~/.config/capy-acp/api-key` with mode 0600. You can also set `CAPY_API_KEY`.
60
+ checks the key with Capy and writes it to `~/.config/capy-acp/api-key` with mode 0600. It also reads the key from a pipe,
61
+ for scripts: `capy-acp --setup < key-file`. You can also set `CAPY_API_KEY`.
57
62
 
58
63
  ## Setup
59
64
 
@@ -70,7 +75,28 @@ In **other ACP clients**, set the agent command to `npx -y capy-acp`. Set the wo
70
75
  folder. The tests used only T3 Code as a client.
71
76
 
72
77
  capy-acp announces `capy-acp --setup` as a terminal auth method. A client that supports terminal auth can run the setup for
73
- you.
78
+ you. Until a key is saved, `session/new` fails with `auth_required`, so T3 Code shows the agent as signed out and offers
79
+ the setup.
80
+
81
+ To give the key in T3 Code instead, add `CAPY_API_KEY` to the environment of the provider instance. In
82
+ `~/.t3/userdata/settings.json`, the instance takes `environment: [{ "name": "CAPY_API_KEY", "value": "…", "sensitive": true }]`.
83
+ The other [settings](#settings) go in the same list.
84
+
85
+ ### Install without npx
86
+
87
+ `npx -y capy-acp` downloads the newest version when its cache is empty. To pin a version, install it in a folder of its own and
88
+ run that copy:
89
+
90
+ ```sh
91
+ npm install --prefix ~/.local/opt/capy-acp capy-acp@0.2.0
92
+ ```
93
+
94
+ Then set the command to `node` with the argument `~/.local/opt/capy-acp/node_modules/capy-acp/dist/bin.js`, as an absolute
95
+ path. Use the absolute path of `node` too if your editor does not start from a login shell. A version manager such as fnm can
96
+ give `which node` a path that changes in each shell, so use the path of the installed Node version instead.
97
+
98
+ On **Windows**, T3 Code starts the command without a shell and refuses `.cmd` files such as `npx.cmd`. Set the command to the
99
+ absolute path of `node.exe`, with the absolute path of `dist\bin.js` as the argument.
74
100
 
75
101
  ## Settings
76
102
 
@@ -78,15 +104,16 @@ you.
78
104
  | --- | --- | --- |
79
105
  | `CAPY_API_KEY` | (unset) | The Capy API key. The adapter reads it for each request, so a new key needs no restart |
80
106
  | `CAPY_API_KEY_FILE` | `~/.config/capy-acp/api-key` | The file with the key, if `CAPY_API_KEY` is not set |
107
+ | `CAPY_ACP_PRICING_URL` | `https://docs.capy.ai/models-and-pricing.md` | The page with the model price table. An empty value turns the prices off |
81
108
  | `CAPY_ACP_MODEL` | `anthropic/claude-opus-5-5` | The first model of a session. The model picker lists all models of your Capy account and labels the models that Capy bills to credits |
82
109
  | `CAPY_ACP_REASONING` | `high` | The first reasoning level. If a model does not offer this level, the adapter uses the last level that the model lists |
83
- | `CAPY_ACP_WORKSPACE` | `linked` | `linked`: Capy edits the folder that you opened. `worktree`: each session gets a new Capy worktree, and the client shows no diffs |
110
+ | `CAPY_ACP_WORKSPACE` | `linked` | `linked`: Capy edits the folder that you opened. `worktree`: each session gets a new Capy worktree, in the worktree folder of Capy (`~/.capy/worktrees` by default). The diffs show the files there |
84
111
  | `CAPY_ACP_ALLOW_WORKTREE_FALLBACK` | off | For a clone that is not linked, use a worktree of a linked folder of the same repository |
85
112
  | `CAPY_ACP_WAITING_LIMIT_MS` | `600000` | The time that a prompt stays open while Capy waits for a background command |
86
113
  | `CAPY_ACP_FORWARD_HOST_INSTRUCTIONS` | off | Send the host instructions from T3 Code to Capy. Without this setting, the adapter sends only the request of the user |
87
114
  | `CAPY_DEVICE_ID` | from the desktop app or `capy dock` | The device to use, if the machine has a device in more than one organization |
88
115
  | `CAPY_DESKTOP_CONFIG_DIR` | `~/.config/Capy` (Linux), `~/Library/Application Support/Capy` (macOS), `%APPDATA%\Capy` (Windows) | The folder of the desktop app file `device-ids.json` |
89
- | `CAPY_HOME` | `~/.capy` | The folder of `device/workspaces.json` (the linked folders) and, for `capy dock`, `dock/status.json` |
116
+ | `CAPY_HOME` | `~/.capy` | The folder of `worktrees`, `device/workspaces.json` (the linked folders) and, for `capy dock`, `dock/status.json` |
90
117
  | `CAPY_ACP_STATE_DIR` | `~/.local/state/capy-acp/sessions` | The saved sessions: one small JSON file for each session, with ids, the stream cursor and the model. No credentials |
91
118
  | `CAPY_ACP_ATTACHMENTS_DIR` | `~/.cache/capy-acp/attachments` | The folder for files from the *first* prompt of a thread (see below) |
92
119
 
@@ -98,33 +125,46 @@ gives their paths, and the device agent reads them on this machine. Follow-up me
98
125
 
99
126
  ## Limitations
100
127
 
101
- - **The adapter finds the device in local Capy files.** The Capy public API cannot list devices or linked folders. The adapter
102
- reads `device-ids.json` (desktop app) or `~/.capy/dock/status.json` (`capy dock`), and `workspaces.json`. It never writes
103
- these files. If a Capy update moves or changes them, setup fails, and the reply gives the file that the adapter could not
104
- read. The macOS and Windows paths of the desktop app are the Electron defaults, and no test used them. If your paths are
105
- different, set `CAPY_DESKTOP_CONFIG_DIR` and `CAPY_HOME`.
106
- - **Tool items show tool names and times, but no commands or output.** The Capy stream does not give them. In linked mode, the
107
- diffs show the file changes. In worktree mode, the client shows no diffs.
128
+ The first four come from Capy. [docs/capy-api-notes.md](docs/capy-api-notes.md) lists the API changes that would remove the
129
+ first three.
130
+
131
+ - **Tool items show tool names and times, but no commands or output.** The Capy stream does not give them. The diffs show the
132
+ file changes.
108
133
  - **The client shows no reasoning, plan or token usage.** The Capy stream does not give them.
109
- - **The adapter works only with GitHub repositories**, which it finds from the `origin` remote.
110
- - Tests saw delivered files and subagents only with `capy dock` on macOS and Windows: one text file, and one subagent on the
111
- same machine. No test used a subagent on a new cloud machine.
112
- - On macOS and Windows, an ACP test client operated the adapter. T3 Code did not.
113
- - After a cancel, the client shows the stopped tool call as failed. This is also true for a call that completed just before the
114
- cancel, because the Capy transcript does not show the difference.
115
- - If you edit files in the folder while Capy works, the diffs show your edits as part of the current Capy tool call.
134
+ - **The adapter reads the device id from a local Capy file.** The Capy API cannot list devices. The file is `device-ids.json`
135
+ of the desktop app, or `~/.capy/dock/status.json` of `capy dock`. The adapter never writes it. If a Capy update moves it,
136
+ setup fails, and the reply names the file. Set `CAPY_DEVICE_ID` to continue.
137
+ - **Capy works only with repositories on GitHub.com.**
138
+ - **If you edit a file while a Capy tool call that can write runs, the diffs show your edit as part of that call.** The adapter
139
+ sees only the files, not the process that changed them.
140
+
141
+ ## Tests
142
+
143
+ | Platform | Capy | Client | Checks |
144
+ | --- | --- | --- | --- |
145
+ | Linux x64, Node 22 to 26 | Desktop app 0.6.0 | T3 Code 0.1.12, ACP test client | All the items in [What the client shows](#what-the-client-shows), and restarts |
146
+ | macOS 26 arm64, Node 26 | `capy dock` 0.7.2 | ACP test client | Prompts, cancel, a dropped stream, a delivered file, a subagent |
147
+ | Windows Server 2022 x64, Node 24 | `capy dock` 0.7.2 | ACP test client | The macOS checks, and diffs in linked mode and worktree mode |
148
+
149
+ CI runs the unit tests on Linux. The unit tests also pass on macOS and Windows. These cases had no test:
150
+
151
+ - T3 Code on macOS or Windows.
152
+ - The desktop app on macOS or Windows. The adapter finds its files in the folders that the code of the app sets.
153
+ - A subagent on a new cloud machine.
116
154
 
117
155
  ## Troubleshooting
118
156
 
119
- The adapter writes its log to stderr. These are common first replies:
157
+ Run `npx -y capy-acp --doctor` in the project folder. It checks Node, the API key, the device and the folder, and prints a
158
+ fix for each problem. It also says if npm has a newer capy-acp. The adapter writes its log to stderr. These are common first replies:
120
159
 
121
160
  | Reply | Fix |
122
161
  | --- | --- |
123
- | `No Capy API key` | Run `npx -y capy-acp --setup`, or set `CAPY_API_KEY`. Then send the message again |
124
- | `No paired Capy device found` | Sign in to the Capy desktop app, or run `capy dock`. Or set `CAPY_DEVICE_ID`, and `CAPY_DESKTOP_CONFIG_DIR` or `CAPY_HOME` |
125
- | `… is not a clone of a GitHub repository` | Open the folder of the repository. Its `origin` remote must point to GitHub |
126
- | `No Capy project includes owner/repo` | Add the repository to a Capy project |
127
- | `… is not a linked folder on this Capy device` | Link the folder in Capy as the reply tells you. Then send the message again |
162
+ | T3 Code shows the agent as signed out | Run `npx -y capy-acp --setup`, or set `CAPY_API_KEY` |
163
+ | **Start Capy on this computer** | Sign in to the Capy desktop app, or run `capy dock`. The reply lists each file that capy-acp read. Or set `CAPY_DEVICE_ID`, and `CAPY_DESKTOP_CONFIG_DIR` or `CAPY_HOME` |
164
+ | **Open a repository to use Capy**, or **Add the GitHub remote** | Open the folder of a clone. One of its remotes must name the GitHub repository |
165
+ | **Add owner/repo to a Capy project** | Add the repository to a Capy project |
166
+ | **Link this folder to Capy** | Link the folder as the reply tells you. Then send the message again |
167
+ | **Use the folder that Capy links for owner/repo** | Open the folder that the reply names, link this folder instead, or set `CAPY_ACP_ALLOW_WORKTREE_FALLBACK=1` |
128
168
  | `Capy has not started on this message yet` | Make sure that the Capy desktop app or `capy dock` runs and is signed in. The message stays in the thread queue |
129
169
 
130
170
  ## Development
@@ -137,8 +177,8 @@ node spike/acp-client.ts <folder> "<prompt>" ["<follow-up>"] [--cancel-after-ms
137
177
  ```
138
178
 
139
179
  The tests replay recorded Capy streams from `fixtures/`. They operate the agent over a real ACP connection with a fake Capy
140
- client. [`docs/capy-api-notes.md`](docs/capy-api-notes.md) records what the recordings showed about the Capy API, the design
141
- decisions, and feedback for the API.
180
+ client. [`docs/design.md`](docs/design.md) explains how the adapter works around the Capy API, and
181
+ [`docs/capy-api-notes.md`](docs/capy-api-notes.md) is the feedback for Capy: ranked asks, with evidence from the recordings.
142
182
 
143
183
  ## License
144
184
 
package/dist/agent.js CHANGED
@@ -10,24 +10,22 @@
10
10
  import { randomUUID } from "node:crypto";
11
11
  import * as acp from "@agentclientprotocol/sdk";
12
12
  import { Cause, Deferred, Effect, Exit, ManagedRuntime } from "effect";
13
- import { CapyClient, describeError, layer as capyLayer } from "./capy/client.js";
14
- import { makeChangeTracker } from "./changes.js";
13
+ import { CapyClient, describeError, isCapyError, layer as capyLayer } from "./capy/client.js";
14
+ import { makeChangeTracker, makeWorktreeTracker } from "./changes.js";
15
+ import { fetchPrices, formatCredits, modelDescription, modelLabel } from "./pricing.js";
16
+ import { noApiKey, problemOf, rejectedApiKey, toMarkdown, unreachable } from "./problems.js";
15
17
  import { promptParts } from "./prompt.js";
16
18
  import { API_KEY_AUTH, savedApiKey } from "./setup.js";
17
19
  import { makeSessionStore } from "./store.js";
18
20
  import { history } from "./translate.js";
19
21
  import { fileLink, runTurn, titleOf } from "./turn.js";
20
22
  import { AGENT_NAME, AGENT_VERSION } from "./version.js";
21
- import { readDeviceId, readGit, readLinkedFolders, resolveWorkspace } from "./workspace.js";
23
+ import { readDevice, readGit, readLinkedFolders, resolveWorkspace } from "./workspace.js";
22
24
  /** A Capy stream event id (a ULID), the only thing a stream cursor may be. */
23
25
  const EVENT_ID = /^[0-9A-HJKMNP-TV-Z]{26}$/;
24
26
  const log = (message) => process.stderr.write(`[capy-acp] ${message}\n`);
25
- /** Models billed to Capy credits are labelled, since device threads otherwise cost nothing. */
26
- const modelLabel = (model) => (model.route === "capy" ? `${model.name} (Capy credits)` : model.name);
27
27
  /** Capy's answer when a linked root is not (or no longer) linked to this device. */
28
28
  const isNotLinked = (error) => error._tag === "CapyApiError" && /does not link a folder/i.test(error.message);
29
- const linkFix = (root, projectName) => `Link it to this device in Capy: open https://capy.ai/settings/projects, choose "${projectName}", and add ${root} under ` +
30
- "Project folders (or use Scan a folder in the Capy desktop app). Then send your message again.";
31
29
  /** The reasoning level a session really sends: its own when the model offers it, else the model's highest. */
32
30
  const effectiveReasoning = (reasoning, modes) => modes.includes(reasoning) ? reasoning : modes.at(-1);
33
31
  export const makeAgent = (config, capy = capyLayer(config)) => {
@@ -35,6 +33,7 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
35
33
  const sessions = new Map();
36
34
  const store = makeSessionStore(config.stateDir);
37
35
  let models;
36
+ let prices;
38
37
  /** Saves the session → thread mapping. A failed write costs only resumability, so it is logged. */
39
38
  const persist = async (sessionId, session) => {
40
39
  if (session.threadId === undefined)
@@ -69,12 +68,49 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
69
68
  const withCapy = (f) => Effect.gen(function* () {
70
69
  return yield* f(yield* CapyClient);
71
70
  });
71
+ const loadPrices = () => (prices ??= config.pricingUrl === ""
72
+ ? Promise.resolve(new Map())
73
+ : fetchPrices(config.pricingUrl).catch((error) => {
74
+ log(`no model prices: ${error instanceof Error ? error.message : String(error)}`);
75
+ return new Map();
76
+ }));
72
77
  const loadModels = async () => {
73
- if (models === undefined)
78
+ if (models === undefined) {
79
+ void loadPrices();
74
80
  models = await run(withCapy((capy) => capy.listModels));
81
+ }
75
82
  return models;
76
83
  };
77
- const configOptions = (session, available) => {
84
+ /**
85
+ * Shows what the turn added to the thread's Capy credits, as an ACP notice. Turns on a subscription
86
+ * add nothing and show nothing. Capy can book a turn's credits late; they then show after the next turn.
87
+ */
88
+ const reportCredits = async (session, notify) => {
89
+ const before = session.credits;
90
+ const usage = await readCredits(session.threadId);
91
+ if (usage === undefined)
92
+ return;
93
+ session.credits = usage.totalCredits;
94
+ if (before === undefined || usage.totalCredits <= before)
95
+ return;
96
+ const parts = [
97
+ ["models", usage.llmCredits],
98
+ ["machines", usage.vmCredits],
99
+ ["images", usage.imageCredits]
100
+ ].flatMap(([name, credits]) => (typeof credits === "number" && credits > 0 ? [`${name} ${formatCredits(credits)}`] : []));
101
+ await notify({
102
+ sessionUpdate: "notice",
103
+ severity: "info",
104
+ title: `Capy credits: ${formatCredits(usage.totalCredits - before)}`,
105
+ description: `This thread has used ${formatCredits(usage.totalCredits)} of Capy credits${parts.length > 1 ? ` (${parts.join(", ")})` : ""}.`
106
+ });
107
+ };
108
+ /** The thread's credit total, or undefined when Capy does not answer. Never fails the prompt. */
109
+ const readCredits = async (threadId) => {
110
+ const exit = await runtime.runPromiseExit(withCapy((capy) => capy.getThread(threadId)));
111
+ return Exit.isSuccess(exit) ? exit.value.usage : undefined;
112
+ };
113
+ const configOptions = (session, available, priced) => {
78
114
  const current = available.find((m) => m.id === session.model);
79
115
  const modes = current?.reasoningModes ?? [];
80
116
  const options = [
@@ -84,7 +120,10 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
84
120
  category: "model",
85
121
  type: "select",
86
122
  currentValue: session.model,
87
- options: (current === undefined ? [{ id: session.model, name: session.model }, ...available] : available).map((m) => ({ value: m.id, name: modelLabel(m), ...(m.billing ? { description: `Billed to: ${m.billing}` } : {}) }))
123
+ options: (current === undefined ? [{ id: session.model, name: session.model }, ...available] : available).map((m) => {
124
+ const description = modelDescription(m, priced.get(m.id));
125
+ return { value: m.id, name: modelLabel(m, priced.get(m.id)), ...(description === undefined ? {} : { description }) };
126
+ })
88
127
  }
89
128
  ];
90
129
  if (modes.length > 0) {
@@ -105,21 +144,35 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
105
144
  if (Exit.isSuccess(exit))
106
145
  return exit.value;
107
146
  const failure = exit.cause.reasons.find(Cause.isFailReason);
108
- throw new Error(failure === undefined ? Cause.pretty(exit.cause) : describeError(failure.error));
147
+ throw failure === undefined ? new Error(Cause.pretty(exit.cause)) : failure.error;
148
+ };
149
+ /** The fix for a failed setup step: a missing or rejected key, no network, no device. */
150
+ const setupProblem = (reason) => {
151
+ const known = problemOf(reason);
152
+ if (known !== undefined)
153
+ return known;
154
+ if (isCapyError(reason)) {
155
+ if (reason._tag === "CapyConfigError")
156
+ return noApiKey(config.apiKeyFile);
157
+ if (reason._tag === "CapyApiError" && (reason.status === 401 || reason.status === 403))
158
+ return rejectedApiKey(describeError(reason));
159
+ return unreachable(config.apiUrl, describeError(reason));
160
+ }
161
+ return { title: "capy-acp could not start", detail: reason instanceof Error ? reason.message : String(reason), steps: ["Send your message again."] };
109
162
  };
110
163
  /** Folder → project → device workspace. Never throws: failures become the session's `problem`. */
111
- const setUp = async (cwd) => {
112
- const [projects, deviceId, linked, git] = await Promise.allSettled([
164
+ const setUp = async (cwd, threadId) => {
165
+ const [projects, device, linked, git] = await Promise.allSettled([
113
166
  attempt(withCapy((capy) => capy.listProjects)),
114
- readDeviceId(config),
167
+ readDevice(config),
115
168
  readLinkedFolders(config),
116
169
  readGit(cwd)
117
170
  ]);
118
171
  // Reported in this order: the API key first, then the paired device, since nothing else can be
119
172
  // fixed without them. (Folder and git reads never reject.)
120
- if (projects.status === "rejected" || deviceId.status === "rejected" || linked.status === "rejected" || git.status === "rejected") {
121
- const reason = [projects, deviceId, linked, git].flatMap((r) => (r.status === "rejected" ? [r.reason] : []))[0];
122
- return { deviceId: "", resolved: undefined, problem: reason instanceof Error ? reason.message : String(reason), changes: undefined };
173
+ if (projects.status === "rejected" || device.status === "rejected" || linked.status === "rejected" || git.status === "rejected") {
174
+ const reason = [projects, device, linked, git].flatMap((r) => (r.status === "rejected" ? [r.reason] : []))[0];
175
+ return { deviceId: "", resolved: undefined, problem: setupProblem(reason), changes: undefined };
123
176
  }
124
177
  const resolution = resolveWorkspace({
125
178
  cwd,
@@ -127,13 +180,21 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
127
180
  linked: linked.value,
128
181
  projects: projects.value,
129
182
  mode: config.workspaceMode,
130
- allowWorktreeFallback: config.allowWorktreeFallback
183
+ allowWorktreeFallback: config.allowWorktreeFallback,
184
+ device: device.value.kind
131
185
  });
132
186
  if (resolution._tag === "Unresolved")
133
- return { deviceId: deviceId.value, resolved: undefined, problem: resolution.message, changes: undefined };
187
+ return { deviceId: device.value.id, resolved: undefined, problem: resolution.problem, changes: undefined };
134
188
  const workspace = resolution.value.workspace;
135
- const changes = workspace.kind === "linked" ? makeChangeTracker(workspace.root, (message) => log(message)) : undefined;
136
- return { deviceId: deviceId.value, resolved: resolution.value, problem: undefined, changes };
189
+ const changes = workspace.kind === "linked"
190
+ ? makeChangeTracker(workspace.root, log)
191
+ : makeWorktreeTracker(config.capyHome, resolution.value.repo, threadId, log);
192
+ return { deviceId: device.value.id, resolved: resolution.value, problem: undefined, changes };
193
+ };
194
+ const requireApiKey = async () => {
195
+ if ((await savedApiKey(config)) === undefined) {
196
+ throw acp.RequestError.authRequired(undefined, "No Capy API key. Run `npx -y capy-acp --setup`, or set CAPY_API_KEY.");
197
+ }
137
198
  };
138
199
  /** A saved session to continue. A session that never sent a prompt has no record, and opens empty. */
139
200
  const restorable = async (sessionId) => {
@@ -148,7 +209,8 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
148
209
  const folder = record?.cwd ?? cwd;
149
210
  if (record !== undefined && record.cwd !== cwd)
150
211
  log(`session ${sessionId}: client opened ${cwd}; the thread works in ${record.cwd}`);
151
- const setup = await setUp(folder);
212
+ void loadPrices();
213
+ const setup = await setUp(folder, () => sessions.get(sessionId)?.threadId);
152
214
  const available = await loadModels().catch(() => []);
153
215
  const session = {
154
216
  ...setup,
@@ -161,13 +223,14 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
161
223
  noteShown: record !== undefined,
162
224
  busy: false,
163
225
  closed: false,
164
- cancel: undefined
226
+ cancel: undefined,
227
+ credits: undefined
165
228
  };
166
229
  sessions.set(sessionId, session);
167
230
  log(setup.resolved === undefined
168
- ? `session ${sessionId}: cannot run in ${folder}: ${setup.problem}`
231
+ ? `session ${sessionId}: cannot run in ${folder}: ${setup.problem?.title}`
169
232
  : `session ${sessionId}: ${setup.resolved.repo} in project ${setup.resolved.projectName} (${setup.resolved.workspace.kind})`);
170
- return configOptions(session, available);
233
+ return configOptions(session, available, await loadPrices());
171
234
  };
172
235
  const app = acp
173
236
  .agent({ name: AGENT_NAME })
@@ -180,19 +243,19 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
180
243
  sessionCapabilities: { list: {}, resume: {}, close: {} }
181
244
  },
182
245
  agentInfo: { name: AGENT_NAME, title: "Capy", version: AGENT_VERSION },
183
- // Without a key, prompts still open and answer with the fix; this method lets a client offer setup.
246
+ // Without a key, sessions fail with auth_required; this method lets a client offer setup.
184
247
  authMethods: [API_KEY_AUTH]
185
248
  }))
186
249
  .onRequest(acp.methods.agent.authenticate, async () => {
187
- if ((await savedApiKey(config)) === undefined) {
188
- throw acp.RequestError.authRequired(undefined, `No Capy API key. Run capy-acp --setup, or set CAPY_API_KEY.`);
189
- }
250
+ await requireApiKey();
190
251
  return {};
191
252
  })
192
253
  .onRequest(acp.methods.agent.session.new, async ({ params }) => {
193
- // Setup problems become the session's first reply instead of a session/new error: T3 Code
254
+ // A missing key fails here with auth_required, so clients offer sign-in (T3 Code shows the
255
+ // agent as signed out). Other setup problems become the session's first reply instead: T3 Code
194
256
  // shows only "Provider session failed to open" and drops the error's message, which here
195
257
  // always names the fix. Each prompt re-checks, so linking the folder needs no new session.
258
+ await requireApiKey();
196
259
  const sessionId = randomUUID();
197
260
  return { sessionId, configOptions: await openSession(sessionId, params.cwd, undefined) };
198
261
  })
@@ -280,7 +343,7 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
280
343
  throw acp.RequestError.invalidParams(undefined, `Unknown option ${params.configId}`);
281
344
  }
282
345
  await persist(params.sessionId, session);
283
- return { configOptions: configOptions(session, available) };
346
+ return { configOptions: configOptions(session, available, await loadPrices()) };
284
347
  })
285
348
  .onRequest(acp.methods.agent.session.prompt, async ({ params, client }) => {
286
349
  const session = sessions.get(params.sessionId);
@@ -303,7 +366,7 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
303
366
  try {
304
367
  if (session.resolved === undefined) {
305
368
  // The user may have fixed the setup (linked the folder, added the repo) since the last try.
306
- Object.assign(session, await setUp(session.cwd));
369
+ Object.assign(session, await setUp(session.cwd, () => session.threadId));
307
370
  if (session.resolved !== undefined)
308
371
  log(`session ${params.sessionId}: setup resolved on retry`);
309
372
  }
@@ -311,13 +374,19 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
311
374
  return { stopReason: "cancelled" };
312
375
  const resolved = session.resolved;
313
376
  if (resolved === undefined) {
314
- await say(`capy-acp can't run here. ${session.problem ?? ""}`);
377
+ if (session.problem !== undefined)
378
+ await say(toMarkdown(session.problem));
315
379
  return ended;
316
380
  }
317
381
  if (!session.noteShown && resolved.note !== undefined) {
318
382
  session.noteShown = true;
319
383
  await say(`_${resolved.note}_\n\n`);
320
384
  }
385
+ // A new thread starts at 0 credits.
386
+ if (session.threadId === undefined)
387
+ session.credits = 0;
388
+ else if (session.credits === undefined)
389
+ session.credits = (await readCredits(session.threadId))?.totalCredits;
321
390
  const reasoningModes = (await loadModels().catch(() => [])).find((m) => m.id === session.model)?.reasoningModes ?? [];
322
391
  const reasoningMode = effectiveReasoning(session.reasoning, reasoningModes);
323
392
  const exit = await runtime.runPromiseExit(runTurn({
@@ -351,16 +420,22 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
351
420
  log(`session ${params.sessionId}: ${describeError(error)}`);
352
421
  if (resolved.workspace.kind === "linked" && session.threadId === undefined && isNotLinked(error)) {
353
422
  // The folder list on disk can lag the server, or the link was removed: say how to fix it.
354
- const root = resolved.workspace.root;
355
- Object.assign(session, {
356
- resolved: undefined,
357
- changes: undefined,
358
- problem: `Capy says this device does not link ${root}. ${linkFix(root, resolved.projectName)}`
359
- });
360
- await say(`capy-acp can't run here. ${session.problem}`);
423
+ Object.assign(session, { resolved: undefined, changes: undefined, problem: resolved.notLinked });
424
+ await say(toMarkdown(resolved.notLinked));
425
+ }
426
+ else if (error._tag === "CapyApiError" && error.status >= 400 && error.status < 500 && error.status !== 429) {
427
+ await say(toMarkdown(error.status === 401 || error.status === 403 ? rejectedApiKey(describeError(error)) : {
428
+ title: "Capy did not take this message",
429
+ detail: `Nothing was sent. ${describeError(error)}`,
430
+ steps: ["Fix what the error names, then send your message again."]
431
+ }));
361
432
  }
362
433
  else {
363
- await say(`capy-acp could not send this message to Capy, so nothing was sent. ${describeError(error)}`);
434
+ await say(toMarkdown(error._tag === "CapyConfigError" ? noApiKey(config.apiKeyFile) : {
435
+ title: "Send your message again",
436
+ detail: `capy-acp could not reach Capy, so nothing was sent. ${describeError(error)}`,
437
+ steps: []
438
+ }));
364
439
  }
365
440
  return ended;
366
441
  }
@@ -370,6 +445,8 @@ export const makeAgent = (config, capy = capyLayer(config)) => {
370
445
  if (session.threadId !== undefined)
371
446
  session.title ??= titleOf(text || files.map((f) => f.name).join(", "));
372
447
  await persist(params.sessionId, session);
448
+ if (session.threadId !== undefined)
449
+ await reportCredits(session, notify);
373
450
  if (session.threadId !== undefined)
374
451
  log(`session ${params.sessionId}: thread ${session.threadId} → ${result.stopReason}`);
375
452
  return { stopReason: result.stopReason };