capy-acp 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +184 -2
- package/dist/agent.js +468 -0
- package/dist/agent.js.map +1 -0
- package/dist/bin.js +74 -0
- package/dist/bin.js.map +1 -0
- package/dist/capy/client.js +174 -0
- package/dist/capy/client.js.map +1 -0
- package/dist/capy/events.js +140 -0
- package/dist/capy/events.js.map +1 -0
- package/dist/changes.js +218 -0
- package/dist/changes.js.map +1 -0
- package/dist/config.js +41 -0
- package/dist/config.js.map +1 -0
- package/dist/doctor.js +102 -0
- package/dist/doctor.js.map +1 -0
- package/dist/pricing.js +60 -0
- package/dist/pricing.js.map +1 -0
- package/dist/problems.js +108 -0
- package/dist/problems.js.map +1 -0
- package/dist/prompt.js +101 -0
- package/dist/prompt.js.map +1 -0
- package/dist/setup.js +92 -0
- package/dist/setup.js.map +1 -0
- package/dist/sse.js +95 -0
- package/dist/sse.js.map +1 -0
- package/dist/store.js +85 -0
- package/dist/store.js.map +1 -0
- package/dist/translate.js +309 -0
- package/dist/translate.js.map +1 -0
- package/dist/turn.js +319 -0
- package/dist/turn.js.map +1 -0
- package/dist/version.js +5 -0
- package/dist/version.js.map +1 -0
- package/dist/workspace.js +164 -0
- package/dist/workspace.js.map +1 -0
- package/package.json +48 -4
package/dist/problems.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** An Error that carries a Problem, for code paths that throw. */
|
|
2
|
+
export class ProblemError extends Error {
|
|
3
|
+
problem;
|
|
4
|
+
constructor(problem) {
|
|
5
|
+
super(`${problem.title}. ${problem.detail}`);
|
|
6
|
+
this.problem = problem;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export const problemOf = (error) => (error instanceof ProblemError ? error.problem : undefined);
|
|
10
|
+
export const toMarkdown = (problem) => [`**${problem.title}**`, problem.detail, problem.steps.map((step, i) => `${i + 1}. ${step}`).join("\n")]
|
|
11
|
+
.filter((part) => part !== "")
|
|
12
|
+
.join("\n\n");
|
|
13
|
+
export const toText = (problem, indent = "") => [`${problem.title}. ${problem.detail}`, ...problem.steps.map((step, i) => `${indent}${i + 1}. ${step}`)].join("\n");
|
|
14
|
+
const RETRY = "Send your message again.";
|
|
15
|
+
const NEW_SESSION = "Start a new chat in that folder. A session keeps the folder that it opened with.";
|
|
16
|
+
export const noApiKey = (keyFile) => ({
|
|
17
|
+
title: "Add your Capy API key",
|
|
18
|
+
detail: "capy-acp needs a Capy API key to start Capy threads.",
|
|
19
|
+
steps: [
|
|
20
|
+
"Create a key in the Capy app under Settings, then API.",
|
|
21
|
+
`Run \`npx -y capy-acp --setup\` in a terminal and paste the key (it goes to ${keyFile}). If your editor offers Sign in for this agent, that runs the same command. You can also set \`CAPY_API_KEY\` in the agent's environment.`,
|
|
22
|
+
RETRY
|
|
23
|
+
]
|
|
24
|
+
});
|
|
25
|
+
export const rejectedApiKey = (detail) => ({
|
|
26
|
+
title: "Replace your Capy API key",
|
|
27
|
+
detail: `Capy did not accept the API key (${detail}).`,
|
|
28
|
+
steps: ["Create a new key in the Capy app under Settings, then API.", "Run `npx -y capy-acp --setup` and paste it.", RETRY]
|
|
29
|
+
});
|
|
30
|
+
export const unreachable = (apiUrl, detail) => ({
|
|
31
|
+
title: "Capy could not be reached",
|
|
32
|
+
detail: `${detail}.`,
|
|
33
|
+
steps: [`Check the network connection to ${apiUrl}.`, RETRY]
|
|
34
|
+
});
|
|
35
|
+
export const noDevice = (files) => ({
|
|
36
|
+
title: "Start Capy on this computer",
|
|
37
|
+
detail: "Capy threads run on this computer, and capy-acp found no Capy device here.",
|
|
38
|
+
steps: [
|
|
39
|
+
"Open the Capy desktop app and sign in, or run `capy dock` on a computer without a screen.",
|
|
40
|
+
RETRY,
|
|
41
|
+
`capy-acp looked in ${files.map((file) => `${file.path} (${file.found === "missing" ? "missing" : "no device in it"})`).join(" and ")}. Capy desktop 0.10.0 writes device-ids.json when it starts, and older versions may not, so update the desktop app if you use it. Or set \`CAPY_DEVICE_ID\` to this computer's device id.`
|
|
42
|
+
]
|
|
43
|
+
});
|
|
44
|
+
export const unreadableDeviceFile = (file, detail) => ({
|
|
45
|
+
title: "Check the Capy desktop app",
|
|
46
|
+
detail: `capy-acp could not read the device file ${file} (${detail}).`,
|
|
47
|
+
steps: ["Restart the Capy desktop app, or set `CAPY_DEVICE_ID` to the id of this computer's Capy device.", RETRY]
|
|
48
|
+
});
|
|
49
|
+
export const manyOrganizations = (count) => ({
|
|
50
|
+
title: "Choose a Capy organization",
|
|
51
|
+
detail: `This computer is paired with ${count} Capy organizations, so capy-acp cannot tell which device to use.`,
|
|
52
|
+
steps: ["Set `CAPY_DEVICE_ID` in the agent's environment to the device id of the organization that you want.", RETRY]
|
|
53
|
+
});
|
|
54
|
+
const isT3Scratch = (folder) => {
|
|
55
|
+
const parts = folder.split(/[\\/]+/);
|
|
56
|
+
return parts.some((part, i) => part === ".t3" && parts[i + 1] === "scratch");
|
|
57
|
+
};
|
|
58
|
+
export const notGit = (folder) => isT3Scratch(folder)
|
|
59
|
+
? {
|
|
60
|
+
title: "Open a project to use Capy",
|
|
61
|
+
detail: "T3 Code started this chat without a project. Capy threads run on a GitHub repository from one of your Capy projects.",
|
|
62
|
+
steps: ["In T3 Code, add a project for a clone of that repository.", "Start a new chat in that project."]
|
|
63
|
+
}
|
|
64
|
+
: {
|
|
65
|
+
title: "Open a repository to use Capy",
|
|
66
|
+
detail: `${folder} is not in a git repository. Capy threads run on a GitHub repository from one of your Capy projects.`,
|
|
67
|
+
steps: ["Open a clone of that repository in your editor.", NEW_SESSION]
|
|
68
|
+
};
|
|
69
|
+
export const noGitHubRemote = (gitRoot) => ({
|
|
70
|
+
title: "Add the GitHub remote",
|
|
71
|
+
detail: `${gitRoot} has no git remote that names a GitHub repository, so capy-acp cannot find its Capy project.`,
|
|
72
|
+
steps: ["Add the remote, for example `git remote add origin git@github.com:owner/repo.git`.", RETRY]
|
|
73
|
+
});
|
|
74
|
+
export const notInProject = (repos) => ({
|
|
75
|
+
title: `Add ${repos[0]} to a Capy project`,
|
|
76
|
+
detail: `No Capy project includes ${repos.join(" or ")}.`,
|
|
77
|
+
steps: ["Open https://capy.ai/settings/projects and add the repository to a project.", RETRY]
|
|
78
|
+
});
|
|
79
|
+
const linkSteps = (input) => {
|
|
80
|
+
// Only the device itself can link a local folder: the desktop app, or `capy dock dirs add`. The
|
|
81
|
+
// web app cannot. `capy://app/<path>` opens that page of the desktop app (checked in 0.10.0).
|
|
82
|
+
const desktop = `Open \`capy://app/settings/projects/${input.projectId}\` to show "${input.projectName}" in the Capy desktop app. Set it up on this computer and choose ${input.root}.`;
|
|
83
|
+
const dock = [
|
|
84
|
+
"Stop `capy dock`. Caution: this also stops the Capy threads that run on this computer.",
|
|
85
|
+
`Run \`capy dock dirs add ${input.root}\`, then start \`capy dock\` again.`
|
|
86
|
+
];
|
|
87
|
+
if (input.device === "desktop")
|
|
88
|
+
return [desktop];
|
|
89
|
+
if (input.device === "dock")
|
|
90
|
+
return dock;
|
|
91
|
+
return [`With the desktop app: ${desktop}`, `With \`capy dock\`: ${dock.join(" ")}`];
|
|
92
|
+
};
|
|
93
|
+
export const notLinked = (input) => input.sameRepoRoot === undefined
|
|
94
|
+
? {
|
|
95
|
+
title: "Link this folder to Capy",
|
|
96
|
+
detail: `Capy runs threads only in folders that are linked to this computer, and ${input.root} is not linked.`,
|
|
97
|
+
steps: [...linkSteps(input), RETRY]
|
|
98
|
+
}
|
|
99
|
+
: {
|
|
100
|
+
title: `Use the folder that Capy links for ${input.repo}`,
|
|
101
|
+
detail: `On this computer, Capy links ${input.repo} at ${input.sameRepoRoot}, not at ${input.root}.`,
|
|
102
|
+
steps: [
|
|
103
|
+
`Open ${input.sameRepoRoot} in your editor, and start a new chat there.`,
|
|
104
|
+
`Or link ${input.root} instead. ${linkSteps(input).join(" ")} Then send your message again.`,
|
|
105
|
+
`Or set \`CAPY_ACP_ALLOW_WORKTREE_FALLBACK=1\` in the agent's environment. Capy then works in a new worktree of ${input.sameRepoRoot}, and its edits do not appear in ${input.root}.`
|
|
106
|
+
]
|
|
107
|
+
};
|
|
108
|
+
//# sourceMappingURL=problems.js.map
|
|
@@ -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,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;KACrG,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC;KAC7B,IAAI,CAAC,MAAM,CAAC,CAAA;AAEjB,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,OAAgB,EAAE,MAAM,GAAG,EAAE,EAAU,EAAE,CAC9D,CAAC,GAAG,OAAO,CAAC,KAAK,KAAK,OAAO,CAAC,MAAM,EAAE,EAAE,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAA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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/prompt.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** Capy's per-file upload limit (`POST /files`). */
|
|
2
|
+
export const MAX_UPLOAD_BYTES = 262_144_000;
|
|
3
|
+
const EXTENSIONS = {
|
|
4
|
+
"image/png": "png",
|
|
5
|
+
"image/jpeg": "jpg",
|
|
6
|
+
"image/gif": "gif",
|
|
7
|
+
"image/webp": "webp",
|
|
8
|
+
"image/svg+xml": "svg",
|
|
9
|
+
"image/avif": "avif",
|
|
10
|
+
"audio/mpeg": "mp3",
|
|
11
|
+
"audio/mp3": "mp3",
|
|
12
|
+
"audio/wav": "wav",
|
|
13
|
+
"audio/x-wav": "wav",
|
|
14
|
+
"audio/ogg": "ogg",
|
|
15
|
+
"audio/webm": "webm",
|
|
16
|
+
"audio/mp4": "m4a",
|
|
17
|
+
"application/pdf": "pdf"
|
|
18
|
+
};
|
|
19
|
+
/** The file name a block's URI ends in, if it has one. */
|
|
20
|
+
const uriName = (uri) => {
|
|
21
|
+
if (!uri)
|
|
22
|
+
return undefined;
|
|
23
|
+
const path = uri.replace(/[?#].*$/, "");
|
|
24
|
+
const raw = path.slice(path.lastIndexOf("/") + 1);
|
|
25
|
+
let name = raw;
|
|
26
|
+
try {
|
|
27
|
+
name = decodeURIComponent(raw);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
// A stray "%" (`100%.png`) is not an escape; keep the name as written.
|
|
31
|
+
}
|
|
32
|
+
return name === "" ? undefined : name;
|
|
33
|
+
};
|
|
34
|
+
const blockText = (block) => {
|
|
35
|
+
switch (block.type) {
|
|
36
|
+
case "text":
|
|
37
|
+
return block.text;
|
|
38
|
+
case "resource_link":
|
|
39
|
+
return `[${block.name}](${block.uri})`;
|
|
40
|
+
case "resource": {
|
|
41
|
+
const resource = block.resource;
|
|
42
|
+
if ("text" in resource) {
|
|
43
|
+
return `<file uri="${resource.uri}">\n${resource.text}\n</file>`;
|
|
44
|
+
}
|
|
45
|
+
return "";
|
|
46
|
+
}
|
|
47
|
+
case "image":
|
|
48
|
+
case "audio":
|
|
49
|
+
return "";
|
|
50
|
+
default:
|
|
51
|
+
return "";
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
const USER_REQUEST = /<user_request>\s*([\s\S]*?)\s*<\/user_request>/;
|
|
55
|
+
const HOST_BLOCK = /<(t3_code_instructions|runtime_info|pull_request_linking)>[\s\S]*?<\/\1>/;
|
|
56
|
+
// Global copy for replace only: `test` on a /g regex keeps `lastIndex` between calls.
|
|
57
|
+
const HOST_BLOCKS = new RegExp(HOST_BLOCK.source, "g");
|
|
58
|
+
const ATTRIBUTION = /^\s*\[T3 Code: [^\]\n]* sent this message, not the user\.\]\s*/;
|
|
59
|
+
/** Strips T3's host instructions from one text block, keeping the user's request. */
|
|
60
|
+
export const unwrapHostEnvelope = (text) => {
|
|
61
|
+
const request = USER_REQUEST.exec(text);
|
|
62
|
+
const body = request?.[1] !== undefined && HOST_BLOCK.test(text.replace(USER_REQUEST, "")) ? request[1] : text.replace(HOST_BLOCKS, "");
|
|
63
|
+
// The attribution can sit inside `<user_request>` too, when an agent starts a thread.
|
|
64
|
+
return body.replace(ATTRIBUTION, "").trim();
|
|
65
|
+
};
|
|
66
|
+
export const promptText = (blocks, options) => blocks
|
|
67
|
+
.map((block) => block.type === "text" && !options.forwardHostInstructions ? unwrapHostEnvelope(block.text) : blockText(block))
|
|
68
|
+
.map((part) => part.trim())
|
|
69
|
+
.filter((part) => part !== "")
|
|
70
|
+
.join("\n\n");
|
|
71
|
+
/** The prompt's text plus its media, decoded for upload. */
|
|
72
|
+
export const promptParts = (blocks, options) => {
|
|
73
|
+
const files = [];
|
|
74
|
+
const notes = [];
|
|
75
|
+
const counts = new Map();
|
|
76
|
+
const add = (kind, data, mediaType, uri) => {
|
|
77
|
+
const bytes = Buffer.from(data, "base64");
|
|
78
|
+
const n = (counts.get(kind) ?? 0) + 1;
|
|
79
|
+
counts.set(kind, n);
|
|
80
|
+
const name = uriName(uri) ?? `${kind}-${n}.${EXTENSIONS[mediaType] ?? "bin"}`;
|
|
81
|
+
if (bytes.byteLength === 0)
|
|
82
|
+
return;
|
|
83
|
+
if (bytes.byteLength > MAX_UPLOAD_BYTES) {
|
|
84
|
+
notes.push(`[${name} was not attached: it is over Capy's 250 MB file limit]`);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
files.push({ name, mediaType, bytes });
|
|
88
|
+
};
|
|
89
|
+
for (const block of blocks) {
|
|
90
|
+
if (block.type === "image")
|
|
91
|
+
add("image", block.data, block.mimeType, block.uri);
|
|
92
|
+
else if (block.type === "audio")
|
|
93
|
+
add("audio", block.data, block.mimeType, undefined);
|
|
94
|
+
else if (block.type === "resource" && "blob" in block.resource) {
|
|
95
|
+
add("file", block.resource.blob, block.resource.mimeType ?? "application/octet-stream", block.resource.uri);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const text = [promptText(blocks, options), ...notes].filter((part) => part !== "").join("\n\n");
|
|
99
|
+
return { text, files };
|
|
100
|
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AAM;QAClC,IAAI,KAAK,CAAC,UAAU,GAAG,gBAAgB,EAAE,CAAC;YACxC,KAAK,CAAC,IAAI,CAAC,IAAI,IAAI,yDAAyD,CAAC,CAAA;YAC7E,OAAM;QACR,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAA;IACxC,CAAC,CAAA;IACD,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;YAAE,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;aAC1E,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;YAAE,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAA;aAC/E,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,IAAI,MAAM,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;YAC/D,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,IAAI,0BAA0B,EAAE,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;QAC7G,CAAC;IACH,CAAC;IACD,MAAM,IAAI,GAAG,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IAC/F,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;AACxB,CAAC,CAAA","sourcesContent":["/**\n * Turns an ACP prompt into the text sent to Capy.\n *\n * T3 Code adds host instructions to prompts that describe T3-only tools Capy's agent does not\n * have. It sends two shapes (both seen in T3 Code 0.1.12):\n * - Typed in T3: `<t3_code_instructions>…</t3_code_instructions><user_request>…</user_request>`\n * followed by `<runtime_info>` and `<pull_request_linking>` blocks.\n * - Sent by another agent: an attribution line\n * `[T3 Code: the agent in T3 thread \"…\" sent this message, not the user.]` before the request,\n * either inside that same envelope or bare with only the trailing blocks.\n * By default only the request itself is forwarded; `CAPY_ACP_FORWARD_HOST_INSTRUCTIONS=1` forwards\n * everything.\n *\n * Images, audio and binary embedded resources become files attached to the Capy message, which\n * land on the agent's machine (Capy's models see attached images).\n */\nimport type { ContentBlock } from \"@agentclientprotocol/sdk\"\nimport type { FileUpload } from \"./capy/client.js\"\n\n/** Capy's per-file upload limit (`POST /files`). */\nexport const MAX_UPLOAD_BYTES = 262_144_000\n\nconst EXTENSIONS: Record<string, string> = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpg\",\n \"image/gif\": \"gif\",\n \"image/webp\": \"webp\",\n \"image/svg+xml\": \"svg\",\n \"image/avif\": \"avif\",\n \"audio/mpeg\": \"mp3\",\n \"audio/mp3\": \"mp3\",\n \"audio/wav\": \"wav\",\n \"audio/x-wav\": \"wav\",\n \"audio/ogg\": \"ogg\",\n \"audio/webm\": \"webm\",\n \"audio/mp4\": \"m4a\",\n \"application/pdf\": \"pdf\"\n}\n\n/** The file name a block's URI ends in, if it has one. */\nconst uriName = (uri: string | null | undefined): string | undefined => {\n if (!uri) return undefined\n const path = uri.replace(/[?#].*$/, \"\")\n const raw = path.slice(path.lastIndexOf(\"/\") + 1)\n let name = raw\n try {\n name = decodeURIComponent(raw)\n } catch {\n // A stray \"%\" (`100%.png`) is not an escape; keep the name as written.\n }\n return name === \"\" ? undefined : name\n}\n\nconst blockText = (block: ContentBlock): string => {\n switch (block.type) {\n case \"text\":\n return block.text\n case \"resource_link\":\n return `[${block.name}](${block.uri})`\n case \"resource\": {\n const resource = block.resource\n if (\"text\" in resource) {\n return `<file uri=\"${resource.uri}\">\\n${resource.text}\\n</file>`\n }\n return \"\"\n }\n case \"image\":\n case \"audio\":\n return \"\"\n default:\n return \"\"\n }\n}\n\nconst USER_REQUEST = /<user_request>\\s*([\\s\\S]*?)\\s*<\\/user_request>/\nconst HOST_BLOCK = /<(t3_code_instructions|runtime_info|pull_request_linking)>[\\s\\S]*?<\\/\\1>/\n// Global copy for replace only: `test` on a /g regex keeps `lastIndex` between calls.\nconst HOST_BLOCKS = new RegExp(HOST_BLOCK.source, \"g\")\nconst ATTRIBUTION = /^\\s*\\[T3 Code: [^\\]\\n]* sent this message, not the user\\.\\]\\s*/\n\n/** Strips T3's host instructions from one text block, keeping the user's request. */\nexport const unwrapHostEnvelope = (text: string): string => {\n const request = USER_REQUEST.exec(text)\n const body =\n request?.[1] !== undefined && HOST_BLOCK.test(text.replace(USER_REQUEST, \"\")) ? request[1] : text.replace(HOST_BLOCKS, \"\")\n // The attribution can sit inside `<user_request>` too, when an agent starts a thread.\n return body.replace(ATTRIBUTION, \"\").trim()\n}\n\nexport const promptText = (\n blocks: ReadonlyArray<ContentBlock>,\n options: { readonly forwardHostInstructions: boolean }\n): string =>\n blocks\n .map((block) =>\n block.type === \"text\" && !options.forwardHostInstructions ? unwrapHostEnvelope(block.text) : blockText(block)\n )\n .map((part) => part.trim())\n .filter((part) => part !== \"\")\n .join(\"\\n\\n\")\n\nexport interface PromptParts {\n readonly text: string\n readonly files: ReadonlyArray<FileUpload>\n}\n\n/** The prompt's text plus its media, decoded for upload. */\nexport const promptParts = (\n blocks: ReadonlyArray<ContentBlock>,\n options: { readonly forwardHostInstructions: boolean }\n): PromptParts => {\n const files: Array<FileUpload> = []\n const notes: Array<string> = []\n const counts = new Map<string, number>()\n const add = (kind: string, data: string, mediaType: string, uri: string | null | undefined) => {\n const bytes = Buffer.from(data, \"base64\")\n const n = (counts.get(kind) ?? 0) + 1\n counts.set(kind, n)\n const name = uriName(uri) ?? `${kind}-${n}.${EXTENSIONS[mediaType] ?? \"bin\"}`\n if (bytes.byteLength === 0) return\n if (bytes.byteLength > MAX_UPLOAD_BYTES) {\n notes.push(`[${name} was not attached: it is over Capy's 250 MB file limit]`)\n return\n }\n files.push({ name, mediaType, bytes })\n }\n for (const block of blocks) {\n if (block.type === \"image\") add(\"image\", block.data, block.mimeType, block.uri)\n else if (block.type === \"audio\") add(\"audio\", block.data, block.mimeType, undefined)\n else if (block.type === \"resource\" && \"blob\" in block.resource) {\n add(\"file\", block.resource.blob, block.resource.mimeType ?? \"application/octet-stream\", block.resource.uri)\n }\n }\n const text = [promptText(blocks, options), ...notes].filter((part) => part !== \"\").join(\"\\n\\n\")\n return { text, files }\n}\n"]}
|
package/dist/setup.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `capy-acp --setup`: saves a Capy API key on this machine. ACP clients run it as the agent's
|
|
3
|
+
* terminal auth method; people can run it directly too. The key is checked against Capy before it
|
|
4
|
+
* is saved, and is never printed.
|
|
5
|
+
*/
|
|
6
|
+
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
7
|
+
import { dirname } from "node:path";
|
|
8
|
+
import { readDevice } from "./workspace.js";
|
|
9
|
+
/** The terminal auth method that `initialize` announces. */
|
|
10
|
+
export const API_KEY_AUTH = {
|
|
11
|
+
type: "terminal",
|
|
12
|
+
id: "capy-api-key",
|
|
13
|
+
name: "Capy API key",
|
|
14
|
+
description: "Save a Capy API key on this machine. Create a key in the Capy app under Settings, then API.",
|
|
15
|
+
args: ["--setup"]
|
|
16
|
+
};
|
|
17
|
+
/** The key from `CAPY_API_KEY` or the key file, or undefined when neither has one. */
|
|
18
|
+
export const savedApiKey = async (config) => {
|
|
19
|
+
const fromEnv = process.env.CAPY_API_KEY?.trim();
|
|
20
|
+
if (fromEnv)
|
|
21
|
+
return fromEnv;
|
|
22
|
+
const fromFile = await readFile(config.apiKeyFile, "utf8").then((text) => text.trim(), () => "");
|
|
23
|
+
return fromFile || undefined;
|
|
24
|
+
};
|
|
25
|
+
/** Returns the exit code: 0 when a key is saved and accepted. */
|
|
26
|
+
export const runSetup = async (config, io) => {
|
|
27
|
+
io.write(`capy-acp setup. The key goes to ${config.apiKeyFile} (readable only by you).\n`);
|
|
28
|
+
const key = (await io.readSecret("Capy API key: ")).trim();
|
|
29
|
+
if (key === "") {
|
|
30
|
+
io.write("No key entered. Nothing was saved.\n");
|
|
31
|
+
return 1;
|
|
32
|
+
}
|
|
33
|
+
const check = await io
|
|
34
|
+
.fetch(`${config.apiUrl}/projects`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" } })
|
|
35
|
+
.then((response) => response.status, (error) => (error instanceof Error ? error.message : String(error)));
|
|
36
|
+
if (check === 401 || check === 403) {
|
|
37
|
+
io.write("Capy rejected this key. Nothing was saved.\n");
|
|
38
|
+
return 1;
|
|
39
|
+
}
|
|
40
|
+
await mkdir(dirname(config.apiKeyFile), { recursive: true, mode: 0o700 });
|
|
41
|
+
await writeFile(config.apiKeyFile, `${key}\n`, { mode: 0o600 });
|
|
42
|
+
// writeFile keeps the mode of a file that already exists.
|
|
43
|
+
await chmod(config.apiKeyFile, 0o600);
|
|
44
|
+
io.write(typeof check === "number" && check >= 200 && check < 300
|
|
45
|
+
? "Capy accepted the key. Saved.\n"
|
|
46
|
+
: `Saved, but capy-acp could not check the key with Capy (${check}).\n`);
|
|
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
|
+
return 0;
|
|
49
|
+
};
|
|
50
|
+
/** Reads a line from the terminal with echo off, or the first line of piped input. */
|
|
51
|
+
export const readSecretFromTerminal = (prompt) => {
|
|
52
|
+
const input = process.stdin;
|
|
53
|
+
if (!input.isTTY) {
|
|
54
|
+
return new Promise((resolve) => {
|
|
55
|
+
let data = "";
|
|
56
|
+
input.setEncoding("utf8");
|
|
57
|
+
input.on("data", (chunk) => (data += chunk));
|
|
58
|
+
input.on("end", () => resolve(data.split(/\r?\n/)[0] ?? ""));
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
process.stdout.write(prompt);
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
let value = "";
|
|
64
|
+
const finish = (error) => {
|
|
65
|
+
input.off("data", onData);
|
|
66
|
+
input.setRawMode(false);
|
|
67
|
+
input.pause();
|
|
68
|
+
process.stdout.write("\n");
|
|
69
|
+
if (error)
|
|
70
|
+
reject(error);
|
|
71
|
+
else
|
|
72
|
+
resolve(value);
|
|
73
|
+
};
|
|
74
|
+
const onData = (chunk) => {
|
|
75
|
+
for (const char of chunk) {
|
|
76
|
+
if (char === "\r" || char === "\n")
|
|
77
|
+
return finish();
|
|
78
|
+
if (char === "\u0003")
|
|
79
|
+
return finish(new Error("Cancelled."));
|
|
80
|
+
if (char === "\u007f" || char === "\b")
|
|
81
|
+
value = value.slice(0, -1);
|
|
82
|
+
else
|
|
83
|
+
value += char;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
input.setEncoding("utf8");
|
|
87
|
+
input.setRawMode(true);
|
|
88
|
+
input.resume();
|
|
89
|
+
input.on("data", onData);
|
|
90
|
+
});
|
|
91
|
+
};
|
|
92
|
+
//# sourceMappingURL=setup.js.map
|
|
@@ -0,0 +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,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,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OAAO,MAAM,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/sse.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
export const makeSseParser = () => {
|
|
2
|
+
let buffer = "";
|
|
3
|
+
let event = "";
|
|
4
|
+
let data = [];
|
|
5
|
+
let id;
|
|
6
|
+
let sawField = false;
|
|
7
|
+
const dispatch = (out) => {
|
|
8
|
+
if (sawField && data.length > 0) {
|
|
9
|
+
out.push({ event: event === "" ? "message" : event, data: data.join("\n"), ...(id === undefined ? {} : { id }) });
|
|
10
|
+
}
|
|
11
|
+
event = "";
|
|
12
|
+
data = [];
|
|
13
|
+
id = undefined;
|
|
14
|
+
sawField = false;
|
|
15
|
+
};
|
|
16
|
+
const line = (raw, out) => {
|
|
17
|
+
if (raw === "")
|
|
18
|
+
return dispatch(out);
|
|
19
|
+
if (raw.startsWith(":"))
|
|
20
|
+
return;
|
|
21
|
+
const colon = raw.indexOf(":");
|
|
22
|
+
const field = colon === -1 ? raw : raw.slice(0, colon);
|
|
23
|
+
let value = colon === -1 ? "" : raw.slice(colon + 1);
|
|
24
|
+
if (value.startsWith(" "))
|
|
25
|
+
value = value.slice(1);
|
|
26
|
+
switch (field) {
|
|
27
|
+
case "event":
|
|
28
|
+
event = value;
|
|
29
|
+
sawField = true;
|
|
30
|
+
return;
|
|
31
|
+
case "data":
|
|
32
|
+
data.push(value);
|
|
33
|
+
sawField = true;
|
|
34
|
+
return;
|
|
35
|
+
case "id":
|
|
36
|
+
if (!value.includes("\u0000"))
|
|
37
|
+
id = value;
|
|
38
|
+
sawField = true;
|
|
39
|
+
return;
|
|
40
|
+
default:
|
|
41
|
+
// `retry:` and unknown fields carry nothing the adapter needs.
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
const drain = (final) => {
|
|
46
|
+
const out = [];
|
|
47
|
+
for (;;) {
|
|
48
|
+
const match = /\r\n|\r|\n/.exec(buffer);
|
|
49
|
+
if (match === null)
|
|
50
|
+
break;
|
|
51
|
+
// A lone trailing "\r" may be the first half of "\r\n"; wait for the next chunk.
|
|
52
|
+
if (match[0] === "\r" && match.index === buffer.length - 1 && !final)
|
|
53
|
+
break;
|
|
54
|
+
line(buffer.slice(0, match.index), out);
|
|
55
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
56
|
+
}
|
|
57
|
+
if (final) {
|
|
58
|
+
if (buffer !== "")
|
|
59
|
+
line(buffer, out);
|
|
60
|
+
buffer = "";
|
|
61
|
+
dispatch(out);
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
};
|
|
65
|
+
// Chunks with no line break are only collected, and joined once a break arrives: scanning the
|
|
66
|
+
// whole buffer for every chunk made one long line (a big frame) cost quadratic time.
|
|
67
|
+
let pending = [];
|
|
68
|
+
const flush = () => {
|
|
69
|
+
if (pending.length > 0) {
|
|
70
|
+
buffer += pending.join("");
|
|
71
|
+
pending = [];
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
push: (chunk) => {
|
|
76
|
+
if (!/[\r\n]/.test(chunk) && !buffer.endsWith("\r")) {
|
|
77
|
+
pending.push(chunk);
|
|
78
|
+
return [];
|
|
79
|
+
}
|
|
80
|
+
flush();
|
|
81
|
+
buffer += chunk;
|
|
82
|
+
return drain(false);
|
|
83
|
+
},
|
|
84
|
+
end: () => {
|
|
85
|
+
flush();
|
|
86
|
+
return drain(true);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
/** Parses a complete recorded stream, for fixtures and tests. */
|
|
91
|
+
export const parseSse = (text) => {
|
|
92
|
+
const parser = makeSseParser();
|
|
93
|
+
return [...parser.push(text), ...parser.end()];
|
|
94
|
+
};
|
|
95
|
+
//# sourceMappingURL=sse.js.map
|
package/dist/sse.js.map
ADDED
|
@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G,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,EAAE,CAAC,CAAA;AAChD,CAAC,CAAA","sourcesContent":["/**\n * Incremental Server-Sent Events parser (WHATWG event-stream rules, minus reconnection).\n *\n * Capy's stream is read with fetch because EventSource cannot send an Authorization header,\n * so the frames are parsed here. Feed it decoded text in arbitrary chunks; complete frames\n * come out as soon as their terminating blank line arrives.\n */\nexport interface SseFrame {\n readonly event: string\n readonly data: string\n /** Present only when the frame carried an `id:` line. Capy sets it on `transcript` frames. */\n readonly id?: string\n}\n\nexport interface SseParser {\n /** Feeds a chunk of text and returns the frames it completed. */\n readonly push: (chunk: string) => ReadonlyArray<SseFrame>\n /** Flushes a final frame that had no trailing blank line. */\n readonly end: () => ReadonlyArray<SseFrame>\n}\n\nexport const makeSseParser = (): SseParser => {\n let buffer = \"\"\n let event = \"\"\n let data: Array<string> = []\n let id: string | undefined\n let sawField = false\n\n const dispatch = (out: Array<SseFrame>) => {\n if (sawField && data.length > 0) {\n out.push({ event: event === \"\" ? \"message\" : event, data: data.join(\"\\n\"), ...(id === undefined ? {} : { id }) })\n }\n event = \"\"\n data = []\n id = undefined\n sawField = false\n }\n\n const line = (raw: string, out: Array<SseFrame>) => {\n if (raw === \"\") return dispatch(out)\n if (raw.startsWith(\":\")) return\n const colon = raw.indexOf(\":\")\n const field = colon === -1 ? raw : raw.slice(0, colon)\n let value = colon === -1 ? \"\" : raw.slice(colon + 1)\n if (value.startsWith(\" \")) value = value.slice(1)\n switch (field) {\n case \"event\":\n event = value\n sawField = true\n return\n case \"data\":\n data.push(value)\n sawField = true\n return\n case \"id\":\n if (!value.includes(\"\\u0000\")) id = value\n sawField = true\n return\n default:\n // `retry:` and unknown fields carry nothing the adapter needs.\n return\n }\n }\n\n const drain = (final: boolean): ReadonlyArray<SseFrame> => {\n const out: Array<SseFrame> = []\n for (;;) {\n const match = /\\r\\n|\\r|\\n/.exec(buffer)\n if (match === null) break\n // A lone trailing \"\\r\" may be the first half of \"\\r\\n\"; wait for the next chunk.\n if (match[0] === \"\\r\" && match.index === buffer.length - 1 && !final) break\n line(buffer.slice(0, match.index), out)\n buffer = buffer.slice(match.index + match[0].length)\n }\n if (final) {\n if (buffer !== \"\") line(buffer, out)\n buffer = \"\"\n dispatch(out)\n }\n return out\n }\n\n // Chunks with no line break are only collected, and joined once a break arrives: scanning the\n // whole buffer for every chunk made one long line (a big frame) cost quadratic time.\n let pending: Array<string> = []\n const flush = () => {\n if (pending.length > 0) {\n buffer += pending.join(\"\")\n pending = []\n }\n }\n\n return {\n push: (chunk) => {\n if (!/[\\r\\n]/.test(chunk) && !buffer.endsWith(\"\\r\")) {\n pending.push(chunk)\n return []\n }\n flush()\n buffer += chunk\n return drain(false)\n },\n end: () => {\n flush()\n return drain(true)\n }\n }\n}\n\n/** Parses a complete recorded stream, for fixtures and tests. */\nexport const parseSse = (text: string): ReadonlyArray<SseFrame> => {\n const parser = makeSseParser()\n return [...parser.push(text), ...parser.end()]\n}\n"]}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remembers which Capy thread each ACP session drives, so `session/load` and `session/resume`
|
|
3
|
+
* work after the client or the adapter restarts.
|
|
4
|
+
*
|
|
5
|
+
* One small JSON file per session under the state directory: T3 Code runs one adapter process
|
|
6
|
+
* per thread, and separate files need no locking between them. Writes go to a temp file first
|
|
7
|
+
* and are renamed into place, so a crash never leaves a half-written record. Records hold ids and
|
|
8
|
+
* settings only, never credentials.
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { Schema } from "effect";
|
|
14
|
+
export const SessionRecord = Schema.Struct({
|
|
15
|
+
sessionId: Schema.String,
|
|
16
|
+
cwd: Schema.String,
|
|
17
|
+
threadId: Schema.String,
|
|
18
|
+
/** Last transcript event id the client has seen; the next stream resumes after it. */
|
|
19
|
+
cursor: Schema.optionalKey(Schema.String),
|
|
20
|
+
model: Schema.String,
|
|
21
|
+
reasoning: Schema.String,
|
|
22
|
+
title: Schema.optionalKey(Schema.String),
|
|
23
|
+
updatedAt: Schema.String
|
|
24
|
+
});
|
|
25
|
+
const decode = Schema.decodeUnknownOption(Schema.fromJsonString(SessionRecord));
|
|
26
|
+
/** Session ids come from clients; only plain ids may become file names. */
|
|
27
|
+
const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
28
|
+
export const makeSessionStore = (dir) => {
|
|
29
|
+
const file = (sessionId) => join(dir, `${sessionId}.json`);
|
|
30
|
+
// Saves of one session run one at a time, in call order: Windows refuses a rename onto a file that
|
|
31
|
+
// another rename is replacing (EPERM, seen on Windows Server 2022), and the last save must win.
|
|
32
|
+
const queues = new Map();
|
|
33
|
+
const write = async (record) => {
|
|
34
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
35
|
+
// Unique per write, so a crashed or failed write never collides with the next one.
|
|
36
|
+
const temp = `${file(record.sessionId)}.${randomUUID()}.tmp`;
|
|
37
|
+
try {
|
|
38
|
+
await writeFile(temp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
|
|
39
|
+
await rename(temp, file(record.sessionId));
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
await rm(temp, { force: true }).catch(() => undefined);
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const read = async (path) => {
|
|
47
|
+
try {
|
|
48
|
+
const record = decode(await readFile(path, "utf8"));
|
|
49
|
+
return record._tag === "Some" ? record.value : undefined;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
get: async (sessionId) => (SAFE_ID.test(sessionId) ? read(file(sessionId)) : undefined),
|
|
57
|
+
save: (record) => {
|
|
58
|
+
if (!SAFE_ID.test(record.sessionId))
|
|
59
|
+
return Promise.resolve();
|
|
60
|
+
const id = record.sessionId;
|
|
61
|
+
const next = (queues.get(id) ?? Promise.resolve()).then(() => write(record), () => write(record));
|
|
62
|
+
queues.set(id, next);
|
|
63
|
+
const settle = () => {
|
|
64
|
+
if (queues.get(id) === next)
|
|
65
|
+
queues.delete(id);
|
|
66
|
+
};
|
|
67
|
+
next.then(settle, settle);
|
|
68
|
+
return next;
|
|
69
|
+
},
|
|
70
|
+
list: async () => {
|
|
71
|
+
let names;
|
|
72
|
+
try {
|
|
73
|
+
names = await readdir(dir);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return [];
|
|
77
|
+
}
|
|
78
|
+
const records = await Promise.all(names.filter((name) => name.endsWith(".json")).map((name) => read(join(dir, name))));
|
|
79
|
+
return records
|
|
80
|
+
.filter((record) => record !== undefined)
|
|
81
|
+
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
//# sourceMappingURL=store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAClF,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAE/B,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC;IACzC,SAAS,EAAE,MAAM,CAAC,MAAM;IACxB,GAAG,EAAE,MAAM,CAAC,MAAM;IAClB,QAAQ,EAAE,MAAM,CAAC,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CAAA;YACpB,MAAM,MAAM,GAAG,GAAG,EAAE;gBAClB,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,IAAI;oBAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;YAChD,CAAC,CAAA;YACD,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;YACzB,OAAO,IAAI,CAAA;QACb,CAAC;QACD,IAAI,EAAE,KAAK,IAAI,EAAE;YACf,IAAI,KAAoB,CAAA;YACxB,IAAI,CAAC;gBACH,KAAK,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,CAAA;YAC5B,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,EAAE,CAAA;YACX,CAAC;YACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;YACtH,OAAO,OAAO;iBACX,MAAM,CAAC,CAAC,MAAM,EAA2B,EAAE,CAAC,MAAM,KAAK,SAAS,CAAC;iBACjE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAA;QAC3D,CAAC;KACF,CAAA;AACH,CAAC,CAAA","sourcesContent":["/**\n * Remembers which Capy thread each ACP session drives, so `session/load` and `session/resume`\n * work after the client or the adapter restarts.\n *\n * One small JSON file per session under the state directory: T3 Code runs one adapter process\n * per thread, and separate files need no locking between them. Writes go to a temp file first\n * and are renamed into place, so a crash never leaves a half-written record. Records hold ids and\n * settings only, never credentials.\n */\nimport { randomUUID } from \"node:crypto\"\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\"\nimport { join } from \"node:path\"\nimport { Schema } from \"effect\"\n\nexport const SessionRecord = Schema.Struct({\n sessionId: Schema.String,\n cwd: Schema.String,\n threadId: Schema.String,\n /** Last transcript event id the client has seen; the next stream resumes after it. */\n cursor: Schema.optionalKey(Schema.String),\n model: Schema.String,\n reasoning: Schema.String,\n title: Schema.optionalKey(Schema.String),\n updatedAt: Schema.String\n})\nexport type SessionRecord = typeof SessionRecord.Type\n\nconst decode = Schema.decodeUnknownOption(Schema.fromJsonString(SessionRecord))\n\n/** Session ids come from clients; only plain ids may become file names. */\nconst SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/\n\nexport interface SessionStore {\n readonly get: (sessionId: string) => Promise<SessionRecord | undefined>\n readonly save: (record: SessionRecord) => Promise<void>\n /** Newest first. */\n readonly list: () => Promise<ReadonlyArray<SessionRecord>>\n}\n\nexport const makeSessionStore = (dir: string): SessionStore => {\n const file = (sessionId: string) => join(dir, `${sessionId}.json`)\n // Saves of one session run one at a time, in call order: Windows refuses a rename onto a file that\n // another rename is replacing (EPERM, seen on Windows Server 2022), and the last save must win.\n const queues = new Map<string, Promise<void>>()\n const write = async (record: SessionRecord) => {\n await mkdir(dir, { recursive: true, mode: 0o700 })\n // Unique per write, so a crashed or failed write never collides with the next one.\n const temp = `${file(record.sessionId)}.${randomUUID()}.tmp`\n try {\n await writeFile(temp, `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 })\n await rename(temp, file(record.sessionId))\n } catch (error) {\n await rm(temp, { force: true }).catch(() => undefined)\n throw error\n }\n }\n const read = async (path: string): Promise<SessionRecord | undefined> => {\n try {\n const record = decode(await readFile(path, \"utf8\"))\n return record._tag === \"Some\" ? record.value : undefined\n } catch {\n return undefined\n }\n }\n return {\n get: async (sessionId) => (SAFE_ID.test(sessionId) ? read(file(sessionId)) : undefined),\n save: (record) => {\n if (!SAFE_ID.test(record.sessionId)) return Promise.resolve()\n const id = record.sessionId\n const next = (queues.get(id) ?? Promise.resolve()).then(() => write(record), () => write(record))\n queues.set(id, next)\n const settle = () => {\n if (queues.get(id) === next) queues.delete(id)\n }\n next.then(settle, settle)\n return next\n },\n list: async () => {\n let names: Array<string>\n try {\n names = await readdir(dir)\n } catch {\n return []\n }\n const records = await Promise.all(names.filter((name) => name.endsWith(\".json\")).map((name) => read(join(dir, name))))\n return records\n .filter((record): record is SessionRecord => record !== undefined)\n .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))\n }\n }\n}\n"]}
|