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 +83 -43
- package/dist/agent.js +118 -41
- package/dist/agent.js.map +1 -1
- package/dist/bin.js +54 -3
- package/dist/bin.js.map +1 -1
- package/dist/capy/client.js +9 -1
- package/dist/capy/client.js.map +1 -1
- package/dist/changes.js +64 -44
- package/dist/changes.js.map +1 -1
- package/dist/config.js +4 -2
- package/dist/config.js.map +1 -1
- package/dist/doctor.js +102 -0
- package/dist/doctor.js.map +1 -0
- package/dist/pricing.js +60 -0
- package/dist/pricing.js.map +1 -0
- package/dist/problems.js +108 -0
- package/dist/problems.js.map +1 -0
- package/dist/setup.js +2 -2
- package/dist/setup.js.map +1 -1
- package/dist/translate.js +35 -18
- package/dist/translate.js.map +1 -1
- package/dist/turn.js +32 -34
- package/dist/turn.js.map +1 -1
- package/dist/workspace.js +77 -42
- package/dist/workspace.js.map +1 -1
- package/package.json +4 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"problems.js","sourceRoot":"","sources":["../src/problems.ts"],"names":[],"mappings":"AAaA,kEAAkE;AAClE,MAAM,OAAO,YAAa,SAAQ,KAAK;IAChB,OAAO;IAA5B,YAAqB,OAAgB;QACnC,KAAK,CAAC,GAAG,OAAO,CAAC,KAAK,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAAA;uBADzB,OAAO;IAE5B,CAAC;CACF;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,KAAc,EAAuB,EAAE,CAAC,CAAC,KAAK,YAAY,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAA;AAE7H,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,OAAgB,EAAU,EAAE,CACrD,CAAC,KAAK,OAAO,CAAC,KAAK,IAAI,EAAE,OAAO,CAAC,MAAM,EAAE,OAAO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S;QAAE,OAAO,CAAC,OAAO,CAAC,CAAA;IAChD,IAAI,KAAK,CAAC,MAAM,KAAK,MAAM;QAAE,OAAO,IAAI,CAAA;IACxC,OAAO,CAAC,yBAAyB,OAAO,EAAE,EAAE,uBAAuB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;AACtF,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,KAQzB,EAAW,EAAE,CACZ,KAAK,CAAC,YAAY,KAAK,SAAS;IAC9B,CAAC,CAAC;QACE,KAAK,EAAE,0BAA0B;QACjC,MAAM,EAAE,2EAA2E,KAAK,CAAC,IAAI,iBAAiB;QAC9G,KAAK,EAAE,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,EAAE,KAAK,CAAC;KACpC;IACH,CAAC,CAAC;QACE,KAAK,EAAE,sCAAsC,KAAK,CAAC,IAAI,EAAE;QACzD,MAAM,EAAE,gCAAgC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,YAAY,YAAY,KAAK,CAAC,IAAI,GAAG;QACpG,KAAK,EAAE;YACL,QAAQ,KAAK,CAAC,YAAY,8CAA8C;YACxE,WAAW,KAAK,CAAC,IAAI,aAAa,SAAS,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,gCAAgC;YAC5F,kHAAkH,KAAK,CAAC,YAAY,oCAAoC,KAAK,CAAC,IAAI,GAAG;SACtL;KACF,CAAA","sourcesContent":["/**\n * Setup problems that the user must fix, with the steps to fix them. The first reply of a session\n * shows them as Markdown; `--doctor` prints them as plain text. Each problem says what to do, not\n * only what went wrong.\n */\nexport interface Problem {\n /** What to do, as a short imperative: \"Add your Capy API key\". */\n readonly title: string\n /** Why, in one or two sentences. */\n readonly detail: string\n readonly steps: ReadonlyArray<string>\n}\n\n/** An Error that carries a Problem, for code paths that throw. */\nexport class ProblemError extends Error {\n constructor(readonly problem: Problem) {\n super(`${problem.title}. ${problem.detail}`)\n }\n}\n\nexport const problemOf = (error: unknown): Problem | undefined => (error instanceof ProblemError ? error.problem : undefined)\n\nexport const toMarkdown = (problem: Problem): string =>\n [`**${problem.title}**`, problem.detail, problem.steps.map((step, i) => `${i + 1}. ${step}`).join(\"\\n\")]\n .filter((part) => part !== \"\")\n .join(\"\\n\\n\")\n\nexport const toText = (problem: Problem, indent = \"\"): string =>\n [`${problem.title}. ${problem.detail}`, ...problem.steps.map((step, i) => `${indent}${i + 1}. ${step}`)].join(\"\\n\")\n\nconst RETRY = \"Send your message again.\"\nconst NEW_SESSION = \"Start a new chat in that folder. A session keeps the folder that it opened with.\"\n\nexport const noApiKey = (keyFile: string): Problem => ({\n title: \"Add your Capy API key\",\n detail: \"capy-acp needs a Capy API key to start Capy threads.\",\n steps: [\n \"Create a key in the Capy app under Settings, then API.\",\n `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.`,\n RETRY\n ]\n})\n\nexport const rejectedApiKey = (detail: string): Problem => ({\n title: \"Replace your Capy API key\",\n detail: `Capy did not accept the API key (${detail}).`,\n steps: [\"Create a new key in the Capy app under Settings, then API.\", \"Run `npx -y capy-acp --setup` and paste it.\", RETRY]\n})\n\nexport const unreachable = (apiUrl: string, detail: string): Problem => ({\n title: \"Capy could not be reached\",\n detail: `${detail}.`,\n steps: [`Check the network connection to ${apiUrl}.`, RETRY]\n})\n\n/** A file that can name this computer's Capy device, and what capy-acp found in it. */\nexport interface DeviceFile {\n readonly path: string\n readonly found: \"missing\" | \"no device\"\n}\n\nexport const noDevice = (files: ReadonlyArray<DeviceFile>): Problem => ({\n title: \"Start Capy on this computer\",\n detail: \"Capy threads run on this computer, and capy-acp found no Capy device here.\",\n steps: [\n \"Open the Capy desktop app and sign in, or run `capy dock` on a computer without a screen.\",\n RETRY,\n `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.`\n ]\n})\n\nexport const unreadableDeviceFile = (file: string, detail: string): Problem => ({\n title: \"Check the Capy desktop app\",\n detail: `capy-acp could not read the device file ${file} (${detail}).`,\n steps: [\"Restart the Capy desktop app, or set `CAPY_DEVICE_ID` to the id of this computer's Capy device.\", RETRY]\n})\n\nexport const manyOrganizations = (count: number): Problem => ({\n title: \"Choose a Capy organization\",\n detail: `This computer is paired with ${count} Capy organizations, so capy-acp cannot tell which device to use.`,\n steps: [\"Set `CAPY_DEVICE_ID` in the agent's environment to the device id of the organization that you want.\", RETRY]\n})\n\nconst isT3Scratch = (folder: string) => {\n const parts = folder.split(/[\\\\/]+/)\n return parts.some((part, i) => part === \".t3\" && parts[i + 1] === \"scratch\")\n}\n\nexport const notGit = (folder: string): Problem =>\n isT3Scratch(folder)\n ? {\n title: \"Open a project to use Capy\",\n detail: \"T3 Code started this chat without a project. Capy threads run on a GitHub repository from one of your Capy projects.\",\n steps: [\"In T3 Code, add a project for a clone of that repository.\", \"Start a new chat in that project.\"]\n }\n : {\n title: \"Open a repository to use Capy\",\n detail: `${folder} is not in a git repository. Capy threads run on a GitHub repository from one of your Capy projects.`,\n steps: [\"Open a clone of that repository in your editor.\", NEW_SESSION]\n }\n\nexport const noGitHubRemote = (gitRoot: string): Problem => ({\n title: \"Add the GitHub remote\",\n detail: `${gitRoot} has no git remote that names a GitHub repository, so capy-acp cannot find its Capy project.`,\n steps: [\"Add the remote, for example `git remote add origin git@github.com:owner/repo.git`.\", RETRY]\n})\n\nexport const notInProject = (repos: ReadonlyArray<string>): Problem => ({\n title: `Add ${repos[0]} to a Capy project`,\n detail: `No Capy project includes ${repos.join(\" or \")}.`,\n steps: [\"Open https://capy.ai/settings/projects and add the repository to a project.\", RETRY]\n})\n\n/** How this computer is paired with Capy, which decides how a folder gets linked. */\nexport type DeviceKind = \"desktop\" | \"dock\"\n\nconst linkSteps = (input: { readonly root: string; readonly projectId: string; readonly projectName: string; readonly device: DeviceKind | undefined }) => {\n // Only the device itself can link a local folder: the desktop app, or `capy dock dirs add`. The\n // web app cannot. `capy://app/<path>` opens that page of the desktop app (checked in 0.10.0).\n 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}.`\n const dock = [\n \"Stop `capy dock`. Caution: this also stops the Capy threads that run on this computer.\",\n `Run \\`capy dock dirs add ${input.root}\\`, then start \\`capy dock\\` again.`\n ]\n if (input.device === \"desktop\") return [desktop]\n if (input.device === \"dock\") return dock\n return [`With the desktop app: ${desktop}`, `With \\`capy dock\\`: ${dock.join(\" \")}`]\n}\n\nexport const notLinked = (input: {\n readonly root: string\n readonly repo: string\n readonly projectId: string\n readonly projectName: string\n readonly device: DeviceKind | undefined\n /** Another folder on this computer that Capy links for the same repository. */\n readonly sameRepoRoot?: string | undefined\n}): Problem =>\n input.sameRepoRoot === undefined\n ? {\n title: \"Link this folder to Capy\",\n detail: `Capy runs threads only in folders that are linked to this computer, and ${input.root} is not linked.`,\n steps: [...linkSteps(input), RETRY]\n }\n : {\n title: `Use the folder that Capy links for ${input.repo}`,\n detail: `On this computer, Capy links ${input.repo} at ${input.sameRepoRoot}, not at ${input.root}.`,\n steps: [\n `Open ${input.sameRepoRoot} in your editor, and start a new chat there.`,\n `Or link ${input.root} instead. ${linkSteps(input).join(\" \")} Then send your message again.`,\n `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}.`\n ]\n }\n"]}
|
package/dist/setup.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
7
7
|
import { dirname } from "node:path";
|
|
8
|
-
import {
|
|
8
|
+
import { readDevice } from "./workspace.js";
|
|
9
9
|
/** The terminal auth method that `initialize` announces. */
|
|
10
10
|
export const API_KEY_AUTH = {
|
|
11
11
|
type: "terminal",
|
|
@@ -44,7 +44,7 @@ export const runSetup = async (config, io) => {
|
|
|
44
44
|
io.write(typeof check === "number" && check >= 200 && check < 300
|
|
45
45
|
? "Capy accepted the key. Saved.\n"
|
|
46
46
|
: `Saved, but capy-acp could not check the key with Capy (${check}).\n`);
|
|
47
|
-
await
|
|
47
|
+
await readDevice(config).then((device) => io.write(`Capy device on this machine: ${device.id}.\n`), (error) => io.write(`${error instanceof Error ? error.message : String(error)}\n`));
|
|
48
48
|
return 0;
|
|
49
49
|
};
|
|
50
50
|
/** Reads a line from the terminal with echo off, or the first line of piped input. */
|
package/dist/setup.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setup.js","sourceRoot":"","sources":["../src/setup.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AACpE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAEnC,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"setup.js","sourceRoot":"","sources":["../src/setup.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AACpE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAEnC,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAE3C,4DAA4D;AAC5D,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,IAAI,EAAE,UAAU;IAChB,EAAE,EAAE,cAAc;IAClB,IAAI,EAAE,cAAc;IACpB,WAAW,EAAE,6FAA6F;IAC1G,IAAI,EAAE,CAAC,SAAS,CAAC;CACT,C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CAAC,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC,CAAA;gBAC7D,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI;oBAAE,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;;oBAC7D,KAAK,IAAI,IAAI,CAAA;YACpB,CAAC;QACH,CAAC,CAAA;QACD,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAA;QACzB,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;QACtB,KAAK,CAAC,MAAM,EAAE,CAAA;QACd,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC1B,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA","sourcesContent":["/**\n * `capy-acp --setup`: saves a Capy API key on this machine. ACP clients run it as the agent's\n * terminal auth method; people can run it directly too. The key is checked against Capy before it\n * is saved, and is never printed.\n */\nimport { chmod, mkdir, readFile, writeFile } from \"node:fs/promises\"\nimport { dirname } from \"node:path\"\nimport type { AdapterConfig } from \"./config.js\"\nimport { readDevice } from \"./workspace.js\"\n\n/** The terminal auth method that `initialize` announces. */\nexport const API_KEY_AUTH = {\n type: \"terminal\",\n id: \"capy-api-key\",\n name: \"Capy API key\",\n description: \"Save a Capy API key on this machine. Create a key in the Capy app under Settings, then API.\",\n args: [\"--setup\"]\n} as const\n\nexport interface SetupIo {\n /** Reads one line without echoing it. */\n readonly readSecret: (prompt: string) => Promise<string>\n readonly write: (text: string) => void\n readonly fetch: typeof fetch\n}\n\n/** The key from `CAPY_API_KEY` or the key file, or undefined when neither has one. */\nexport const savedApiKey = async (config: AdapterConfig): Promise<string | undefined> => {\n const fromEnv = process.env.CAPY_API_KEY?.trim()\n if (fromEnv) return fromEnv\n const fromFile = await readFile(config.apiKeyFile, \"utf8\").then((text) => text.trim(), () => \"\")\n return fromFile || undefined\n}\n\n/** Returns the exit code: 0 when a key is saved and accepted. */\nexport const runSetup = async (config: AdapterConfig, io: SetupIo): Promise<number> => {\n io.write(`capy-acp setup. The key goes to ${config.apiKeyFile} (readable only by you).\\n`)\n const key = (await io.readSecret(\"Capy API key: \")).trim()\n if (key === \"\") {\n io.write(\"No key entered. Nothing was saved.\\n\")\n return 1\n }\n const check = await io\n .fetch(`${config.apiUrl}/projects`, { headers: { authorization: `Bearer ${key}`, accept: \"application/json\" } })\n .then((response) => response.status, (error: unknown) => (error instanceof Error ? error.message : String(error)))\n if (check === 401 || check === 403) {\n io.write(\"Capy rejected this key. Nothing was saved.\\n\")\n return 1\n }\n await mkdir(dirname(config.apiKeyFile), { recursive: true, mode: 0o700 })\n await writeFile(config.apiKeyFile, `${key}\\n`, { mode: 0o600 })\n // writeFile keeps the mode of a file that already exists.\n await chmod(config.apiKeyFile, 0o600)\n io.write(\n typeof check === \"number\" && check >= 200 && check < 300\n ? \"Capy accepted the key. Saved.\\n\"\n : `Saved, but capy-acp could not check the key with Capy (${check}).\\n`\n )\n await readDevice(config).then(\n (device) => io.write(`Capy device on this machine: ${device.id}.\\n`),\n (error: unknown) => io.write(`${error instanceof Error ? error.message : String(error)}\\n`)\n )\n return 0\n}\n\n/** Reads a line from the terminal with echo off, or the first line of piped input. */\nexport const readSecretFromTerminal = (prompt: string): Promise<string> => {\n const input = process.stdin\n if (!input.isTTY) {\n return new Promise((resolve) => {\n let data = \"\"\n input.setEncoding(\"utf8\")\n input.on(\"data\", (chunk: string) => (data += chunk))\n input.on(\"end\", () => resolve(data.split(/\\r?\\n/)[0] ?? \"\"))\n })\n }\n process.stdout.write(prompt)\n return new Promise((resolve, reject) => {\n let value = \"\"\n const finish = (error?: Error) => {\n input.off(\"data\", onData)\n input.setRawMode(false)\n input.pause()\n process.stdout.write(\"\\n\")\n if (error) reject(error)\n else resolve(value)\n }\n const onData = (chunk: string) => {\n for (const char of chunk) {\n if (char === \"\\r\" || char === \"\\n\") return finish()\n if (char === \"\\u0003\") return finish(new Error(\"Cancelled.\"))\n if (char === \"\\u007f\" || char === \"\\b\") value = value.slice(0, -1)\n else value += char\n }\n }\n input.setEncoding(\"utf8\")\n input.setRawMode(true)\n input.resume()\n input.on(\"data\", onData)\n })\n}\n"]}
|
package/dist/translate.js
CHANGED
|
@@ -7,7 +7,8 @@ export const initialTurn = (cursor) => ({
|
|
|
7
7
|
settled: new Set(),
|
|
8
8
|
endPending: false,
|
|
9
9
|
lastAssistantCallId: undefined,
|
|
10
|
-
tools: new Map()
|
|
10
|
+
tools: new Map(),
|
|
11
|
+
cancelled: false
|
|
11
12
|
});
|
|
12
13
|
const READ_TOOLS = new Set(["read", "view", "cat", "open"]);
|
|
13
14
|
const SEARCH_TOOLS = new Set(["grep", "glob", "search", "find", "ls", "list"]);
|
|
@@ -28,6 +29,19 @@ export const toolKind = (names) => {
|
|
|
28
29
|
return "think";
|
|
29
30
|
return "other";
|
|
30
31
|
};
|
|
32
|
+
/**
|
|
33
|
+
* How a committed tool entry ended. Each `execute` call that ran to its end lists its inner tools with
|
|
34
|
+
* their durations, and Capy commits a call that an interrupt stopped with no `calls` list at all (seen
|
|
35
|
+
* in every cancelled test turn). An entry that names its tool directly (Haiku's `bash`) never lists
|
|
36
|
+
* inner tools, so after a cancel its outcome is unknown, and it shows as failed rather than finished.
|
|
37
|
+
*/
|
|
38
|
+
export const toolStatus = (message, cancelled) => {
|
|
39
|
+
if ((message.calls?.length ?? 0) > 0)
|
|
40
|
+
return "completed";
|
|
41
|
+
if (message.tool === "execute")
|
|
42
|
+
return "failed";
|
|
43
|
+
return cancelled ? "failed" : "completed";
|
|
44
|
+
};
|
|
31
45
|
const formatSeconds = (ms) => (ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`);
|
|
32
46
|
/** Title for a committed tool entry: its summary when it has one, else the inner tools it ran. */
|
|
33
47
|
export const toolTitle = (message) => {
|
|
@@ -36,7 +50,7 @@ export const toolTitle = (message) => {
|
|
|
36
50
|
return summary;
|
|
37
51
|
const calls = message.calls ?? [];
|
|
38
52
|
if (calls.length === 0)
|
|
39
|
-
return message.tool ?? "Tool call";
|
|
53
|
+
return message.tool === "execute" ? "Stopped tool call" : (message.tool ?? "Tool call");
|
|
40
54
|
const names = [...new Set(calls.map((call) => call.tool))].join(", ");
|
|
41
55
|
const total = calls.reduce((sum, call) => sum + (call.durationMs ?? 0), 0);
|
|
42
56
|
return total > 0 ? `${names} (${formatSeconds(total)})` : names;
|
|
@@ -101,17 +115,13 @@ const onTranscript = (state, cursor, message) => {
|
|
|
101
115
|
const names = message.calls?.map((call) => call.tool) ?? (message.tool === undefined ? [] : [message.tool]);
|
|
102
116
|
const title = toolTitle(message);
|
|
103
117
|
const kind = toolKind(names.length > 0 ? names : [message.tool ?? ""]);
|
|
118
|
+
const status = toolStatus(message, base.cancelled);
|
|
104
119
|
const tools = new Map(base.tools).set(message.id, { title, kind, done: true });
|
|
105
120
|
const next = { ...base, active: true, tools };
|
|
106
|
-
|
|
107
|
-
return {
|
|
108
|
-
state: next,
|
|
109
|
-
updates: [{ sessionUpdate: "tool_call", toolCallId: message.id, title, kind, status: "completed" }]
|
|
110
|
-
};
|
|
111
|
-
}
|
|
121
|
+
const fields = { toolCallId: message.id, title, kind, status };
|
|
112
122
|
return {
|
|
113
123
|
state: next,
|
|
114
|
-
updates: [{ sessionUpdate: "
|
|
124
|
+
updates: [known === undefined ? { sessionUpdate: "tool_call", ...fields } : { sessionUpdate: "tool_call_update", ...fields }]
|
|
115
125
|
};
|
|
116
126
|
}
|
|
117
127
|
}
|
|
@@ -206,9 +216,11 @@ export const changeTitle = (changes) => {
|
|
|
206
216
|
return `${verb} ${names.slice(0, MAX_TITLE_FILES - 1).join(", ")} and ${rest} more files`;
|
|
207
217
|
};
|
|
208
218
|
/**
|
|
209
|
-
* The ACP update that shows a tool call's file changes as diffs.
|
|
210
|
-
*
|
|
211
|
-
*
|
|
219
|
+
* The ACP update that shows a tool call's file changes as diffs. `status` keeps a call that was closed
|
|
220
|
+
* as failed (cancelled, failed run) from reading as completed. With `outside`, it opens an item of its
|
|
221
|
+
* own for changes that no Capy tool call made: they happened while no call that can write ran, so
|
|
222
|
+
* they are the user's, or a background command's. Its kind is `other`, so that clients show the title,
|
|
223
|
+
* which says so, and not a plain "changed files".
|
|
212
224
|
*/
|
|
213
225
|
export const fileChangeUpdate = (toolCallId, changes, options = {}) => {
|
|
214
226
|
const content = changes.flatMap((change) => change.previewable
|
|
@@ -219,19 +231,24 @@ export const fileChangeUpdate = (toolCallId, changes, options = {}) => {
|
|
|
219
231
|
newText: change.newText ?? ""
|
|
220
232
|
}]
|
|
221
233
|
: []);
|
|
222
|
-
const
|
|
234
|
+
const locations = changes.map((change) => ({ path: change.path }));
|
|
235
|
+
if (options.outside === true) {
|
|
236
|
+
const title = `${changeTitle(changes)} outside a Capy tool call`;
|
|
237
|
+
return { sessionUpdate: "tool_call", toolCallId, title, kind: "other", status: "completed", content, locations };
|
|
238
|
+
}
|
|
239
|
+
return {
|
|
240
|
+
sessionUpdate: "tool_call_update",
|
|
223
241
|
toolCallId,
|
|
224
242
|
title: changeTitle(changes),
|
|
225
243
|
kind: changes.every((c) => c.operation === "delete") ? "delete" : "edit",
|
|
226
244
|
status: options.status ?? "completed",
|
|
227
245
|
content,
|
|
228
|
-
locations
|
|
246
|
+
locations
|
|
229
247
|
};
|
|
230
|
-
return options.create === true ? { sessionUpdate: "tool_call", ...fields } : { sessionUpdate: "tool_call_update", ...fields };
|
|
231
248
|
};
|
|
232
|
-
/**
|
|
249
|
+
/** The tool calls an update set closes, in order. */
|
|
233
250
|
export const closedTools = (updates) => updates.flatMap((u) => (u.sessionUpdate === "tool_call" || u.sessionUpdate === "tool_call_update") && (u.status === "completed" || u.status === "failed")
|
|
234
|
-
? [u.toolCallId]
|
|
251
|
+
? [{ toolCallId: u.toolCallId, status: u.status, kind: u.kind ?? undefined }]
|
|
235
252
|
: []);
|
|
236
253
|
/** Closes tool calls still in progress when the turn ends: completed on success, failed otherwise. */
|
|
237
254
|
export const finishTools = (state, outcome) => {
|
|
@@ -260,7 +277,7 @@ export const history = (messages) => {
|
|
|
260
277
|
const names = message.calls?.map((call) => call.tool) ?? (message.tool === undefined ? [] : [message.tool]);
|
|
261
278
|
out.push({
|
|
262
279
|
source: "assistant",
|
|
263
|
-
update: { sessionUpdate: "tool_call", toolCallId: message.id, title: toolTitle(message), kind: toolKind(names), status:
|
|
280
|
+
update: { sessionUpdate: "tool_call", toolCallId: message.id, title: toolTitle(message), kind: toolKind(names), status: toolStatus(message, false) }
|
|
264
281
|
});
|
|
265
282
|
}
|
|
266
283
|
else if (message.source === "user") {
|
package/dist/translate.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translate.js","sourceRoot":"","sources":["../src/translate.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAwD,YAAY,EAAqB,MAAM,kBAAkB,CAAA;AA2CxH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,MAA0B,EAAa,EAAE,CAAC,CAAC;IACrE,MAAM;IACN,MAAM,EAAE,SAAS;IACjB,MAAM,EAAE,KAAK;IACb,SAAS,EAAE,IAAI,GAAG,EAAE;IACpB,OAAO,EAAE,IAAI,GAAG,EAAE;IAClB,UAAU,EAAE,KAAK;IACjB,mBAAmB,EAAE,SAAS;IAC9B,KAAK,EAAE,IAAI,GAAG,EAAE;CACjB,CAAC,CAAA;AAEF,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAA;AAC3D,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAA;AAC9E,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAA;AAE3E;;;GAGG;AACH,MAAM,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,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;IAC9D,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,CAAA;AACpC,CAAC,CAAA","sourcesContent":["/**\n * Translates one prompt turn's Capy stream events into ACP `session/update` payloads.\n *\n * Pure and synchronous so recorded streams replay deterministically in tests. Rules come from\n * the spike recordings (see docs/capy-api-notes.md):\n * - The turn is driven by `status` and `transcript` frames. `run`/`turn` framing is unreliable\n * at stream start (stray aborted turns, missing or late `run start`), so it is ignored.\n * - Live `assistant` fragments stream as message chunks. A committed assistant entry only adds\n * text the fragments missed (fast finishes, resumed streams, dropped frames).\n * - Capy commits the final reply's transcript entry after the `idle` status, so `Ended` waits for\n * every streamed reply to commit; otherwise the next turn's resume cursor would replay it. A reply\n * that streamed no fragments (a `dropped` turn) can still commit after `Ended`: the runner keeps\n * reading until the server closes the stream (see turn.ts).\n * - Strong models report every tool as `execute` with empty text; the committed tool entry's\n * `calls` list names the inner tools, so the title is upgraded when it lands.\n * - Capy never sends a tool's command line, file paths or output. Kinds that promise those\n * (`execute`, `edit`) are therefore not used for Capy's own frames: clients render them as an\n * empty command or a nameless file. File edits are reported by `fileChangeUpdate` instead, from\n * changes the adapter observes on disk (see changes.ts).\n */\nimport type { SessionUpdate, ToolCallContent, ToolKind } from \"@agentclientprotocol/sdk\"\nimport { type CapyEvent, type Message, type MessageAttachment, messageFiles, type ThreadStatus } from \"./capy/events.js\"\nimport type { FileChange } from \"./changes.js\"\n\nexport type TurnSignal =\n | { readonly _tag: \"Ended\" }\n | { readonly _tag: \"Failed\" }\n | { readonly _tag: \"Waiting\" }\n | { readonly _tag: \"Archived\" }\n | { readonly _tag: \"StreamDone\" }\n | { readonly _tag: \"StreamError\"; readonly code: string; readonly message: string }\n\ninterface ToolState {\n readonly title: string\n readonly kind: ToolKind\n readonly done: boolean\n /** Subagents only: the status last shown, and whether it was ever seen running. */\n readonly shown?: string\n readonly ran?: boolean\n}\n\nexport interface TurnState {\n /** Last transcript cursor seen; the next stream resumes after it. */\n readonly cursor: string | undefined\n readonly status: ThreadStatus | undefined\n /** True once the agent has demonstrably picked up this turn's message. */\n readonly active: boolean\n readonly assistant: ReadonlyMap<string, string>\n /** Assistant callIds whose transcript entry has committed. */\n readonly settled: ReadonlySet<string>\n /** Saw `idle` while a streamed reply had not committed yet; end once it does. */\n readonly endPending: boolean\n readonly lastAssistantCallId: string | undefined\n readonly tools: ReadonlyMap<string, ToolState>\n}\n\nexport interface Step {\n readonly state: TurnState\n readonly updates: ReadonlyArray<SessionUpdate>\n readonly signal?: TurnSignal\n /** Files the agent delivered with a reply. Linking them needs I/O, so the runner emits them. */\n readonly files?: ReadonlyArray<MessageAttachment>\n}\n\nexport const initialTurn = (cursor: string | undefined): TurnState => ({\n cursor,\n status: undefined,\n active: false,\n assistant: new Map(),\n settled: new Set(),\n endPending: false,\n lastAssistantCallId: undefined,\n tools: new Map()\n})\n\nconst READ_TOOLS = new Set([\"read\", \"view\", \"cat\", \"open\"])\nconst SEARCH_TOOLS = new Set([\"grep\", \"glob\", \"search\", \"find\", \"ls\", \"list\"])\nconst FETCH_TOOLS = new Set([\"fetch\", \"web_fetch\", \"web_search\", \"browse\"])\n\n/**\n * The ACP kind for a Capy tool call, from the inner tools it ran. Shell and write tools map to\n * `other`, because Capy gives no command or path to fill `execute` and `edit` items with.\n */\nexport const toolKind = (names: ReadonlyArray<string>): ToolKind => {\n const lower = names.map((name) => name.toLowerCase())\n if (lower.length > 0 && lower.every((name) => READ_TOOLS.has(name))) return \"read\"\n if (lower.length > 0 && lower.every((name) => SEARCH_TOOLS.has(name) || READ_TOOLS.has(name))) return \"search\"\n if (lower.length > 0 && lower.every((name) => FETCH_TOOLS.has(name))) return \"fetch\"\n if (lower.length > 0 && lower.every((name) => name === \"think\")) return \"think\"\n return \"other\"\n}\n\nconst formatSeconds = (ms: number) => (ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`)\n\n/** Title for a committed tool entry: its summary when it has one, else the inner tools it ran. */\nexport const toolTitle = (message: Message): string => {\n const summary = message.text?.trim() ?? \"\"\n if (summary !== \"\") return summary\n const calls = message.calls ?? []\n if (calls.length === 0) return message.tool ?? \"Tool call\"\n const names = [...new Set(calls.map((call) => call.tool))].join(\", \")\n const total = calls.reduce((sum, call) => sum + (call.durationMs ?? 0), 0)\n return total > 0 ? `${names} (${formatSeconds(total)})` : names\n}\n\nconst liveTitle = (name: string, text: string): string => {\n const summary = text.trim()\n if (summary !== \"\") return summary\n return name === \"execute\" ? \"Running tools\" : name\n}\n\nconst chunk = (text: string): SessionUpdate => ({\n sessionUpdate: \"agent_message_chunk\",\n content: { type: \"text\", text }\n})\n\n/** Emits assistant text, separating consecutive replies (Astra sends interim messages). */\nconst emitAssistant = (state: TurnState, callId: string, text: string): Step => {\n if (text === \"\") return { state, updates: [] }\n const previous = state.assistant.get(callId) ?? \"\"\n const separate = previous === \"\" && state.lastAssistantCallId !== undefined && state.lastAssistantCallId !== callId\n const assistant = new Map(state.assistant).set(callId, previous + text)\n return {\n state: { ...state, active: true, assistant, lastAssistantCallId: callId },\n updates: [chunk(separate ? `\\n\\n${text}` : text)]\n }\n}\n\nconst unsettled = (state: TurnState) => [...state.assistant.keys()].filter((id) => !state.settled.has(id)).length\n\n/** Every reply that streamed has committed. */\nexport const turnComplete = (state: TurnState) => unsettled(state) === 0\n\nconst endIfComplete = (step: Step): Step =>\n step.state.endPending && turnComplete(step.state)\n ? { ...step, state: { ...step.state, endPending: false }, signal: { _tag: \"Ended\" } }\n : step\n\nconst onTranscript = (state: TurnState, cursor: string | undefined, message: Message): Step => {\n const base: TurnState = { ...state, cursor: cursor ?? state.cursor }\n switch (message.source) {\n case \"user\":\n // Our own message committing proves the agent picked the turn up.\n return { state: { ...base, active: true }, updates: [] }\n case \"assistant\": {\n const callId = message.callId ?? message.id\n const text = message.text ?? \"\"\n // A resumed stream can deliver a settled entry again; its files were already shown.\n const files = base.settled.has(callId) ? [] : messageFiles(message)\n const streamed = base.assistant.get(callId) ?? \"\"\n // If the committed text diverged from the fragments, keep what streamed: chunks cannot be retracted.\n const emitted = text.startsWith(streamed)\n ? emitAssistant(base, callId, text.slice(streamed.length))\n : { state: { ...base, active: true }, updates: [] }\n const state: TurnState = {\n ...emitted.state,\n assistant: new Map(emitted.state.assistant).set(callId, emitted.state.assistant.get(callId) ?? text),\n settled: new Set(emitted.state.settled).add(callId)\n }\n return endIfComplete({ state, updates: emitted.updates, ...(files.length > 0 ? { files } : {}) })\n }\n case \"tool\": {\n const known = base.tools.get(message.id)\n // Report a tool's completion once. A resumed stream can deliver its entry again, and a repeat\n // would replace the file diffs the runner attached to it.\n if (known?.done === true) return { state: { ...base, active: true }, updates: [] }\n const names = message.calls?.map((call) => call.tool) ?? (message.tool === undefined ? [] : [message.tool])\n const title = toolTitle(message)\n const kind = toolKind(names.length > 0 ? names : [message.tool ?? \"\"])\n const tools = new Map(base.tools).set(message.id, { title, kind, done: true })\n const next: TurnState = { ...base, active: true, tools }\n if (known === undefined) {\n return {\n state: next,\n updates: [{ sessionUpdate: \"tool_call\", toolCallId: message.id, title, kind, status: \"completed\" }]\n }\n }\n return {\n state: next,\n updates: [{ sessionUpdate: \"tool_call_update\", toolCallId: message.id, title, kind, status: \"completed\" }]\n }\n }\n }\n}\n\n/** Subagent ids are prefixed so they can never collide with Capy's own tool call ids. */\nexport const subagentCallId = (id: string) => `capy-subagent-${id}`\n\nconst SUBAGENT_STATUS: Record<string, \"pending\" | \"in_progress\" | \"completed\" | \"failed\"> = {\n draft: \"pending\",\n working: \"in_progress\",\n waiting: \"in_progress\",\n idle: \"completed\",\n done: \"completed\",\n failed: \"failed\"\n}\n\n/** A subagent shows as one tool call that follows its lifecycle. */\nconst onSubagent = (state: TurnState, event: Extract<CapyEvent, { _tag: \"Subagent\" }>): Step => {\n const toolCallId = subagentCallId(event.id)\n const known = state.tools.get(toolCallId)\n const mapped = SUBAGENT_STATUS[event.status] ?? \"in_progress\"\n const ran = known?.ran === true || mapped === \"in_progress\"\n // `idle` means at rest: a new subagent is idle before it starts (seen live), so only one that ran has finished.\n const status = event.status === \"idle\" && !ran ? \"pending\" : mapped\n const done = status === \"completed\" || status === \"failed\"\n if ((known?.done === true && done) || known?.shown === status) return { state, updates: [] }\n const title = `Subagent ${event.path ?? event.id}`\n const tools = new Map(state.tools).set(toolCallId, { title, kind: \"other\" as const, done, shown: status, ran })\n const update: SessionUpdate = known === undefined\n ? { sessionUpdate: \"tool_call\", toolCallId, title, kind: \"other\", status }\n : { sessionUpdate: \"tool_call_update\", toolCallId, status }\n return { state: { ...state, tools }, updates: [update] }\n}\n\nexport const step = (state: TurnState, event: CapyEvent): Step => {\n switch (event._tag) {\n case \"Assistant\":\n return emitAssistant(state, event.callId, event.text)\n case \"ToolCall\": {\n if (state.tools.has(event.callId)) return { state, updates: [] }\n const title = liveTitle(event.name, event.text)\n const kind = toolKind([event.name])\n return {\n state: { ...state, active: true, tools: new Map(state.tools).set(event.callId, { title, kind, done: false }) },\n updates: [{ sessionUpdate: \"tool_call\", toolCallId: event.callId, title, kind, status: \"in_progress\" }]\n }\n }\n case \"Transcript\":\n return onTranscript(state, event.cursor, event.message)\n case \"Status\": {\n const next: TurnState = { ...state, status: event.status, active: state.active || event.status === \"working\" }\n // The first status frame on a fresh connection can still read `idle` before the agent picks up\n // the message, so idle/failed end the turn only after the turn became active.\n if (event.status === \"idle\" && next.active) {\n return turnComplete(next)\n ? { state: next, updates: [], signal: { _tag: \"Ended\" } }\n : { state: { ...next, endPending: true }, updates: [] }\n }\n if (event.status === \"failed\" && next.active) return { state: next, updates: [], signal: { _tag: \"Failed\" } }\n if (event.status === \"waiting\" && next.active) return { state: next, updates: [], signal: { _tag: \"Waiting\" } }\n if (event.status === \"archived\") return { state: next, updates: [], signal: { _tag: \"Archived\" } }\n return { state: next, updates: [] }\n }\n case \"Subagent\":\n return onSubagent(state, event)\n case \"StreamError\":\n return { state, updates: [], signal: { _tag: \"StreamError\", code: event.code, message: event.message } }\n case \"Done\":\n return { state, updates: [], signal: { _tag: \"StreamDone\" } }\n case \"Run\":\n case \"Turn\":\n case \"Heartbeat\":\n case \"Unknown\":\n return { state, updates: [] }\n }\n}\n\nconst MAX_TITLE_FILES = 3\n\n/** \"Edited README.md and docs/SPIKE.md\", \"Created a.ts, b.ts and 2 more files\". */\nexport const changeTitle = (changes: ReadonlyArray<FileChange>): string => {\n const verb = changes.every((c) => c.operation === \"add\")\n ? \"Created\"\n : changes.every((c) => c.operation === \"delete\")\n ? \"Deleted\"\n : \"Edited\"\n const names = changes.map((c) => c.relativePath)\n if (names.length <= MAX_TITLE_FILES) {\n return `${verb} ${names.length === 1 ? names[0] : `${names.slice(0, -1).join(\", \")} and ${names.at(-1)}`}`\n }\n const rest = names.length - (MAX_TITLE_FILES - 1)\n return `${verb} ${names.slice(0, MAX_TITLE_FILES - 1).join(\", \")} and ${rest} more files`\n}\n\n/**\n * The ACP update that shows a tool call's file changes as diffs. With `create`, it opens a new\n * tool call (for changes no Capy tool call can be credited with). `status` keeps a call that was\n * closed as failed (cancelled, failed run) from reading as completed.\n */\nexport const fileChangeUpdate = (\n toolCallId: string,\n changes: ReadonlyArray<FileChange>,\n options: { readonly create?: boolean; readonly status?: \"completed\" | \"failed\" } = {}\n): SessionUpdate => {\n const content: Array<ToolCallContent> = changes.flatMap((change) =>\n change.previewable\n ? [{\n type: \"diff\" as const,\n path: change.path,\n ...(change.oldText === undefined ? {} : { oldText: change.oldText }),\n newText: change.newText ?? \"\"\n }]\n : []\n )\n const fields = {\n toolCallId,\n title: changeTitle(changes),\n kind: changes.every((c) => c.operation === \"delete\") ? (\"delete\" as const) : (\"edit\" as const),\n status: options.status ?? \"completed\",\n content,\n locations: changes.map((change) => ({ path: change.path }))\n }\n return options.create === true ? { sessionUpdate: \"tool_call\", ...fields } : { sessionUpdate: \"tool_call_update\", ...fields }\n}\n\n/** Ids of tool calls an update set closes, in order. */\nexport const closedTools = (updates: ReadonlyArray<SessionUpdate>): ReadonlyArray<string> =>\n updates.flatMap((u) =>\n (u.sessionUpdate === \"tool_call\" || u.sessionUpdate === \"tool_call_update\") && (u.status === \"completed\" || u.status === \"failed\")\n ? [u.toolCallId]\n : []\n )\n\n/** Closes tool calls still in progress when the turn ends: completed on success, failed otherwise. */\nexport const finishTools = (state: TurnState, outcome: \"completed\" | \"failed\"): Step => {\n const updates: Array<SessionUpdate> = []\n const tools = new Map(state.tools)\n for (const [toolCallId, tool] of state.tools) {\n if (tool.done) continue\n tools.set(toolCallId, { ...tool, done: true })\n updates.push({ sessionUpdate: \"tool_call_update\", toolCallId, status: outcome })\n }\n return { state: { ...state, tools }, updates }\n}\n\n/**\n * A committed transcript as ACP history, for `session/load`: user and assistant text as message\n * chunks, tool entries as completed tool calls. Files are left to the caller, as in a live turn.\n */\nexport const history = (messages: ReadonlyArray<Message>): ReadonlyArray<{ readonly update: SessionUpdate; readonly files?: ReadonlyArray<MessageAttachment>; readonly source: \"user\" | \"assistant\" }> => {\n const out: Array<{ update: SessionUpdate; files?: ReadonlyArray<MessageAttachment>; source: \"user\" | \"assistant\" }> = []\n let previous: Message[\"source\"] | undefined\n for (const message of messages) {\n const files = messageFiles(message)\n const withFiles = files.length > 0 ? { files } : {}\n const text = message.text ?? \"\"\n if (message.source === \"tool\") {\n const names = message.calls?.map((call) => call.tool) ?? (message.tool === undefined ? [] : [message.tool])\n out.push({\n source: \"assistant\",\n update: { sessionUpdate: \"tool_call\", toolCallId: message.id, title: toolTitle(message), kind: toolKind(names), status: \"completed\" }\n })\n } else if (message.source === \"user\") {\n out.push({ source: \"user\", update: { sessionUpdate: \"user_message_chunk\", content: { type: \"text\", text } }, ...withFiles })\n } else {\n // Consecutive replies with nothing between them read as one message unless separated.\n const separated = previous === \"assistant\" ? `\\n\\n${text}` : text\n out.push({ source: \"assistant\", update: { sessionUpdate: \"agent_message_chunk\", content: { type: \"text\", text: separated } }, ...withFiles })\n }\n previous = message.source\n }\n return out\n}\n\n/** Replays a whole recorded stream; used by tests and the replay CLI. */\nexport const replay = (events: ReadonlyArray<CapyEvent>, cursor?: string) => {\n let state = initialTurn(cursor)\n const updates: Array<SessionUpdate> = []\n const signals: Array<TurnSignal> = []\n for (const event of events) {\n const result = step(state, event)\n state = result.state\n updates.push(...result.updates)\n if (result.signal !== undefined) signals.push(result.signal)\n }\n return { state, updates, signals }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"translate.js","sourceRoot":"","sources":["../src/translate.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAwD,YAAY,EAAqB,MAAM,kBAAkB,CAAA;AA6CxH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,MAA0B,EAAa,EAAE,CAAC,CAAC;IACrE,MAAM;IACN,MAAM,EAAE,SAAS;IACjB,MAAM,EAAE,KAAK;IACb,SAAS,EAAE,IAAI,GAAG,EAAE;IACpB,OAAO,EAAE,IAAI,GAAG,EAAE;IAClB,UAAU,EAAE,KAAK;IACjB,mBAAmB,EAAE,SAAS;IAC9B,KAAK,EAAE,IAAI,GAAG,EAAE;IAChB,SAAS,EAAE,KAAK;CACjB,CAAC,CAAA;AAEF,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAA;AAC3D,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAA;AAC9E,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAA;AAE3E;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,KAA4B,EAAY,EAAE;IACjE,MAAM,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI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MAAM,CAAA;IAC3B,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAED,yEAAyE;AACzE,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,MAAgC,EAAE,MAAe,EAAE,EAAE;IAC1E,IAAI,KAAK,GAAG,WAAW,CAAC,MAAM,CAAC,CAAA;IAC/B,MAAM,OAAO,GAAyB,EAAE,CAAA;IACxC,MAAM,OAAO,GAAsB,EAAE,CAAA;IACrC,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;QACjC,KAAK,GAAG,MAAM,CAAC,KAAK,CAAA;QACpB,OAAO,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;QAC/B,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS;YAAE,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;IAC9D,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,CAAA;AACpC,CAAC,CAAA","sourcesContent":["/**\n * Translates one prompt turn's Capy stream events into ACP `session/update` payloads.\n *\n * Pure and synchronous so recorded streams replay deterministically in tests. Rules come from\n * the spike recordings (see docs/capy-api-notes.md):\n * - The turn is driven by `status` and `transcript` frames. `run`/`turn` framing is unreliable\n * at stream start (stray aborted turns, missing or late `run start`), so it is ignored.\n * - Live `assistant` fragments stream as message chunks. A committed assistant entry only adds\n * text the fragments missed (fast finishes, resumed streams, dropped frames).\n * - Capy commits the final reply's transcript entry after the `idle` status, so `Ended` waits for\n * every streamed reply to commit; otherwise the next turn's resume cursor would replay it. A reply\n * that streamed no fragments (a `dropped` turn) can still commit after `Ended`: the runner keeps\n * reading until the server closes the stream (see turn.ts).\n * - Strong models report every tool as `execute` with empty text; the committed tool entry's\n * `calls` list names the inner tools, so the title is upgraded when it lands. An `execute` entry\n * without that list is a call an interrupt stopped (see `toolStatus`).\n * - Capy never sends a tool's command line, file paths or output. Kinds that promise those\n * (`execute`, `edit`) are therefore not used for Capy's own frames: clients render them as an\n * empty command or a nameless file. File edits are reported by `fileChangeUpdate` instead, from\n * changes the adapter observes on disk (see changes.ts).\n */\nimport type { SessionUpdate, ToolCallContent, ToolCallStatus, ToolKind } from \"@agentclientprotocol/sdk\"\nimport { type CapyEvent, type Message, type MessageAttachment, messageFiles, type ThreadStatus } from \"./capy/events.js\"\nimport type { FileChange } from \"./changes.js\"\n\nexport type TurnSignal =\n | { readonly _tag: \"Ended\" }\n | { readonly _tag: \"Failed\" }\n | { readonly _tag: \"Waiting\" }\n | { readonly _tag: \"Archived\" }\n | { readonly _tag: \"StreamDone\" }\n | { readonly _tag: \"StreamError\"; readonly code: string; readonly message: string }\n\ninterface ToolState {\n readonly title: string\n readonly kind: ToolKind\n readonly done: boolean\n /** Subagents only: the status last shown, and whether it was ever seen running. */\n readonly shown?: string\n readonly ran?: boolean\n}\n\nexport interface TurnState {\n /** Last transcript cursor seen; the next stream resumes after it. */\n readonly cursor: string | undefined\n readonly status: ThreadStatus | undefined\n /** True once the agent has demonstrably picked up this turn's message. */\n readonly active: boolean\n readonly assistant: ReadonlyMap<string, string>\n /** Assistant callIds whose transcript entry has committed. */\n readonly settled: ReadonlySet<string>\n /** Saw `idle` while a streamed reply had not committed yet; end once it does. */\n readonly endPending: boolean\n readonly lastAssistantCallId: string | undefined\n readonly tools: ReadonlyMap<string, ToolState>\n /** The client cancelled the prompt. */\n readonly cancelled: boolean\n}\n\nexport interface Step {\n readonly state: TurnState\n readonly updates: ReadonlyArray<SessionUpdate>\n readonly signal?: TurnSignal\n /** Files the agent delivered with a reply. Linking them needs I/O, so the runner emits them. */\n readonly files?: ReadonlyArray<MessageAttachment>\n}\n\nexport const initialTurn = (cursor: string | undefined): TurnState => ({\n cursor,\n status: undefined,\n active: false,\n assistant: new Map(),\n settled: new Set(),\n endPending: false,\n lastAssistantCallId: undefined,\n tools: new Map(),\n cancelled: false\n})\n\nconst READ_TOOLS = new Set([\"read\", \"view\", \"cat\", \"open\"])\nconst SEARCH_TOOLS = new Set([\"grep\", \"glob\", \"search\", \"find\", \"ls\", \"list\"])\nconst FETCH_TOOLS = new Set([\"fetch\", \"web_fetch\", \"web_search\", \"browse\"])\n\n/**\n * The ACP kind for a Capy tool call, from the inner tools it ran. Shell and write tools map to\n * `other`, because Capy gives no command or path to fill `execute` and `edit` items with.\n */\nexport const toolKind = (names: ReadonlyArray<string>): ToolKind => {\n const lower = names.map((name) => name.toLowerCase())\n if (lower.length > 0 && lower.every((name) => READ_TOOLS.has(name))) return \"read\"\n if (lower.length > 0 && lower.every((name) => SEARCH_TOOLS.has(name) || READ_TOOLS.has(name))) return \"search\"\n if (lower.length > 0 && lower.every((name) => FETCH_TOOLS.has(name))) return \"fetch\"\n if (lower.length > 0 && lower.every((name) => name === \"think\")) return \"think\"\n return \"other\"\n}\n\n/**\n * How a committed tool entry ended. Each `execute` call that ran to its end lists its inner tools with\n * their durations, and Capy commits a call that an interrupt stopped with no `calls` list at all (seen\n * in every cancelled test turn). An entry that names its tool directly (Haiku's `bash`) never lists\n * inner tools, so after a cancel its outcome is unknown, and it shows as failed rather than finished.\n */\nexport const toolStatus = (message: Message, cancelled: boolean): \"completed\" | \"failed\" => {\n if ((message.calls?.length ?? 0) > 0) return \"completed\"\n if (message.tool === \"execute\") return \"failed\"\n return cancelled ? \"failed\" : \"completed\"\n}\n\nconst formatSeconds = (ms: number) => (ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`)\n\n/** Title for a committed tool entry: its summary when it has one, else the inner tools it ran. */\nexport const toolTitle = (message: Message): string => {\n const summary = message.text?.trim() ?? \"\"\n if (summary !== \"\") return summary\n const calls = message.calls ?? []\n if (calls.length === 0) return message.tool === \"execute\" ? \"Stopped tool call\" : (message.tool ?? \"Tool call\")\n const names = [...new Set(calls.map((call) => call.tool))].join(\", \")\n const total = calls.reduce((sum, call) => sum + (call.durationMs ?? 0), 0)\n return total > 0 ? `${names} (${formatSeconds(total)})` : names\n}\n\nconst liveTitle = (name: string, text: string): string => {\n const summary = text.trim()\n if (summary !== \"\") return summary\n return name === \"execute\" ? \"Running tools\" : name\n}\n\nconst chunk = (text: string): SessionUpdate => ({\n sessionUpdate: \"agent_message_chunk\",\n content: { type: \"text\", text }\n})\n\n/** Emits assistant text, separating consecutive replies (Astra sends interim messages). */\nconst emitAssistant = (state: TurnState, callId: string, text: string): Step => {\n if (text === \"\") return { state, updates: [] }\n const previous = state.assistant.get(callId) ?? \"\"\n const separate = previous === \"\" && state.lastAssistantCallId !== undefined && state.lastAssistantCallId !== callId\n const assistant = new Map(state.assistant).set(callId, previous + text)\n return {\n state: { ...state, active: true, assistant, lastAssistantCallId: callId },\n updates: [chunk(separate ? `\\n\\n${text}` : text)]\n }\n}\n\nconst unsettled = (state: TurnState) => [...state.assistant.keys()].filter((id) => !state.settled.has(id)).length\n\n/** Every reply that streamed has committed. */\nexport const turnComplete = (state: TurnState) => unsettled(state) === 0\n\nconst endIfComplete = (step: Step): Step =>\n step.state.endPending && turnComplete(step.state)\n ? { ...step, state: { ...step.state, endPending: false }, signal: { _tag: \"Ended\" } }\n : step\n\nconst onTranscript = (state: TurnState, cursor: string | undefined, message: Message): Step => {\n const base: TurnState = { ...state, cursor: cursor ?? state.cursor }\n switch (message.source) {\n case \"user\":\n // Our own message committing proves the agent picked the turn up.\n return { state: { ...base, active: true }, updates: [] }\n case \"assistant\": {\n const callId = message.callId ?? message.id\n const text = message.text ?? \"\"\n // A resumed stream can deliver a settled entry again; its files were already shown.\n const files = base.settled.has(callId) ? [] : messageFiles(message)\n const streamed = base.assistant.get(callId) ?? \"\"\n // If the committed text diverged from the fragments, keep what streamed: chunks cannot be retracted.\n const emitted = text.startsWith(streamed)\n ? emitAssistant(base, callId, text.slice(streamed.length))\n : { state: { ...base, active: true }, updates: [] }\n const state: TurnState = {\n ...emitted.state,\n assistant: new Map(emitted.state.assistant).set(callId, emitted.state.assistant.get(callId) ?? text),\n settled: new Set(emitted.state.settled).add(callId)\n }\n return endIfComplete({ state, updates: emitted.updates, ...(files.length > 0 ? { files } : {}) })\n }\n case \"tool\": {\n const known = base.tools.get(message.id)\n // Report a tool's completion once. A resumed stream can deliver its entry again, and a repeat\n // would replace the file diffs the runner attached to it.\n if (known?.done === true) return { state: { ...base, active: true }, updates: [] }\n const names = message.calls?.map((call) => call.tool) ?? (message.tool === undefined ? [] : [message.tool])\n const title = toolTitle(message)\n const kind = toolKind(names.length > 0 ? names : [message.tool ?? \"\"])\n const status = toolStatus(message, base.cancelled)\n const tools = new Map(base.tools).set(message.id, { title, kind, done: true })\n const next: TurnState = { ...base, active: true, tools }\n const fields = { toolCallId: message.id, title, kind, status }\n return {\n state: next,\n updates: [known === undefined ? { sessionUpdate: \"tool_call\", ...fields } : { sessionUpdate: \"tool_call_update\", ...fields }]\n }\n }\n }\n}\n\n/** Subagent ids are prefixed so they can never collide with Capy's own tool call ids. */\nexport const subagentCallId = (id: string) => `capy-subagent-${id}`\n\nconst SUBAGENT_STATUS: Record<string, \"pending\" | \"in_progress\" | \"completed\" | \"failed\"> = {\n draft: \"pending\",\n working: \"in_progress\",\n waiting: \"in_progress\",\n idle: \"completed\",\n done: \"completed\",\n failed: \"failed\"\n}\n\n/** A subagent shows as one tool call that follows its lifecycle. */\nconst onSubagent = (state: TurnState, event: Extract<CapyEvent, { _tag: \"Subagent\" }>): Step => {\n const toolCallId = subagentCallId(event.id)\n const known = state.tools.get(toolCallId)\n const mapped = SUBAGENT_STATUS[event.status] ?? \"in_progress\"\n const ran = known?.ran === true || mapped === \"in_progress\"\n // `idle` means at rest: a new subagent is idle before it starts (seen live), so only one that ran has finished.\n const status = event.status === \"idle\" && !ran ? \"pending\" : mapped\n const done = status === \"completed\" || status === \"failed\"\n if ((known?.done === true && done) || known?.shown === status) return { state, updates: [] }\n const title = `Subagent ${event.path ?? event.id}`\n const tools = new Map(state.tools).set(toolCallId, { title, kind: \"other\" as const, done, shown: status, ran })\n const update: SessionUpdate = known === undefined\n ? { sessionUpdate: \"tool_call\", toolCallId, title, kind: \"other\", status }\n : { sessionUpdate: \"tool_call_update\", toolCallId, status }\n return { state: { ...state, tools }, updates: [update] }\n}\n\nexport const step = (state: TurnState, event: CapyEvent): Step => {\n switch (event._tag) {\n case \"Assistant\":\n return emitAssistant(state, event.callId, event.text)\n case \"ToolCall\": {\n if (state.tools.has(event.callId)) return { state, updates: [] }\n const title = liveTitle(event.name, event.text)\n const kind = toolKind([event.name])\n return {\n state: { ...state, active: true, tools: new Map(state.tools).set(event.callId, { title, kind, done: false }) },\n updates: [{ sessionUpdate: \"tool_call\", toolCallId: event.callId, title, kind, status: \"in_progress\" }]\n }\n }\n case \"Transcript\":\n return onTranscript(state, event.cursor, event.message)\n case \"Status\": {\n const next: TurnState = { ...state, status: event.status, active: state.active || event.status === \"working\" }\n // The first status frame on a fresh connection can still read `idle` before the agent picks up\n // the message, so idle/failed end the turn only after the turn became active.\n if (event.status === \"idle\" && next.active) {\n return turnComplete(next)\n ? { state: next, updates: [], signal: { _tag: \"Ended\" } }\n : { state: { ...next, endPending: true }, updates: [] }\n }\n if (event.status === \"failed\" && next.active) return { state: next, updates: [], signal: { _tag: \"Failed\" } }\n if (event.status === \"waiting\" && next.active) return { state: next, updates: [], signal: { _tag: \"Waiting\" } }\n if (event.status === \"archived\") return { state: next, updates: [], signal: { _tag: \"Archived\" } }\n return { state: next, updates: [] }\n }\n case \"Subagent\":\n return onSubagent(state, event)\n case \"StreamError\":\n return { state, updates: [], signal: { _tag: \"StreamError\", code: event.code, message: event.message } }\n case \"Done\":\n return { state, updates: [], signal: { _tag: \"StreamDone\" } }\n case \"Run\":\n case \"Turn\":\n case \"Heartbeat\":\n case \"Unknown\":\n return { state, updates: [] }\n }\n}\n\nconst MAX_TITLE_FILES = 3\n\n/** \"Edited README.md and docs/SPIKE.md\", \"Created a.ts, b.ts and 2 more files\". */\nexport const changeTitle = (changes: ReadonlyArray<FileChange>): string => {\n const verb = changes.every((c) => c.operation === \"add\")\n ? \"Created\"\n : changes.every((c) => c.operation === \"delete\")\n ? \"Deleted\"\n : \"Edited\"\n const names = changes.map((c) => c.relativePath)\n if (names.length <= MAX_TITLE_FILES) {\n return `${verb} ${names.length === 1 ? names[0] : `${names.slice(0, -1).join(\", \")} and ${names.at(-1)}`}`\n }\n const rest = names.length - (MAX_TITLE_FILES - 1)\n return `${verb} ${names.slice(0, MAX_TITLE_FILES - 1).join(\", \")} and ${rest} more files`\n}\n\n/**\n * The ACP update that shows a tool call's file changes as diffs. `status` keeps a call that was closed\n * as failed (cancelled, failed run) from reading as completed. With `outside`, it opens an item of its\n * own for changes that no Capy tool call made: they happened while no call that can write ran, so\n * they are the user's, or a background command's. Its kind is `other`, so that clients show the title,\n * which says so, and not a plain \"changed files\".\n */\nexport const fileChangeUpdate = (\n toolCallId: string,\n changes: ReadonlyArray<FileChange>,\n options: { readonly outside?: boolean; readonly status?: \"completed\" | \"failed\" } = {}\n): SessionUpdate => {\n const content: Array<ToolCallContent> = changes.flatMap((change) =>\n change.previewable\n ? [{\n type: \"diff\" as const,\n path: change.path,\n ...(change.oldText === undefined ? {} : { oldText: change.oldText }),\n newText: change.newText ?? \"\"\n }]\n : []\n )\n const locations = changes.map((change) => ({ path: change.path }))\n if (options.outside === true) {\n const title = `${changeTitle(changes)} outside a Capy tool call`\n return { sessionUpdate: \"tool_call\", toolCallId, title, kind: \"other\", status: \"completed\", content, locations }\n }\n return {\n sessionUpdate: \"tool_call_update\",\n toolCallId,\n title: changeTitle(changes),\n kind: changes.every((c) => c.operation === \"delete\") ? \"delete\" : \"edit\",\n status: options.status ?? \"completed\",\n content,\n locations\n }\n}\n\nexport interface ClosedTool {\n readonly toolCallId: string\n readonly status: Extract<ToolCallStatus, \"completed\" | \"failed\">\n /** Set when the update names it; subagent updates carry the status only. */\n readonly kind: ToolKind | undefined\n}\n\n/** The tool calls an update set closes, in order. */\nexport const closedTools = (updates: ReadonlyArray<SessionUpdate>): ReadonlyArray<ClosedTool> =>\n updates.flatMap((u) =>\n (u.sessionUpdate === \"tool_call\" || u.sessionUpdate === \"tool_call_update\") && (u.status === \"completed\" || u.status === \"failed\")\n ? [{ toolCallId: u.toolCallId, status: u.status, kind: u.kind ?? undefined }]\n : []\n )\n\n/** Closes tool calls still in progress when the turn ends: completed on success, failed otherwise. */\nexport const finishTools = (state: TurnState, outcome: \"completed\" | \"failed\"): Step => {\n const updates: Array<SessionUpdate> = []\n const tools = new Map(state.tools)\n for (const [toolCallId, tool] of state.tools) {\n if (tool.done) continue\n tools.set(toolCallId, { ...tool, done: true })\n updates.push({ sessionUpdate: \"tool_call_update\", toolCallId, status: outcome })\n }\n return { state: { ...state, tools }, updates }\n}\n\n/**\n * A committed transcript as ACP history, for `session/load`: user and assistant text as message\n * chunks, tool entries as completed tool calls. Files are left to the caller, as in a live turn.\n */\nexport const history = (messages: ReadonlyArray<Message>): ReadonlyArray<{ readonly update: SessionUpdate; readonly files?: ReadonlyArray<MessageAttachment>; readonly source: \"user\" | \"assistant\" }> => {\n const out: Array<{ update: SessionUpdate; files?: ReadonlyArray<MessageAttachment>; source: \"user\" | \"assistant\" }> = []\n let previous: Message[\"source\"] | undefined\n for (const message of messages) {\n const files = messageFiles(message)\n const withFiles = files.length > 0 ? { files } : {}\n const text = message.text ?? \"\"\n if (message.source === \"tool\") {\n const names = message.calls?.map((call) => call.tool) ?? (message.tool === undefined ? [] : [message.tool])\n out.push({\n source: \"assistant\",\n update: { sessionUpdate: \"tool_call\", toolCallId: message.id, title: toolTitle(message), kind: toolKind(names), status: toolStatus(message, false) }\n })\n } else if (message.source === \"user\") {\n out.push({ source: \"user\", update: { sessionUpdate: \"user_message_chunk\", content: { type: \"text\", text } }, ...withFiles })\n } else {\n // Consecutive replies with nothing between them read as one message unless separated.\n const separated = previous === \"assistant\" ? `\\n\\n${text}` : text\n out.push({ source: \"assistant\", update: { sessionUpdate: \"agent_message_chunk\", content: { type: \"text\", text: separated } }, ...withFiles })\n }\n previous = message.source\n }\n return out\n}\n\n/** Replays a whole recorded stream; used by tests and the replay CLI. */\nexport const replay = (events: ReadonlyArray<CapyEvent>, cursor?: string) => {\n let state = initialTurn(cursor)\n const updates: Array<SessionUpdate> = []\n const signals: Array<TurnSignal> = []\n for (const event of events) {\n const result = step(state, event)\n state = result.state\n updates.push(...result.updates)\n if (result.signal !== undefined) signals.push(result.signal)\n }\n return { state, updates, signals }\n}\n"]}
|
package/dist/turn.js
CHANGED
|
@@ -9,7 +9,6 @@ import { basename, isAbsolute, join } from "node:path";
|
|
|
9
9
|
import { pathToFileURL } from "node:url";
|
|
10
10
|
import { Duration, Effect, Option, Result, Stream } from "effect";
|
|
11
11
|
import { CapyClient, CapyTransportError, describeError, isTransient } from "./capy/client.js";
|
|
12
|
-
import { mergeChanges } from "./changes.js";
|
|
13
12
|
import { closedTools, fileChangeUpdate, finishTools, initialTurn, step, turnComplete } from "./translate.js";
|
|
14
13
|
const MAX_IDLE_RECHECKS = 5;
|
|
15
14
|
/** How long an `until=run` connection may stay open after the turn ended before it is dropped. */
|
|
@@ -19,9 +18,8 @@ const CANCEL_GRACE = Duration.seconds(20);
|
|
|
19
18
|
const MAX_FAILURES = 12;
|
|
20
19
|
const backoff = (attempt) => Duration.millis(Math.min(30_000, 250 * 2 ** attempt));
|
|
21
20
|
const chunk = (text) => ({ sessionUpdate: "agent_message_chunk", content: { type: "text", text } });
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
: update;
|
|
21
|
+
/** Kinds of calls that cannot write files: changes seen while one ran are not its doing. */
|
|
22
|
+
const READ_ONLY = new Set(["read", "search", "fetch", "think"]);
|
|
25
23
|
export const titleOf = (text) => {
|
|
26
24
|
const line = text.split("\n").find((l) => l.trim() !== "")?.trim() ?? "capy-acp session";
|
|
27
25
|
return line.length > 80 ? `${line.slice(0, 77)}…` : line;
|
|
@@ -127,29 +125,30 @@ export const runTurn = (input) => Effect.gen(function* () {
|
|
|
127
125
|
let lost;
|
|
128
126
|
/** Set once the client cancels; the loop keeps reading until the thread settles. */
|
|
129
127
|
let cancelRequested = false;
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
128
|
+
/**
|
|
129
|
+
* Shows changes on the tool call that made them. Each call is credited once, when it closes (or at the
|
|
130
|
+
* end of the turn if it never did), so its content is never replaced. Changes with no call to credit
|
|
131
|
+
* (`undefined`) get an item of their own that says they came from outside Capy's tool calls.
|
|
132
|
+
*/
|
|
134
133
|
const showChanges = (toolCallId, changes, status) => {
|
|
135
134
|
if (changes.length === 0)
|
|
136
135
|
return Effect.void;
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
if (merged.length === 0)
|
|
141
|
-
return Effect.void;
|
|
142
|
-
return input.emit(fileChangeUpdate(id, merged, { create: toolCallId === undefined, status }));
|
|
136
|
+
return toolCallId === undefined
|
|
137
|
+
? input.emit(fileChangeUpdate(`capy-acp-changes-${randomUUID()}`, changes, { outside: true }))
|
|
138
|
+
: input.emit(fileChangeUpdate(toolCallId, changes, { status }));
|
|
143
139
|
};
|
|
144
140
|
const apply = (event) => Effect.gen(function* () {
|
|
145
141
|
if (event._tag !== "Heartbeat")
|
|
146
142
|
received++;
|
|
147
143
|
const before = state.cursor;
|
|
148
|
-
const
|
|
144
|
+
const running = [...state.tools.values()].some((tool) => !tool.done);
|
|
145
|
+
const result = step(cancelRequested ? { ...state, cancelled: true } : state, event);
|
|
149
146
|
state = result.state;
|
|
150
|
-
|
|
151
|
-
//
|
|
152
|
-
const
|
|
147
|
+
const updates = result.updates;
|
|
148
|
+
// A call starts while none runs: the changes since the last look were not made by a Capy tool call.
|
|
149
|
+
const starts = updates.some((u) => u.sessionUpdate === "tool_call" && u.status === "in_progress");
|
|
150
|
+
if (starts && !running && tracker !== undefined)
|
|
151
|
+
yield* showChanges(undefined, yield* tracker.collect, "completed");
|
|
153
152
|
yield* Effect.forEach(updates, input.emit, { discard: true });
|
|
154
153
|
for (const file of result.files ?? []) {
|
|
155
154
|
yield* input.emit({ sessionUpdate: "agent_message_chunk", content: yield* fileLink(capy, id, file) });
|
|
@@ -157,12 +156,10 @@ export const runTurn = (input) => Effect.gen(function* () {
|
|
|
157
156
|
if (state.cursor !== undefined && state.cursor !== before && input.onCursor !== undefined) {
|
|
158
157
|
yield* input.onCursor(id, state.cursor);
|
|
159
158
|
}
|
|
160
|
-
const
|
|
161
|
-
if (
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
if (tracker !== undefined)
|
|
165
|
-
yield* showChanges(lastTool, yield* tracker.collect, cancelRequested ? "failed" : "completed");
|
|
159
|
+
const last = closedTools(updates).at(-1);
|
|
160
|
+
if (last !== undefined && tracker !== undefined) {
|
|
161
|
+
// The call just finished, so whatever changed on disk since the last look is its doing, unless it cannot write.
|
|
162
|
+
yield* showChanges(READ_ONLY.has(last.kind) ? undefined : last.toolCallId, yield* tracker.collect, last.status);
|
|
166
163
|
}
|
|
167
164
|
return result.signal;
|
|
168
165
|
});
|
|
@@ -296,25 +293,26 @@ export const runTurn = (input) => Effect.gen(function* () {
|
|
|
296
293
|
state = closed.state;
|
|
297
294
|
yield* Effect.forEach(closed.updates, input.emit, { discard: true });
|
|
298
295
|
// A last look catches edits from a call that never reported completing (interrupts, a final
|
|
299
|
-
// entry that lagged).
|
|
296
|
+
// entry that lagged). With no call left open, the edits came after the last call finished.
|
|
300
297
|
if (tracker !== undefined) {
|
|
301
|
-
const stillOpen = closedTools(closed.updates).at(-1);
|
|
302
|
-
yield* showChanges(stillOpen
|
|
298
|
+
const stillOpen = closedTools(closed.updates).at(-1)?.toolCallId;
|
|
299
|
+
yield* showChanges(stillOpen, yield* tracker.collect, closeAs);
|
|
303
300
|
}
|
|
304
301
|
if (outcome === "failed")
|
|
305
|
-
yield* input.emit(chunk("\n\
|
|
302
|
+
yield* input.emit(chunk("\n\n**Capy reported that this run failed.** The thread keeps its transcript. Send another message to retry."));
|
|
306
303
|
if (outcome === "archived")
|
|
307
|
-
yield* input.emit(chunk("\n\
|
|
304
|
+
yield* input.emit(chunk("\n\n**This Capy thread is archived.** Start a new chat to continue."));
|
|
308
305
|
if (outcome === "lost") {
|
|
309
|
-
yield* input.emit(chunk(`\n\
|
|
310
|
-
"thread
|
|
306
|
+
yield* input.emit(chunk(`\n\n**Lost the connection to Capy** (${lost === undefined ? "unknown error" : describeError(lost)}). Capy may still be ` +
|
|
307
|
+
"working in its thread. Your next message here continues from where this reply stopped."));
|
|
311
308
|
}
|
|
312
309
|
if (outcome === "not-started") {
|
|
313
|
-
yield* input.emit(chunk("Capy has not started on this message yet
|
|
314
|
-
"and is signed in. The message stays in the
|
|
310
|
+
yield* input.emit(chunk("**Capy has not started on this message yet.** Check that the Capy desktop app or `capy dock` runs on this computer " +
|
|
311
|
+
"and is signed in. The message stays in the queue, and Capy starts it when the device is back."));
|
|
315
312
|
}
|
|
316
313
|
if (outcome === "waiting-limit") {
|
|
317
|
-
yield* input.emit(chunk("\n\
|
|
314
|
+
yield* input.emit(chunk("\n\n**Capy is waiting on a background command.** It continues in its thread on its own, and the Capy app shows the " +
|
|
315
|
+
"rest. A new message here stops the wait, so send one only when you want Capy to change course."));
|
|
318
316
|
}
|
|
319
317
|
return { threadId: id, cursor: state.cursor, stopReason: outcome === "cancelled" ? "cancelled" : "end_turn" };
|
|
320
318
|
});
|