capy-acp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yaz Caleb
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,145 @@
1
- # Temporary Holding Version
1
+ <img src="assets/icon.svg" width="64" height="64" alt="">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # capy-acp
4
+
5
+ capy-acp runs [Capy](https://capy.ai) coding-agent threads from an [Agent Client Protocol](https://agentclientprotocol.com)
6
+ (ACP) client, such as T3 Code. Each ACP session is a Capy thread on the Capy device of this machine. The agent works in the
7
+ folder that you open, with your tools. Device threads use no Capy machine time. The model runs on your connected subscription,
8
+ unless you select a model that Capy bills to credits.
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.
17
+
18
+ ## What the client shows
19
+
20
+ - The reply from Capy, streamed as Capy writes it.
21
+ - One item for each Capy tool call. The title gives the tools and the time, for example `bash, write (1.2 s)`.
22
+ - 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.
25
+ - Images, audio and other files that you attach. They go to Capy with the message, and Capy models see attached images.
26
+ - 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
+ to a Capy download URL, which expires.
28
+ - Capy subagents, as items that show their status: pending, running, completed or failed.
29
+
30
+ The adapter also does these things:
31
+
32
+ - Cancel stops the Capy thread. A follow-up message continues the same thread.
33
+ - Sessions stay available after a restart. `session/load` replays the thread transcript, and `session/resume` connects again
34
+ without a replay. `session/list` lists the saved sessions. The next prompt continues the same Capy thread.
35
+ - 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
38
+ restart.
39
+
40
+ ## Permissions
41
+
42
+ Capy runs commands and edits files without approval, as it does in the Capy app. **capy-acp never asks your ACP client for
43
+ permission.** Approval prompts and read-only modes in the client have no effect. To control Capy, write instructions in the
44
+ message or in `AGENTS.md`, or change the Capy settings. The Capy docs say that Capy opens a pull request only when you ask.
45
+
46
+ ## Requirements
47
+
48
+ - Node 22 or later.
49
+ - 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.
55
+ - 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`.
57
+
58
+ ## Setup
59
+
60
+ In **T3 Code**:
61
+
62
+ 1. Open Settings, then Providers, then Add provider.
63
+ 2. Select Show more, then **Local ACP command**.
64
+ 3. Set the command to `npx` with the arguments `-y capy-acp`. To use a checkout, set the command to `node` with the path to
65
+ `dist/bin.js`.
66
+ 4. Open a linked folder as the project.
67
+ 5. Select the Capy provider.
68
+
69
+ In **other ACP clients**, set the agent command to `npx -y capy-acp`. Set the working directory of the session to the linked
70
+ folder. The tests used only T3 Code as a client.
71
+
72
+ capy-acp announces `capy-acp --setup` as a terminal auth method. A client that supports terminal auth can run the setup for
73
+ you.
74
+
75
+ ## Settings
76
+
77
+ | Variable | Default | Effect |
78
+ | --- | --- | --- |
79
+ | `CAPY_API_KEY` | (unset) | The Capy API key. The adapter reads it for each request, so a new key needs no restart |
80
+ | `CAPY_API_KEY_FILE` | `~/.config/capy-acp/api-key` | The file with the key, if `CAPY_API_KEY` is not set |
81
+ | `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
+ | `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 |
84
+ | `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
+ | `CAPY_ACP_WAITING_LIMIT_MS` | `600000` | The time that a prompt stays open while Capy waits for a background command |
86
+ | `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
+ | `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
+ | `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` |
90
+ | `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
+ | `CAPY_ACP_ATTACHMENTS_DIR` | `~/.cache/capy-acp/attachments` | The folder for files from the *first* prompt of a thread (see below) |
92
+
93
+ ### Attachments on a new thread
94
+
95
+ The Capy call that creates a thread accepts only text. A file in a second message can arrive after a fast model already
96
+ answered. For this reason, the adapter saves the files of the first prompt on this machine, readable only by you. The message
97
+ gives their paths, and the device agent reads them on this machine. Follow-up messages attach files with the Capy upload API.
98
+
99
+ ## Limitations
100
+
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.
108
+ - **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.
116
+
117
+ ## Troubleshooting
118
+
119
+ The adapter writes its log to stderr. These are common first replies:
120
+
121
+ | Reply | Fix |
122
+ | --- | --- |
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 |
128
+ | `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
+
130
+ ## Development
131
+
132
+ ```sh
133
+ pnpm install
134
+ pnpm typecheck && pnpm test && pnpm build
135
+ node spike/acp-client.ts <folder> "<prompt>" ["<follow-up>"] [--cancel-after-ms N] [--between "<command>"] \
136
+ [--image N:<file>] [--load <sessionId> | --resume <sessionId>]
137
+ ```
138
+
139
+ 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.
142
+
143
+ ## License
144
+
145
+ [MIT](LICENSE)
package/dist/agent.js ADDED
@@ -0,0 +1,391 @@
1
+ /**
2
+ * The ACP agent: maps ACP sessions to Capy threads on this machine's Capy device.
3
+ *
4
+ * One ACP session is one Capy thread, created on the first prompt (Capy needs the first message
5
+ * to create a thread). The session → thread mapping is saved (store.ts), so `session/load` (which
6
+ * replays the transcript) and `session/resume` (which does not) continue the same thread after a
7
+ * restart. Handlers are thin: they run Effects on a ManagedRuntime that holds the Capy client, and
8
+ * every Capy failure becomes a JSON-RPC error with Capy's own message.
9
+ */
10
+ import { randomUUID } from "node:crypto";
11
+ import * as acp from "@agentclientprotocol/sdk";
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";
15
+ import { promptParts } from "./prompt.js";
16
+ import { API_KEY_AUTH, savedApiKey } from "./setup.js";
17
+ import { makeSessionStore } from "./store.js";
18
+ import { history } from "./translate.js";
19
+ import { fileLink, runTurn, titleOf } from "./turn.js";
20
+ import { AGENT_NAME, AGENT_VERSION } from "./version.js";
21
+ import { readDeviceId, readGit, readLinkedFolders, resolveWorkspace } from "./workspace.js";
22
+ /** A Capy stream event id (a ULID), the only thing a stream cursor may be. */
23
+ const EVENT_ID = /^[0-9A-HJKMNP-TV-Z]{26}$/;
24
+ 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
+ /** Capy's answer when a linked root is not (or no longer) linked to this device. */
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
+ /** The reasoning level a session really sends: its own when the model offers it, else the model's highest. */
32
+ const effectiveReasoning = (reasoning, modes) => modes.includes(reasoning) ? reasoning : modes.at(-1);
33
+ export const makeAgent = (config, capy = capyLayer(config)) => {
34
+ const runtime = ManagedRuntime.make(capy);
35
+ const sessions = new Map();
36
+ const store = makeSessionStore(config.stateDir);
37
+ let models;
38
+ /** Saves the session → thread mapping. A failed write costs only resumability, so it is logged. */
39
+ const persist = async (sessionId, session) => {
40
+ if (session.threadId === undefined)
41
+ return;
42
+ const record = {
43
+ sessionId,
44
+ cwd: session.cwd,
45
+ threadId: session.threadId,
46
+ ...(session.cursor === undefined ? {} : { cursor: session.cursor }),
47
+ model: session.model,
48
+ reasoning: session.reasoning,
49
+ ...(session.title === undefined ? {} : { title: session.title }),
50
+ updatedAt: new Date().toISOString()
51
+ };
52
+ await store.save(record).catch((error) => log(`could not save session ${sessionId}: ${String(error)}`));
53
+ };
54
+ /** Runs an Effect, converting a typed Capy failure into a JSON-RPC error the client can show. */
55
+ const run = async (effect) => {
56
+ const exit = await runtime.runPromiseExit(effect);
57
+ if (Exit.isSuccess(exit))
58
+ return exit.value;
59
+ const failure = exit.cause.reasons.find(Cause.isFailReason);
60
+ if (failure !== undefined) {
61
+ const error = failure.error;
62
+ const message = "_tag" in error ? describeError(error) : String(error);
63
+ log(message);
64
+ throw acp.RequestError.internalError(undefined, message);
65
+ }
66
+ log(Cause.pretty(exit.cause));
67
+ throw acp.RequestError.internalError(undefined, "capy-acp hit an unexpected error; see its stderr log.");
68
+ };
69
+ const withCapy = (f) => Effect.gen(function* () {
70
+ return yield* f(yield* CapyClient);
71
+ });
72
+ const loadModels = async () => {
73
+ if (models === undefined)
74
+ models = await run(withCapy((capy) => capy.listModels));
75
+ return models;
76
+ };
77
+ const configOptions = (session, available) => {
78
+ const current = available.find((m) => m.id === session.model);
79
+ const modes = current?.reasoningModes ?? [];
80
+ const options = [
81
+ {
82
+ id: "model",
83
+ name: "Model",
84
+ category: "model",
85
+ type: "select",
86
+ 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}` } : {}) }))
88
+ }
89
+ ];
90
+ if (modes.length > 0) {
91
+ options.push({
92
+ id: "reasoning",
93
+ name: "Reasoning",
94
+ category: "thought_level",
95
+ type: "select",
96
+ currentValue: effectiveReasoning(session.reasoning, modes) ?? session.reasoning,
97
+ options: modes.map((mode) => ({ value: mode, name: mode }))
98
+ });
99
+ }
100
+ return options;
101
+ };
102
+ /** Runs a Capy call for setup, turning any failure into a sentence for the user. */
103
+ const attempt = async (effect) => {
104
+ const exit = await runtime.runPromiseExit(effect);
105
+ if (Exit.isSuccess(exit))
106
+ return exit.value;
107
+ const failure = exit.cause.reasons.find(Cause.isFailReason);
108
+ throw new Error(failure === undefined ? Cause.pretty(exit.cause) : describeError(failure.error));
109
+ };
110
+ /** 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([
113
+ attempt(withCapy((capy) => capy.listProjects)),
114
+ readDeviceId(config),
115
+ readLinkedFolders(config),
116
+ readGit(cwd)
117
+ ]);
118
+ // Reported in this order: the API key first, then the paired device, since nothing else can be
119
+ // 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 };
123
+ }
124
+ const resolution = resolveWorkspace({
125
+ cwd,
126
+ ...git.value,
127
+ linked: linked.value,
128
+ projects: projects.value,
129
+ mode: config.workspaceMode,
130
+ allowWorktreeFallback: config.allowWorktreeFallback
131
+ });
132
+ if (resolution._tag === "Unresolved")
133
+ return { deviceId: deviceId.value, resolved: undefined, problem: resolution.message, changes: undefined };
134
+ 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 };
137
+ };
138
+ /** A saved session to continue. A session that never sent a prompt has no record, and opens empty. */
139
+ const restorable = async (sessionId) => {
140
+ const busy = sessions.get(sessionId)?.busy === true;
141
+ if (busy)
142
+ throw acp.RequestError.invalidRequest(undefined, "This session is running a prompt.");
143
+ return store.get(sessionId);
144
+ };
145
+ /** Builds a session's state, from its record when it continues a thread, and returns its options. */
146
+ const openSession = async (sessionId, cwd, record) => {
147
+ // A thread works in the folder it was created for, so a saved session keeps its own folder.
148
+ const folder = record?.cwd ?? cwd;
149
+ if (record !== undefined && record.cwd !== cwd)
150
+ log(`session ${sessionId}: client opened ${cwd}; the thread works in ${record.cwd}`);
151
+ const setup = await setUp(folder);
152
+ const available = await loadModels().catch(() => []);
153
+ const session = {
154
+ ...setup,
155
+ cwd: folder,
156
+ threadId: record?.threadId,
157
+ cursor: record?.cursor,
158
+ model: record?.model ?? config.defaultModel,
159
+ reasoning: record?.reasoning ?? config.defaultReasoning,
160
+ title: record?.title,
161
+ noteShown: record !== undefined,
162
+ busy: false,
163
+ closed: false,
164
+ cancel: undefined
165
+ };
166
+ sessions.set(sessionId, session);
167
+ log(setup.resolved === undefined
168
+ ? `session ${sessionId}: cannot run in ${folder}: ${setup.problem}`
169
+ : `session ${sessionId}: ${setup.resolved.repo} in project ${setup.resolved.projectName} (${setup.resolved.workspace.kind})`);
170
+ return configOptions(session, available);
171
+ };
172
+ const app = acp
173
+ .agent({ name: AGENT_NAME })
174
+ .onRequest(acp.methods.agent.initialize, () => ({
175
+ protocolVersion: acp.PROTOCOL_VERSION,
176
+ agentCapabilities: {
177
+ loadSession: true,
178
+ // Media is attached to the Capy message as files (prompt.ts).
179
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
180
+ sessionCapabilities: { list: {}, resume: {}, close: {} }
181
+ },
182
+ 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.
184
+ authMethods: [API_KEY_AUTH]
185
+ }))
186
+ .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
+ }
190
+ return {};
191
+ })
192
+ .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
194
+ // shows only "Provider session failed to open" and drops the error's message, which here
195
+ // always names the fix. Each prompt re-checks, so linking the folder needs no new session.
196
+ const sessionId = randomUUID();
197
+ return { sessionId, configOptions: await openSession(sessionId, params.cwd, undefined) };
198
+ })
199
+ .onRequest(acp.methods.agent.session.load, async ({ params, client }) => {
200
+ const record = await restorable(params.sessionId);
201
+ const configOptions = await openSession(params.sessionId, params.cwd, record);
202
+ if (record !== undefined) {
203
+ // Replay the committed transcript as history before answering, as `session/load` requires.
204
+ const threadId = record.threadId;
205
+ const notify = (update) => client.notify(acp.methods.client.session.update, { sessionId: params.sessionId, update }).catch(() => undefined);
206
+ const messages = await run(withCapy((capy) => capy.listMessages(threadId)));
207
+ for (const entry of history(messages)) {
208
+ await notify(entry.update);
209
+ for (const file of entry.files ?? []) {
210
+ const content = await runtime.runPromise(withCapy((capy) => fileLink(capy, threadId, file)));
211
+ await notify(entry.source === "user" ? { sessionUpdate: "user_message_chunk", content } : { sessionUpdate: "agent_message_chunk", content });
212
+ }
213
+ }
214
+ // The client now has everything, so the next turn streams from the newest entry. User and
215
+ // assistant entries carry their stream event id as their id (tool entries do not), and event
216
+ // ids sort by time, so this only ever moves the saved cursor forward.
217
+ const newest = messages.findLast((m) => m.source !== "tool" && EVENT_ID.test(m.id))?.id;
218
+ const session = sessions.get(params.sessionId);
219
+ if (session !== undefined && newest !== undefined && (session.cursor === undefined || newest > session.cursor)) {
220
+ session.cursor = newest;
221
+ await persist(params.sessionId, session);
222
+ }
223
+ log(`session ${params.sessionId}: loaded thread ${threadId} (${messages.length} entries)`);
224
+ }
225
+ return { configOptions };
226
+ })
227
+ .onRequest(acp.methods.agent.session.resume, async ({ params }) => {
228
+ const record = await restorable(params.sessionId);
229
+ const configOptions = await openSession(params.sessionId, params.cwd, record);
230
+ if (record !== undefined)
231
+ log(`session ${params.sessionId}: resumed thread ${record.threadId}`);
232
+ return { configOptions };
233
+ })
234
+ .onRequest(acp.methods.agent.session.list, async ({ params }) => {
235
+ const records = await store.list();
236
+ return {
237
+ sessions: records
238
+ .filter((record) => params.cwd == null || record.cwd === params.cwd)
239
+ .map((record) => ({ sessionId: record.sessionId, cwd: record.cwd, title: record.title ?? null, updatedAt: record.updatedAt }))
240
+ };
241
+ })
242
+ .onRequest(acp.methods.agent.session.close, async ({ params }) => {
243
+ const session = sessions.get(params.sessionId);
244
+ if (session === undefined)
245
+ return {};
246
+ if (session.busy) {
247
+ // Keep the entry until the cancelled prompt settles, so a load of this id can't start a
248
+ // second turn on the same thread meanwhile. The prompt removes it on the way out.
249
+ session.closed = true;
250
+ if (session.cancel !== undefined)
251
+ Deferred.doneUnsafe(session.cancel, Exit.void);
252
+ }
253
+ else {
254
+ sessions.delete(params.sessionId);
255
+ }
256
+ return {};
257
+ })
258
+ .onRequest(acp.methods.agent.session.setConfigOption, async ({ params }) => {
259
+ const session = sessions.get(params.sessionId);
260
+ if (session === undefined || session.closed)
261
+ throw acp.RequestError.sessionNotFound(params.sessionId);
262
+ const available = await loadModels();
263
+ if (!("value" in params) || typeof params.value !== "string") {
264
+ throw acp.RequestError.invalidParams(undefined, `Unsupported value for ${params.configId}`);
265
+ }
266
+ if (params.configId === "model") {
267
+ if (!available.some((m) => m.id === params.value)) {
268
+ throw acp.RequestError.invalidParams(undefined, `Capy does not offer the model ${params.value}`);
269
+ }
270
+ session.model = params.value;
271
+ }
272
+ else if (params.configId === "reasoning") {
273
+ const modes = available.find((m) => m.id === session.model)?.reasoningModes ?? [];
274
+ if (!modes.includes(params.value)) {
275
+ throw acp.RequestError.invalidParams(undefined, `${session.model} does not offer the reasoning level ${params.value}`);
276
+ }
277
+ session.reasoning = params.value;
278
+ }
279
+ else {
280
+ throw acp.RequestError.invalidParams(undefined, `Unknown option ${params.configId}`);
281
+ }
282
+ await persist(params.sessionId, session);
283
+ return { configOptions: configOptions(session, available) };
284
+ })
285
+ .onRequest(acp.methods.agent.session.prompt, async ({ params, client }) => {
286
+ const session = sessions.get(params.sessionId);
287
+ if (session === undefined || session.closed)
288
+ throw acp.RequestError.sessionNotFound(params.sessionId);
289
+ if (session.busy)
290
+ throw acp.RequestError.invalidRequest(undefined, "A prompt is already running in this session.");
291
+ const { text, files } = promptParts(params.prompt, { forwardHostInstructions: config.forwardHostInstructions });
292
+ if (text === "" && files.length === 0)
293
+ throw acp.RequestError.invalidParams(undefined, "The prompt is empty.");
294
+ // Busy from here on, before any await: a second prompt must not slip in while setup runs.
295
+ const cancel = Deferred.makeUnsafe();
296
+ session.busy = true;
297
+ session.cancel = cancel;
298
+ const notify = (update) => client.notify(acp.methods.client.session.update, { sessionId: params.sessionId, update }).catch(() => undefined);
299
+ // A client that stops listening must not fail the turn: Capy keeps working either way.
300
+ const emit = (update) => Effect.promise(() => notify(update));
301
+ const say = (text) => notify({ sessionUpdate: "agent_message_chunk", content: { type: "text", text } });
302
+ const ended = { stopReason: "end_turn" };
303
+ try {
304
+ if (session.resolved === undefined) {
305
+ // 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));
307
+ if (session.resolved !== undefined)
308
+ log(`session ${params.sessionId}: setup resolved on retry`);
309
+ }
310
+ if (Deferred.isDoneUnsafe(cancel))
311
+ return { stopReason: "cancelled" };
312
+ const resolved = session.resolved;
313
+ if (resolved === undefined) {
314
+ await say(`capy-acp can't run here. ${session.problem ?? ""}`);
315
+ return ended;
316
+ }
317
+ if (!session.noteShown && resolved.note !== undefined) {
318
+ session.noteShown = true;
319
+ await say(`_${resolved.note}_\n\n`);
320
+ }
321
+ const reasoningModes = (await loadModels().catch(() => [])).find((m) => m.id === session.model)?.reasoningModes ?? [];
322
+ const reasoningMode = effectiveReasoning(session.reasoning, reasoningModes);
323
+ const exit = await runtime.runPromiseExit(runTurn({
324
+ changes: session.changes,
325
+ threadId: session.threadId,
326
+ cursor: session.cursor,
327
+ text,
328
+ files,
329
+ attachmentsDir: config.attachmentsDir,
330
+ onCursor: (threadId, cursor) => Effect.promise(() => {
331
+ session.threadId = threadId;
332
+ session.cursor = cursor;
333
+ session.title ??= titleOf(text || files.map((f) => f.name).join(", "));
334
+ return persist(params.sessionId, session);
335
+ }),
336
+ model: { modelId: session.model, ...(reasoningMode === undefined ? {} : { reasoningMode }) },
337
+ target: { projectId: resolved.projectId, deviceId: session.deviceId, workspace: resolved.workspace },
338
+ waitingLimitMs: config.waitingLimitMs,
339
+ cancelled: Deferred.await(cancel),
340
+ emit
341
+ }));
342
+ if (Exit.isFailure(exit)) {
343
+ // runTurn fails only before Capy accepted the message (afterwards it reports problems in
344
+ // the reply), so saying that nothing was sent is accurate, and a resend is safe.
345
+ const failure = exit.cause.reasons.find(Cause.isFailReason);
346
+ if (failure === undefined) {
347
+ log(Cause.pretty(exit.cause));
348
+ throw acp.RequestError.internalError(undefined, "capy-acp hit an unexpected error; see its stderr log.");
349
+ }
350
+ const error = failure.error;
351
+ log(`session ${params.sessionId}: ${describeError(error)}`);
352
+ if (resolved.workspace.kind === "linked" && session.threadId === undefined && isNotLinked(error)) {
353
+ // 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}`);
361
+ }
362
+ else {
363
+ await say(`capy-acp could not send this message to Capy, so nothing was sent. ${describeError(error)}`);
364
+ }
365
+ return ended;
366
+ }
367
+ const result = exit.value;
368
+ session.threadId = result.threadId;
369
+ session.cursor = result.cursor;
370
+ if (session.threadId !== undefined)
371
+ session.title ??= titleOf(text || files.map((f) => f.name).join(", "));
372
+ await persist(params.sessionId, session);
373
+ if (session.threadId !== undefined)
374
+ log(`session ${params.sessionId}: thread ${session.threadId} → ${result.stopReason}`);
375
+ return { stopReason: result.stopReason };
376
+ }
377
+ finally {
378
+ session.busy = false;
379
+ session.cancel = undefined;
380
+ if (session.closed)
381
+ sessions.delete(params.sessionId);
382
+ }
383
+ })
384
+ .onNotification(acp.methods.agent.session.cancel, ({ params }) => {
385
+ const cancel = sessions.get(params.sessionId)?.cancel;
386
+ if (cancel !== undefined)
387
+ Deferred.doneUnsafe(cancel, Exit.void);
388
+ });
389
+ return { app, dispose: () => runtime.dispose() };
390
+ };
391
+ //# sourceMappingURL=agent.js.map