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/bin.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* `capy-acp`: an ACP agent on stdio. stdout carries protocol messages only; logs go to stderr.
|
|
4
|
+
*/
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
import { Readable, Writable } from "node:stream";
|
|
7
|
+
import * as acp from "@agentclientprotocol/sdk";
|
|
8
|
+
import { Cause, Effect, Exit } from "effect";
|
|
9
|
+
import { makeAgent } from "./agent.js";
|
|
10
|
+
import { CapyClient, layer } from "./capy/client.js";
|
|
11
|
+
import { readConfig } from "./config.js";
|
|
12
|
+
import { runDoctor } from "./doctor.js";
|
|
13
|
+
import { readSecretFromTerminal, runSetup } from "./setup.js";
|
|
14
|
+
import { AGENT_NAME, AGENT_VERSION } from "./version.js";
|
|
15
|
+
const HELP = `${AGENT_NAME} ${AGENT_VERSION}: runs Capy coding-agent threads from an ACP client.
|
|
16
|
+
A community project. Not made, endorsed or supported by Capy.
|
|
17
|
+
|
|
18
|
+
Usage:
|
|
19
|
+
npx -y capy-acp Start the ACP agent on stdio. Your ACP client runs this.
|
|
20
|
+
npx -y capy-acp --setup Save a Capy API key on this machine.
|
|
21
|
+
npx -y capy-acp --doctor [folder] Check the setup for a folder (default: this folder).
|
|
22
|
+
npx -y capy-acp --version
|
|
23
|
+
npx -y capy-acp --help
|
|
24
|
+
|
|
25
|
+
Docs: https://github.com/yazcaleb/capy-acp#readme
|
|
26
|
+
`;
|
|
27
|
+
const args = process.argv.slice(2);
|
|
28
|
+
const [command, ...rest] = args;
|
|
29
|
+
if (command === "--version" || command === "-v") {
|
|
30
|
+
process.stdout.write(`${AGENT_NAME} ${AGENT_VERSION}\n`);
|
|
31
|
+
process.exit(0);
|
|
32
|
+
}
|
|
33
|
+
if (command === "--help" || command === "-h") {
|
|
34
|
+
process.stdout.write(HELP);
|
|
35
|
+
process.exit(0);
|
|
36
|
+
}
|
|
37
|
+
if (command === "--setup") {
|
|
38
|
+
const io = { readSecret: readSecretFromTerminal, write: (text) => void process.stdout.write(text), fetch };
|
|
39
|
+
const code = await runSetup(readConfig(), io).catch((error) => (process.stdout.write(`${String(error)}\n`), 1));
|
|
40
|
+
if (code === 0)
|
|
41
|
+
process.stdout.write("Next: run `npx -y capy-acp --doctor` in a project folder to check the rest of the setup.\n");
|
|
42
|
+
process.exit(code);
|
|
43
|
+
}
|
|
44
|
+
if (command === "--doctor") {
|
|
45
|
+
const config = readConfig();
|
|
46
|
+
const listProjects = async () => {
|
|
47
|
+
const exit = await Effect.runPromiseExit(Effect.gen(function* () {
|
|
48
|
+
return yield* (yield* CapyClient).listProjects;
|
|
49
|
+
}).pipe(Effect.provide(layer(config))));
|
|
50
|
+
if (Exit.isSuccess(exit))
|
|
51
|
+
return exit.value;
|
|
52
|
+
throw exit.cause.reasons.find(Cause.isFailReason)?.error ?? new Error(Cause.pretty(exit.cause));
|
|
53
|
+
};
|
|
54
|
+
const latestVersion = async () => {
|
|
55
|
+
const response = await fetch("https://registry.npmjs.org/capy-acp/latest", { signal: AbortSignal.timeout(3_000) });
|
|
56
|
+
const body = response.ok ? (await response.json()) : {};
|
|
57
|
+
return typeof body.version === "string" ? body.version : undefined;
|
|
58
|
+
};
|
|
59
|
+
const io = { write: (text) => void process.stdout.write(text), listProjects, nodeVersion: process.version, latestVersion };
|
|
60
|
+
process.exit(await runDoctor(config, resolve(rest[0] ?? "."), io));
|
|
61
|
+
}
|
|
62
|
+
if (command !== undefined) {
|
|
63
|
+
process.stderr.write(`Unknown option: ${command}\n\n${HELP}`);
|
|
64
|
+
process.exit(2);
|
|
65
|
+
}
|
|
66
|
+
// A person who runs the command in a terminal wants to know what it is. An ACP client pipes stdin.
|
|
67
|
+
if (process.stdin.isTTY) {
|
|
68
|
+
process.stderr.write(`${HELP}\nThis command is an ACP agent: add it to your ACP client. It is waiting for ACP messages on stdin; press Ctrl+C to stop.\n`);
|
|
69
|
+
}
|
|
70
|
+
const { app, dispose } = makeAgent(readConfig());
|
|
71
|
+
const connection = app.connect(acp.ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin)));
|
|
72
|
+
await connection.closed;
|
|
73
|
+
await dispose();
|
|
74
|
+
//# sourceMappingURL=bin.js.map
|
package/dist/bin.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA;;GAEG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,OAAO,EAAE,QAAQ,EAA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,CACd,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAA+B,EAC5D,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAA+B,CAC5D,CACF,CAAA;AACD,MAAM,UAAU,CAAC,MAAM,CAAA;AACvB,MAAM,OAAO,EAAE,CAAA","sourcesContent":["#!/usr/bin/env node\n/**\n * `capy-acp`: an ACP agent on stdio. stdout carries protocol messages only; logs go to stderr.\n */\nimport { resolve } from \"node:path\"\nimport { Readable, Writable } from \"node:stream\"\nimport * as acp from \"@agentclientprotocol/sdk\"\nimport { Cause, Effect, Exit } from \"effect\"\nimport { makeAgent } from \"./agent.js\"\nimport { CapyClient, layer } from \"./capy/client.js\"\nimport { readConfig } from \"./config.js\"\nimport { runDoctor } from \"./doctor.js\"\nimport { readSecretFromTerminal, runSetup } from \"./setup.js\"\nimport { AGENT_NAME, AGENT_VERSION } from \"./version.js\"\n\nconst HELP = `${AGENT_NAME} ${AGENT_VERSION}: runs Capy coding-agent threads from an ACP client.\nA community project. Not made, endorsed or supported by Capy.\n\nUsage:\n npx -y capy-acp Start the ACP agent on stdio. Your ACP client runs this.\n npx -y capy-acp --setup Save a Capy API key on this machine.\n npx -y capy-acp --doctor [folder] Check the setup for a folder (default: this folder).\n npx -y capy-acp --version\n npx -y capy-acp --help\n\nDocs: https://github.com/yazcaleb/capy-acp#readme\n`\n\nconst args = process.argv.slice(2)\nconst [command, ...rest] = args\n\nif (command === \"--version\" || command === \"-v\") {\n process.stdout.write(`${AGENT_NAME} ${AGENT_VERSION}\\n`)\n process.exit(0)\n}\n\nif (command === \"--help\" || command === \"-h\") {\n process.stdout.write(HELP)\n process.exit(0)\n}\n\nif (command === \"--setup\") {\n const io = { readSecret: readSecretFromTerminal, write: (text: string) => void process.stdout.write(text), fetch }\n const code = await runSetup(readConfig(), io).catch((error: unknown) => (process.stdout.write(`${String(error)}\\n`), 1))\n if (code === 0) process.stdout.write(\"Next: run `npx -y capy-acp --doctor` in a project folder to check the rest of the setup.\\n\")\n process.exit(code)\n}\n\nif (command === \"--doctor\") {\n const config = readConfig()\n const listProjects = async () => {\n const exit = await Effect.runPromiseExit(\n Effect.gen(function*() {\n return yield* (yield* CapyClient).listProjects\n }).pipe(Effect.provide(layer(config)))\n )\n if (Exit.isSuccess(exit)) return exit.value\n throw exit.cause.reasons.find(Cause.isFailReason)?.error ?? new Error(Cause.pretty(exit.cause))\n }\n const latestVersion = async () => {\n const response = await fetch(\"https://registry.npmjs.org/capy-acp/latest\", { signal: AbortSignal.timeout(3_000) })\n const body = response.ok ? ((await response.json()) as { version?: unknown }) : {}\n return typeof body.version === \"string\" ? body.version : undefined\n }\n const io = { write: (text: string) => void process.stdout.write(text), listProjects, nodeVersion: process.version, latestVersion }\n process.exit(await runDoctor(config, resolve(rest[0] ?? \".\"), io))\n}\n\nif (command !== undefined) {\n process.stderr.write(`Unknown option: ${command}\\n\\n${HELP}`)\n process.exit(2)\n}\n\n// A person who runs the command in a terminal wants to know what it is. An ACP client pipes stdin.\nif (process.stdin.isTTY) {\n process.stderr.write(`${HELP}\\nThis command is an ACP agent: add it to your ACP client. It is waiting for ACP messages on stdin; press Ctrl+C to stop.\\n`)\n}\n\nconst { app, dispose } = makeAgent(readConfig())\nconst connection = app.connect(\n acp.ndJsonStream(\n Writable.toWeb(process.stdout) as WritableStream<Uint8Array>,\n Readable.toWeb(process.stdin) as ReadableStream<Uint8Array>\n )\n)\nawait connection.closed\nawait dispose()\n"]}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed Capy API client (https://docs.capy.ai/api-reference/overview).
|
|
3
|
+
*
|
|
4
|
+
* Every mutating call this adapter makes is idempotent: creates carry a `requestId` and messages
|
|
5
|
+
* a `clientKey`. So all calls retry on rate limits (honoring `retry-after`), on 502/503/504, and on
|
|
6
|
+
* transport failures.
|
|
7
|
+
*/
|
|
8
|
+
import { readFile } from "node:fs/promises";
|
|
9
|
+
import { Context, Data, Duration, Effect, Layer, Schema, Stream } from "effect";
|
|
10
|
+
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
|
|
11
|
+
import { makeSseParser } from "../sse.js";
|
|
12
|
+
import { decodeEvent, decodeMessage, ThreadStatus } from "./events.js";
|
|
13
|
+
/** A tagged JSON error from the API, such as `capy/RateLimited` or `ModelSelection.Rejected`. */
|
|
14
|
+
export class CapyApiError extends Data.TaggedError("CapyApiError") {
|
|
15
|
+
}
|
|
16
|
+
export class CapyTransportError extends Data.TaggedError("CapyTransportError") {
|
|
17
|
+
}
|
|
18
|
+
/** Something only the user can fix, such as a missing API key. Never retried. */
|
|
19
|
+
export class CapyConfigError extends Data.TaggedError("CapyConfigError") {
|
|
20
|
+
}
|
|
21
|
+
export const isCapyError = (error) => error instanceof CapyApiError || error instanceof CapyTransportError || error instanceof CapyConfigError;
|
|
22
|
+
export const Model = Schema.Struct({
|
|
23
|
+
id: Schema.String,
|
|
24
|
+
name: Schema.String,
|
|
25
|
+
billing: Schema.optionalKey(Schema.String),
|
|
26
|
+
route: Schema.optionalKey(Schema.String),
|
|
27
|
+
reasoningModes: Schema.optionalKey(Schema.Array(Schema.String))
|
|
28
|
+
});
|
|
29
|
+
const Project = Schema.Struct({
|
|
30
|
+
id: Schema.String,
|
|
31
|
+
name: Schema.String,
|
|
32
|
+
repos: Schema.Array(Schema.Struct({ repoFullName: Schema.String }))
|
|
33
|
+
});
|
|
34
|
+
const Page = (item) => Schema.Struct({ items: Schema.Array(item), cursor: Schema.optionalKey(Schema.NullOr(Schema.String)) });
|
|
35
|
+
/** Credits are thousandths of a dollar (see `formatCredits`). */
|
|
36
|
+
const Usage = Schema.Struct({
|
|
37
|
+
totalCredits: Schema.Number,
|
|
38
|
+
llmCredits: Schema.optionalKey(Schema.Number),
|
|
39
|
+
imageCredits: Schema.optionalKey(Schema.Number),
|
|
40
|
+
vmCredits: Schema.optionalKey(Schema.Number)
|
|
41
|
+
});
|
|
42
|
+
export const Thread = Schema.Struct({ id: Schema.String, status: ThreadStatus, usage: Schema.optionalKey(Usage) });
|
|
43
|
+
const Receipt = Schema.Struct({ id: Schema.String });
|
|
44
|
+
const UploadTargets = Schema.Struct({
|
|
45
|
+
targets: Schema.Array(Schema.Struct({ fileId: Schema.String, url: Schema.String }))
|
|
46
|
+
});
|
|
47
|
+
// Items are decoded one by one (`decodeMessage`), so an entry this adapter can't read is skipped.
|
|
48
|
+
const MessagePage = Schema.Struct({
|
|
49
|
+
items: Schema.Array(Schema.Unknown),
|
|
50
|
+
cursor: Schema.optionalKey(Schema.NullOr(Schema.String))
|
|
51
|
+
});
|
|
52
|
+
const Download = Schema.Struct({ url: Schema.String, expiresAt: Schema.optionalKey(Schema.String) });
|
|
53
|
+
export class CapyClient extends Context.Service()("capy-acp/CapyClient") {
|
|
54
|
+
}
|
|
55
|
+
const RETRYABLE_STATUS = new Set([429, 502, 503, 504]);
|
|
56
|
+
const MAX_ATTEMPTS = 4;
|
|
57
|
+
/** A `retry-after` longer than this is not honored: the call fails instead of hanging the prompt. */
|
|
58
|
+
const MAX_RETRY_AFTER_MS = 60_000;
|
|
59
|
+
const retryDelay = (error, attempt) => {
|
|
60
|
+
if (attempt >= MAX_ATTEMPTS)
|
|
61
|
+
return undefined;
|
|
62
|
+
if (error._tag === "CapyTransportError")
|
|
63
|
+
return 500 * 2 ** attempt;
|
|
64
|
+
if (error._tag === "CapyConfigError" || !RETRYABLE_STATUS.has(error.status))
|
|
65
|
+
return undefined;
|
|
66
|
+
const delay = error.retryAfterMs ?? 1000 * 2 ** attempt;
|
|
67
|
+
return delay > MAX_RETRY_AFTER_MS ? undefined : delay;
|
|
68
|
+
};
|
|
69
|
+
/** Network trouble, rate limits and server errors: worth trying again later, unlike a rejected request. */
|
|
70
|
+
export const isTransient = (error) => error._tag === "CapyTransportError" || (error._tag === "CapyApiError" && (error.status === 429 || error.status >= 500));
|
|
71
|
+
/** One line for the user: Capy's own tag and message when it sent them. */
|
|
72
|
+
export const describeError = (error) => error._tag === "CapyApiError" ? `Capy ${error.tag} (${error.status}): ${error.message}` : error.message;
|
|
73
|
+
export const withRetry = (effect, attempt = 1) => effect.pipe(Effect.catch((error) => {
|
|
74
|
+
const delay = retryDelay(error, attempt);
|
|
75
|
+
return delay === undefined
|
|
76
|
+
? Effect.fail(error)
|
|
77
|
+
: Effect.sleep(Duration.millis(delay)).pipe(Effect.andThen(withRetry(effect, attempt + 1)));
|
|
78
|
+
}));
|
|
79
|
+
/** Builds a `CapyApiError` from a non-2xx response, reading Capy's `_tag`/`message` and `retry-after`. */
|
|
80
|
+
const apiError = (response) => response.json.pipe(Effect.orElseSucceed(() => ({})), Effect.flatMap((body) => {
|
|
81
|
+
const record = (typeof body === "object" && body !== null ? body : {});
|
|
82
|
+
const header = Number(response.headers["retry-after"]);
|
|
83
|
+
const bodySeconds = typeof record.retryAfterSeconds === "number" ? record.retryAfterSeconds : undefined;
|
|
84
|
+
const seconds = Number.isFinite(header) ? header : bodySeconds;
|
|
85
|
+
return Effect.fail(new CapyApiError({
|
|
86
|
+
status: response.status,
|
|
87
|
+
tag: typeof record._tag === "string" ? record._tag : `http/${response.status}`,
|
|
88
|
+
message: typeof record.message === "string" ? record.message : `Capy API answered ${response.status}`,
|
|
89
|
+
retryAfterMs: seconds === undefined ? undefined : seconds * 1000
|
|
90
|
+
}));
|
|
91
|
+
}));
|
|
92
|
+
/**
|
|
93
|
+
* Reads the API key for each request, so adding or rotating the key needs no restart. The read is
|
|
94
|
+
* a small local file (or the environment), far cheaper than the request it authorizes.
|
|
95
|
+
*/
|
|
96
|
+
const readApiKey = (config) => {
|
|
97
|
+
const fromEnv = process.env.CAPY_API_KEY?.trim();
|
|
98
|
+
if (fromEnv)
|
|
99
|
+
return Effect.succeed(fromEnv);
|
|
100
|
+
return Effect.tryPromise({
|
|
101
|
+
try: async () => (await readFile(config.apiKeyFile, "utf8")).trim(),
|
|
102
|
+
catch: () => new CapyConfigError({
|
|
103
|
+
message: `No Capy API key. Run \`npx -y capy-acp --setup\` in a terminal, or set CAPY_API_KEY, or put the key in ${config.apiKeyFile} (mode 0600).`
|
|
104
|
+
})
|
|
105
|
+
}).pipe(Effect.filterOrFail((key) => key.length > 0, () => new CapyConfigError({ message: `The Capy API key file ${config.apiKeyFile} is empty.` })));
|
|
106
|
+
};
|
|
107
|
+
export const make = (config) => Effect.gen(function* () {
|
|
108
|
+
const base = yield* HttpClient.HttpClient;
|
|
109
|
+
const http = base.pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl(config.apiUrl)));
|
|
110
|
+
const authorize = (request) => readApiKey(config).pipe(Effect.map((key) => request.pipe(HttpClientRequest.bearerToken(key))));
|
|
111
|
+
const send = (request) => authorize(request).pipe(Effect.flatMap((authorized) => http.execute(authorized).pipe(Effect.mapError((cause) => new CapyTransportError({ message: `Capy API request failed: ${cause.message}`, cause })))), Effect.flatMap((response) => (response.status >= 200 && response.status < 300 ? Effect.succeed(response) : apiError(response))));
|
|
112
|
+
const json = (schema, request) => withRetry(send(request.pipe(HttpClientRequest.acceptJson)).pipe(Effect.flatMap((response) => response.json), Effect.flatMap((body) => Schema.decodeUnknownEffect(schema)(body)), Effect.mapError((error) => error instanceof CapyApiError || error instanceof CapyTransportError || error instanceof CapyConfigError
|
|
113
|
+
? error
|
|
114
|
+
: new CapyTransportError({ message: `Unexpected Capy API response: ${String(error)}`, cause: error })), Effect.timeout(Duration.seconds(30)), Effect.catchTag("TimeoutError", () => Effect.fail(new CapyTransportError({ message: "Capy API request timed out" })))));
|
|
115
|
+
const listProjects = Effect.gen(function* () {
|
|
116
|
+
const projects = [];
|
|
117
|
+
let cursor = undefined;
|
|
118
|
+
do {
|
|
119
|
+
const query = cursor ? `?cursor=${encodeURIComponent(cursor)}` : "";
|
|
120
|
+
const page = yield* json(Page(Project), HttpClientRequest.get(`/projects${query}`));
|
|
121
|
+
projects.push(...page.items);
|
|
122
|
+
cursor = page.cursor;
|
|
123
|
+
} while (cursor);
|
|
124
|
+
return projects;
|
|
125
|
+
});
|
|
126
|
+
const listMessages = (threadId) => Effect.gen(function* () {
|
|
127
|
+
const messages = [];
|
|
128
|
+
let after = undefined;
|
|
129
|
+
for (;;) {
|
|
130
|
+
const query = after ? `?after=${encodeURIComponent(after)}` : "";
|
|
131
|
+
const page = yield* json(MessagePage, HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}/messages${query}`));
|
|
132
|
+
for (const item of page.items) {
|
|
133
|
+
const message = decodeMessage(item);
|
|
134
|
+
if (message._tag === "Some")
|
|
135
|
+
messages.push(message.value);
|
|
136
|
+
}
|
|
137
|
+
// A page can be empty; an unchanged cursor means unsettled entries block paging for now.
|
|
138
|
+
if (!page.cursor || page.cursor === after)
|
|
139
|
+
return messages;
|
|
140
|
+
after = page.cursor;
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
// Presigned PUT: exact Content-Type and Content-Length, and no Authorization header.
|
|
144
|
+
const putBytes = (url, file) => withRetry(base.execute(HttpClientRequest.put(url).pipe(HttpClientRequest.bodyUint8Array(file.bytes, file.mediaType))).pipe(Effect.mapError((cause) => new CapyTransportError({ message: `Uploading ${file.name} failed: ${cause.message}`, cause })), Effect.flatMap((response) => response.status >= 200 && response.status < 300
|
|
145
|
+
? Effect.void
|
|
146
|
+
: Effect.fail(new CapyApiError({ status: response.status, tag: `upload/${response.status}`, message: `Uploading ${file.name} failed (${response.status})`, retryAfterMs: undefined })))));
|
|
147
|
+
const uploadFiles = (files) => Effect.gen(function* () {
|
|
148
|
+
if (files.length === 0)
|
|
149
|
+
return [];
|
|
150
|
+
const { targets } = yield* json(UploadTargets, HttpClientRequest.post("/files").pipe(HttpClientRequest.bodyJsonUnsafe({ files: files.map((f) => ({ name: f.name, mediaType: f.mediaType, sizeBytes: f.bytes.byteLength })) })));
|
|
151
|
+
if (targets.length !== files.length) {
|
|
152
|
+
return yield* Effect.fail(new CapyTransportError({ message: `Capy returned ${targets.length} upload targets for ${files.length} files` }));
|
|
153
|
+
}
|
|
154
|
+
yield* Effect.forEach(files, (file, i) => putBytes(targets[i].url, file), { concurrency: 4, discard: true });
|
|
155
|
+
return files.map((file, i) => ({ fileId: targets[i].fileId, name: file.name }));
|
|
156
|
+
});
|
|
157
|
+
return CapyClient.of({
|
|
158
|
+
listModels: json(Page(Model), HttpClientRequest.get("/models")).pipe(Effect.map((page) => page.items)),
|
|
159
|
+
listProjects,
|
|
160
|
+
createThread: (body) => json(Thread, HttpClientRequest.post("/threads").pipe(HttpClientRequest.bodyJsonUnsafe(body))),
|
|
161
|
+
sendMessage: (threadId, body) => json(Receipt, HttpClientRequest.post(`/threads/${encodeURIComponent(threadId)}/message`).pipe(HttpClientRequest.bodyJsonUnsafe(body))),
|
|
162
|
+
interrupt: (threadId) => withRetry(send(HttpClientRequest.post(`/threads/${encodeURIComponent(threadId)}/interrupt`))).pipe(Effect.asVoid),
|
|
163
|
+
getThread: (threadId) => json(Thread, HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}`)),
|
|
164
|
+
uploadFiles,
|
|
165
|
+
listMessages,
|
|
166
|
+
attachmentUrl: (threadId, fileId) => json(Download, HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}/attachments/${encodeURIComponent(fileId)}/download`)).pipe(Effect.map((download) => download.url)),
|
|
167
|
+
stream: (threadId, { cursor, untilRun }) => Stream.unwrap(withRetry(send(HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}/stream${untilRun ? "?until=run" : ""}`).pipe(HttpClientRequest.setHeader("accept", "text/event-stream"), cursor === undefined ? (request) => request : HttpClientRequest.setHeader("last-event-id", cursor)))).pipe(Effect.map((response) => response.stream.pipe(Stream.mapError((cause) => new CapyTransportError({ message: `Capy stream dropped: ${cause.message}`, cause })), Stream.decodeText(), Stream.mapAccum(makeSseParser, (parser, text) => [parser, parser.push(text)], {
|
|
168
|
+
onHalt: (parser) => parser.end()
|
|
169
|
+
}), Stream.map(decodeEvent)))))
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
/** Never fails to build: a missing API key surfaces on the first request, where the user sees it. */
|
|
173
|
+
export const layer = (config) => Layer.effect(CapyClient, make(config)).pipe(Layer.provide(FetchHttpClient.layer));
|
|
174
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/capy/client.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAC3C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC/E,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,iBAAiB,EAA2B,MAAM,aAAa,CAAA;AAErG,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AACzC,OAAO,EAAkB,WAAW,EAAE,aAAa,EAAgB,YAAY,EAAE,MAAM,aAAa,CAAA;AAEpG,iGAAiG;AACjG,MAAM,OAAO,YAAa,SAAQ,IAAI,CAAC,WAAW,CAAC,cAAc,CAK/D;CAAG;AAEL,MAAM,OAAO,kBAAmB,SAAQ,IAAI,CAAC,WAAW,CAAC,oBAAoB,CAG3E;CAAG;AAEL,iFAAiF;AACjF,MAAM,OAAO,eAAgB,SAAQ,IAAI,CAAC,WAAW,CAAC,iBAAiB,CAErE;CAAG;AAIL,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,KAAc,EAAsB,EAAE,CAChE,KAAK,YAAY,YAAY,IAAI,KAAK,YAAY,kBAAkB,IAAI,KAAK,YAAY,eAAe,CAAA;AAE1G,MAAM,CAAC,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC;IACjC,EAAE,EAAE,MAAM,CAAC,MAAM;IACjB,IAAI,EAAE,MAAM,CAAC,MAAM;IACnB,OAAO,EAAE,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC;IAC1C,KAAK,EAAE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E,EAAE,CAAC,IAAI,kBAAkB,CAAC,EAAE,OAAO,EAAE,wBAAwB,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC,EAC/G,MAAM,CAAC,UAAU,EAAE,EACnB,MAAM,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,MAAM,EAAE,IAAY,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAU,EAAE;YAC7F,MAAM,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,EAAE;SACjC,CAAC,EACF,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,CACxB,CACF,CACF,CACF;KACJ,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA;AAEJ,qGAAqG;AACrG,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,MAAqB,EAA2B,EAAE,CACtE,KAAK,CAAC,MAAM,CAAC,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAA","sourcesContent":["/**\n * Typed Capy API client (https://docs.capy.ai/api-reference/overview).\n *\n * Every mutating call this adapter makes is idempotent: creates carry a `requestId` and messages\n * a `clientKey`. So all calls retry on rate limits (honoring `retry-after`), on 502/503/504, and on\n * transport failures.\n */\nimport { readFile } from \"node:fs/promises\"\nimport { Context, Data, Duration, Effect, Layer, Schema, Stream } from \"effect\"\nimport { FetchHttpClient, HttpClient, HttpClientRequest, type HttpClientResponse } from \"effect/http\"\nimport type { AdapterConfig } from \"../config.js\"\nimport { makeSseParser } from \"../sse.js\"\nimport { type CapyEvent, decodeEvent, decodeMessage, type Message, ThreadStatus } from \"./events.js\"\n\n/** A tagged JSON error from the API, such as `capy/RateLimited` or `ModelSelection.Rejected`. */\nexport class CapyApiError extends Data.TaggedError(\"CapyApiError\")<{\n readonly status: number\n readonly tag: string\n readonly message: string\n readonly retryAfterMs: number | undefined\n}> {}\n\nexport class CapyTransportError extends Data.TaggedError(\"CapyTransportError\")<{\n readonly message: string\n readonly cause?: unknown\n}> {}\n\n/** Something only the user can fix, such as a missing API key. Never retried. */\nexport class CapyConfigError extends Data.TaggedError(\"CapyConfigError\")<{\n readonly message: string\n}> {}\n\nexport type CapyError = CapyApiError | CapyTransportError | CapyConfigError\n\nexport const isCapyError = (error: unknown): error is CapyError =>\n error instanceof CapyApiError || error instanceof CapyTransportError || error instanceof CapyConfigError\n\nexport const Model = Schema.Struct({\n id: Schema.String,\n name: Schema.String,\n billing: Schema.optionalKey(Schema.String),\n route: Schema.optionalKey(Schema.String),\n reasoningModes: Schema.optionalKey(Schema.Array(Schema.String))\n})\nexport type Model = typeof Model.Type\n\nconst Project = Schema.Struct({\n id: Schema.String,\n name: Schema.String,\n repos: Schema.Array(Schema.Struct({ repoFullName: Schema.String }))\n})\n\nconst Page = <S extends Schema.Top>(item: S) =>\n Schema.Struct({ items: Schema.Array(item), cursor: Schema.optionalKey(Schema.NullOr(Schema.String)) })\n\n/** Credits are thousandths of a dollar (see `formatCredits`). */\nconst Usage = Schema.Struct({\n totalCredits: Schema.Number,\n llmCredits: Schema.optionalKey(Schema.Number),\n imageCredits: Schema.optionalKey(Schema.Number),\n vmCredits: Schema.optionalKey(Schema.Number)\n})\n\nexport const Thread = Schema.Struct({ id: Schema.String, status: ThreadStatus, usage: Schema.optionalKey(Usage) })\nexport type Thread = typeof Thread.Type\n\nconst Receipt = Schema.Struct({ id: Schema.String })\n\nconst UploadTargets = Schema.Struct({\n targets: Schema.Array(Schema.Struct({ fileId: Schema.String, url: Schema.String }))\n})\n\n// Items are decoded one by one (`decodeMessage`), so an entry this adapter can't read is skipped.\nconst MessagePage = Schema.Struct({\n items: Schema.Array(Schema.Unknown),\n cursor: Schema.optionalKey(Schema.NullOr(Schema.String))\n})\n\nconst Download = Schema.Struct({ url: Schema.String, expiresAt: Schema.optionalKey(Schema.String) })\n\n/** A file to attach to a message: uploaded through `POST /files`, then referenced by id. */\nexport interface FileUpload {\n readonly name: string\n readonly mediaType: string\n readonly bytes: Uint8Array\n}\n\nexport interface MessageFile {\n readonly fileId: string\n readonly name: string\n}\n\nexport interface ModelSelection {\n readonly modelId: string\n readonly reasoningMode?: string\n}\n\nexport interface CreateThread {\n readonly requestId: string\n readonly projectId: string\n readonly title?: string\n readonly message: string\n readonly model: ModelSelection\n readonly device: {\n readonly deviceId: string\n readonly workspace: { readonly kind: \"linked\"; readonly root: string } | { readonly kind: \"worktree\" }\n }\n}\n\nexport interface SendMessage {\n readonly text: string\n readonly clientKey: string\n readonly model?: ModelSelection\n readonly delivery?: \"interrupt\" | \"steer\" | \"queue\"\n readonly files?: ReadonlyArray<MessageFile>\n}\n\nexport class CapyClient extends Context.Service<\n CapyClient,\n {\n readonly listModels: Effect.Effect<ReadonlyArray<Model>, CapyError>\n readonly listProjects: Effect.Effect<ReadonlyArray<typeof Project.Type>, CapyError>\n readonly createThread: (body: CreateThread) => Effect.Effect<Thread, CapyError>\n readonly sendMessage: (threadId: string, body: SendMessage) => Effect.Effect<{ readonly id: string }, CapyError>\n readonly interrupt: (threadId: string) => Effect.Effect<void, CapyError>\n readonly getThread: (threadId: string) => Effect.Effect<Thread, CapyError>\n /** Uploads files for a message, in order. The bytes go straight to storage through presigned URLs. */\n readonly uploadFiles: (files: ReadonlyArray<FileUpload>) => Effect.Effect<ReadonlyArray<MessageFile>, CapyError>\n /** The whole committed transcript, oldest first. */\n readonly listMessages: (threadId: string) => Effect.Effect<ReadonlyArray<Message>, CapyError>\n /** A short-lived URL for a file attached to the thread's transcript. */\n readonly attachmentUrl: (threadId: string, fileId: string) => Effect.Effect<string, CapyError>\n /** Thread events after `cursor`. With `untilRun`, the server closes the stream when the run ends. */\n readonly stream: (\n threadId: string,\n options: { readonly cursor: string | undefined; readonly untilRun: boolean }\n ) => Stream.Stream<CapyEvent, CapyError>\n }\n>()(\"capy-acp/CapyClient\") {}\n\nconst RETRYABLE_STATUS = new Set([429, 502, 503, 504])\nconst MAX_ATTEMPTS = 4\n/** A `retry-after` longer than this is not honored: the call fails instead of hanging the prompt. */\nconst MAX_RETRY_AFTER_MS = 60_000\n\nconst retryDelay = (error: CapyError, attempt: number): number | undefined => {\n if (attempt >= MAX_ATTEMPTS) return undefined\n if (error._tag === \"CapyTransportError\") return 500 * 2 ** attempt\n if (error._tag === \"CapyConfigError\" || !RETRYABLE_STATUS.has(error.status)) return undefined\n const delay = error.retryAfterMs ?? 1000 * 2 ** attempt\n return delay > MAX_RETRY_AFTER_MS ? undefined : delay\n}\n\n/** Network trouble, rate limits and server errors: worth trying again later, unlike a rejected request. */\nexport const isTransient = (error: CapyError): boolean =>\n error._tag === \"CapyTransportError\" || (error._tag === \"CapyApiError\" && (error.status === 429 || error.status >= 500))\n\n/** One line for the user: Capy's own tag and message when it sent them. */\nexport const describeError = (error: CapyError): string =>\n error._tag === \"CapyApiError\" ? `Capy ${error.tag} (${error.status}): ${error.message}` : error.message\n\nexport const withRetry = <A>(effect: Effect.Effect<A, CapyError>, attempt = 1): Effect.Effect<A, CapyError> =>\n effect.pipe(\n Effect.catch((error: CapyError) => {\n const delay = retryDelay(error, attempt)\n return delay === undefined\n ? Effect.fail(error)\n : Effect.sleep(Duration.millis(delay)).pipe(Effect.andThen(withRetry(effect, attempt + 1)))\n })\n )\n\n/** Builds a `CapyApiError` from a non-2xx response, reading Capy's `_tag`/`message` and `retry-after`. */\nconst apiError = (response: HttpClientResponse.HttpClientResponse): Effect.Effect<never, CapyError> =>\n response.json.pipe(\n Effect.orElseSucceed(() => ({})),\n Effect.flatMap((body) => {\n const record = (typeof body === \"object\" && body !== null ? body : {}) as Record<string, unknown>\n const header = Number(response.headers[\"retry-after\"])\n const bodySeconds = typeof record.retryAfterSeconds === \"number\" ? record.retryAfterSeconds : undefined\n const seconds = Number.isFinite(header) ? header : bodySeconds\n return Effect.fail(\n new CapyApiError({\n status: response.status,\n tag: typeof record._tag === \"string\" ? record._tag : `http/${response.status}`,\n message: typeof record.message === \"string\" ? record.message : `Capy API answered ${response.status}`,\n retryAfterMs: seconds === undefined ? undefined : seconds * 1000\n })\n )\n })\n )\n\n/**\n * Reads the API key for each request, so adding or rotating the key needs no restart. The read is\n * a small local file (or the environment), far cheaper than the request it authorizes.\n */\nconst readApiKey = (config: AdapterConfig): Effect.Effect<string, CapyConfigError> => {\n const fromEnv = process.env.CAPY_API_KEY?.trim()\n if (fromEnv) return Effect.succeed(fromEnv)\n return Effect.tryPromise({\n try: async () => (await readFile(config.apiKeyFile, \"utf8\")).trim(),\n catch: () =>\n new CapyConfigError({\n message: `No Capy API key. Run \\`npx -y capy-acp --setup\\` in a terminal, or set CAPY_API_KEY, or put the key in ${config.apiKeyFile} (mode 0600).`\n })\n }).pipe(\n Effect.filterOrFail(\n (key) => key.length > 0,\n () => new CapyConfigError({ message: `The Capy API key file ${config.apiKeyFile} is empty.` })\n )\n )\n}\n\nexport const make = (config: AdapterConfig) =>\n Effect.gen(function*() {\n const base = yield* HttpClient.HttpClient\n const http = base.pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl(config.apiUrl)))\n const authorize = (request: HttpClientRequest.HttpClientRequest) =>\n readApiKey(config).pipe(Effect.map((key) => request.pipe(HttpClientRequest.bearerToken(key))))\n\n const send = (request: HttpClientRequest.HttpClientRequest) =>\n authorize(request).pipe(\n Effect.flatMap((authorized) =>\n http.execute(authorized).pipe(\n Effect.mapError((cause) => new CapyTransportError({ message: `Capy API request failed: ${cause.message}`, cause }))\n )\n ),\n Effect.flatMap((response) => (response.status >= 200 && response.status < 300 ? Effect.succeed(response) : apiError(response)))\n )\n\n const json = <S extends Schema.Top & Schema.Decoder<unknown>>(\n schema: S,\n request: HttpClientRequest.HttpClientRequest\n ): Effect.Effect<S[\"Type\"], CapyError> =>\n withRetry(\n send(request.pipe(HttpClientRequest.acceptJson)).pipe(\n Effect.flatMap((response) => response.json),\n Effect.flatMap((body) => Schema.decodeUnknownEffect(schema)(body)),\n Effect.mapError((error) =>\n error instanceof CapyApiError || error instanceof CapyTransportError || error instanceof CapyConfigError\n ? error\n : new CapyTransportError({ message: `Unexpected Capy API response: ${String(error)}`, cause: error })\n ),\n Effect.timeout(Duration.seconds(30)),\n Effect.catchTag(\"TimeoutError\", () => Effect.fail(new CapyTransportError({ message: \"Capy API request timed out\" })))\n )\n )\n\n const listProjects = Effect.gen(function*() {\n const projects: Array<typeof Project.Type> = []\n let cursor: string | null | undefined = undefined\n do {\n const query: string = cursor ? `?cursor=${encodeURIComponent(cursor)}` : \"\"\n const page: { readonly items: ReadonlyArray<typeof Project.Type>; readonly cursor?: string | null } = yield* json(Page(Project), HttpClientRequest.get(`/projects${query}`))\n projects.push(...page.items)\n cursor = page.cursor\n } while (cursor)\n return projects\n })\n\n const listMessages = (threadId: string) =>\n Effect.gen(function*() {\n const messages: Array<Message> = []\n let after: string | null | undefined = undefined\n for (;;) {\n const query: string = after ? `?after=${encodeURIComponent(after)}` : \"\"\n const page: typeof MessagePage.Type = yield* json(MessagePage, HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}/messages${query}`))\n for (const item of page.items) {\n const message = decodeMessage(item)\n if (message._tag === \"Some\") messages.push(message.value)\n }\n // A page can be empty; an unchanged cursor means unsettled entries block paging for now.\n if (!page.cursor || page.cursor === after) return messages\n after = page.cursor\n }\n })\n\n // Presigned PUT: exact Content-Type and Content-Length, and no Authorization header.\n const putBytes = (url: string, file: FileUpload) =>\n withRetry(\n base.execute(HttpClientRequest.put(url).pipe(HttpClientRequest.bodyUint8Array(file.bytes, file.mediaType))).pipe(\n Effect.mapError((cause) => new CapyTransportError({ message: `Uploading ${file.name} failed: ${cause.message}`, cause })),\n Effect.flatMap((response) =>\n response.status >= 200 && response.status < 300\n ? Effect.void\n : Effect.fail(\n new CapyApiError({ status: response.status, tag: `upload/${response.status}`, message: `Uploading ${file.name} failed (${response.status})`, retryAfterMs: undefined })\n )\n )\n )\n )\n\n const uploadFiles = (files: ReadonlyArray<FileUpload>) =>\n Effect.gen(function*() {\n if (files.length === 0) return []\n const { targets } = yield* json(\n UploadTargets,\n HttpClientRequest.post(\"/files\").pipe(\n HttpClientRequest.bodyJsonUnsafe({ files: files.map((f) => ({ name: f.name, mediaType: f.mediaType, sizeBytes: f.bytes.byteLength })) })\n )\n )\n if (targets.length !== files.length) {\n return yield* Effect.fail(new CapyTransportError({ message: `Capy returned ${targets.length} upload targets for ${files.length} files` }))\n }\n yield* Effect.forEach(files, (file, i) => putBytes(targets[i]!.url, file), { concurrency: 4, discard: true })\n return files.map((file, i) => ({ fileId: targets[i]!.fileId, name: file.name }))\n })\n\n return CapyClient.of({\n listModels: json(Page(Model), HttpClientRequest.get(\"/models\")).pipe(Effect.map((page) => page.items)),\n listProjects,\n createThread: (body) => json(Thread, HttpClientRequest.post(\"/threads\").pipe(HttpClientRequest.bodyJsonUnsafe(body))),\n sendMessage: (threadId, body) =>\n json(\n Receipt,\n HttpClientRequest.post(`/threads/${encodeURIComponent(threadId)}/message`).pipe(HttpClientRequest.bodyJsonUnsafe(body))\n ),\n interrupt: (threadId) =>\n withRetry(send(HttpClientRequest.post(`/threads/${encodeURIComponent(threadId)}/interrupt`))).pipe(Effect.asVoid),\n getThread: (threadId) => json(Thread, HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}`)),\n uploadFiles,\n listMessages,\n attachmentUrl: (threadId, fileId) =>\n json(\n Download,\n HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}/attachments/${encodeURIComponent(fileId)}/download`)\n ).pipe(Effect.map((download) => download.url)),\n stream: (threadId, { cursor, untilRun }) =>\n Stream.unwrap(\n withRetry(\n send(\n HttpClientRequest.get(`/threads/${encodeURIComponent(threadId)}/stream${untilRun ? \"?until=run\" : \"\"}`).pipe(\n HttpClientRequest.setHeader(\"accept\", \"text/event-stream\"),\n cursor === undefined ? (request) => request : HttpClientRequest.setHeader(\"last-event-id\", cursor)\n )\n )\n ).pipe(\n Effect.map((response) =>\n response.stream.pipe(\n Stream.mapError((cause) => new CapyTransportError({ message: `Capy stream dropped: ${cause.message}`, cause })),\n Stream.decodeText(),\n Stream.mapAccum(makeSseParser, (parser, text: string) => [parser, parser.push(text)] as const, {\n onHalt: (parser) => parser.end()\n }),\n Stream.map(decodeEvent)\n )\n )\n )\n )\n })\n })\n\n/** Never fails to build: a missing API key surfaces on the first request, where the user sees it. */\nexport const layer = (config: AdapterConfig): Layer.Layer<CapyClient> =>\n Layer.effect(CapyClient, make(config)).pipe(Layer.provide(FetchHttpClient.layer))\n"]}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Capy thread-stream events (`GET /threads/{id}/stream`), decoded from SSE frames.
|
|
3
|
+
*
|
|
4
|
+
* Event names this adapter does not know decode to `Unknown`, as Capy's docs ask: the
|
|
5
|
+
* vocabulary grows over time. A known event whose payload fails to decode also becomes
|
|
6
|
+
* `Unknown`, so one malformed frame never kills a session.
|
|
7
|
+
*/
|
|
8
|
+
import { Option, Schema } from "effect";
|
|
9
|
+
export const ThreadStatus = Schema.Literals(["working", "waiting", "idle", "failed", "archived"]);
|
|
10
|
+
const nullable = (schema) => Schema.optionalKey(Schema.NullOr(schema));
|
|
11
|
+
// The message list sends `null` for absent fields (`clientKey: null`) where the stream omits them,
|
|
12
|
+
// and documents `durationMs` as a number or "Infinity". Only id and source are strict.
|
|
13
|
+
const RawMessage = Schema.Struct({
|
|
14
|
+
id: Schema.String,
|
|
15
|
+
source: Schema.Literals(["user", "assistant", "tool"]),
|
|
16
|
+
text: nullable(Schema.String),
|
|
17
|
+
tool: nullable(Schema.String),
|
|
18
|
+
callId: nullable(Schema.String),
|
|
19
|
+
calls: nullable(Schema.Array(Schema.Struct({ tool: Schema.String, durationMs: nullable(Schema.Unknown) }))),
|
|
20
|
+
model: nullable(Schema.String),
|
|
21
|
+
clientKey: nullable(Schema.String),
|
|
22
|
+
createdAt: nullable(Schema.String),
|
|
23
|
+
attachments: nullable(Schema.Array(Schema.Unknown))
|
|
24
|
+
});
|
|
25
|
+
const present = (key, value) => (value === null || value === undefined ? {} : { [key]: value });
|
|
26
|
+
export const decodeMessage = (data) => Option.map(Schema.decodeUnknownOption(RawMessage)(data), (raw) => ({
|
|
27
|
+
id: raw.id,
|
|
28
|
+
source: raw.source,
|
|
29
|
+
...present("text", raw.text),
|
|
30
|
+
...present("tool", raw.tool),
|
|
31
|
+
...present("callId", raw.callId),
|
|
32
|
+
...present("calls", raw.calls?.map((call) => ({
|
|
33
|
+
tool: call.tool,
|
|
34
|
+
...(typeof call.durationMs === "number" && Number.isFinite(call.durationMs) ? { durationMs: call.durationMs } : {})
|
|
35
|
+
}))),
|
|
36
|
+
...present("model", raw.model),
|
|
37
|
+
...present("clientKey", raw.clientKey),
|
|
38
|
+
...present("createdAt", raw.createdAt),
|
|
39
|
+
...present("attachments", raw.attachments)
|
|
40
|
+
}));
|
|
41
|
+
const Attachment = Schema.Struct({
|
|
42
|
+
file: Schema.Struct({
|
|
43
|
+
fileId: Schema.String,
|
|
44
|
+
name: Schema.String,
|
|
45
|
+
mediaType: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
|
46
|
+
sizeBytes: Schema.optionalKey(Schema.Unknown),
|
|
47
|
+
sourcePath: Schema.optionalKey(Schema.NullOr(Schema.String))
|
|
48
|
+
}),
|
|
49
|
+
title: Schema.optionalKey(Schema.NullOr(Schema.String))
|
|
50
|
+
});
|
|
51
|
+
export const messageFiles = (message) => (message.attachments ?? []).flatMap((item) => Option.match(Schema.decodeUnknownOption(Attachment)(item), {
|
|
52
|
+
onNone: () => [],
|
|
53
|
+
onSome: ({ file, title }) => [{
|
|
54
|
+
fileId: file.fileId,
|
|
55
|
+
name: file.name,
|
|
56
|
+
mediaType: file.mediaType ?? undefined,
|
|
57
|
+
sizeBytes: typeof file.sizeBytes === "number" && Number.isFinite(file.sizeBytes) ? file.sizeBytes : undefined,
|
|
58
|
+
sourcePath: file.sourcePath ?? undefined,
|
|
59
|
+
title: title ?? undefined
|
|
60
|
+
}]
|
|
61
|
+
}));
|
|
62
|
+
const payloads = {
|
|
63
|
+
status: Schema.Struct({ status: ThreadStatus }),
|
|
64
|
+
run: Schema.Struct({ phase: Schema.Literals(["start", "end"]) }),
|
|
65
|
+
turn: Schema.Struct({
|
|
66
|
+
phase: Schema.Literals(["start", "end"]),
|
|
67
|
+
outcome: Schema.optionalKey(Schema.String)
|
|
68
|
+
}),
|
|
69
|
+
assistant: Schema.Struct({ callId: Schema.String, text: Schema.String }),
|
|
70
|
+
tool_call: Schema.Struct({ callId: Schema.String, name: Schema.String, text: Schema.optionalKey(Schema.String) }),
|
|
71
|
+
error: Schema.Struct({ code: Schema.String, message: Schema.optionalKey(Schema.String) }),
|
|
72
|
+
// Subagent lifecycle. Thread streams send `task` frames unless opened with `frames=subagent`.
|
|
73
|
+
task: Schema.Struct({ taskId: Schema.String, taskPath: Schema.optionalKey(Schema.NullOr(Schema.String)), status: Schema.String }),
|
|
74
|
+
subagent: Schema.Struct({ subagentId: Schema.String, subagentPath: Schema.optionalKey(Schema.NullOr(Schema.String)), status: Schema.String })
|
|
75
|
+
};
|
|
76
|
+
const decode = (schema, data) => Schema.decodeUnknownOption(schema)(data);
|
|
77
|
+
export const decodeEvent = (frame) => {
|
|
78
|
+
const unknown = { _tag: "Unknown", event: frame.event };
|
|
79
|
+
let data;
|
|
80
|
+
try {
|
|
81
|
+
data = JSON.parse(frame.data);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return unknown;
|
|
85
|
+
}
|
|
86
|
+
switch (frame.event) {
|
|
87
|
+
case "status":
|
|
88
|
+
return Option.match(decode(payloads.status, data), {
|
|
89
|
+
onNone: () => unknown,
|
|
90
|
+
onSome: ({ status }) => ({ _tag: "Status", status })
|
|
91
|
+
});
|
|
92
|
+
case "transcript":
|
|
93
|
+
return Option.match(decodeMessage(data), {
|
|
94
|
+
onNone: () => unknown,
|
|
95
|
+
onSome: (message) => ({ _tag: "Transcript", cursor: frame.id, message })
|
|
96
|
+
});
|
|
97
|
+
case "run":
|
|
98
|
+
return Option.match(decode(payloads.run, data), {
|
|
99
|
+
onNone: () => unknown,
|
|
100
|
+
onSome: ({ phase }) => ({ _tag: "Run", phase })
|
|
101
|
+
});
|
|
102
|
+
case "turn":
|
|
103
|
+
return Option.match(decode(payloads.turn, data), {
|
|
104
|
+
onNone: () => unknown,
|
|
105
|
+
onSome: (turn) => ({ _tag: "Turn", phase: turn.phase, outcome: turn.outcome })
|
|
106
|
+
});
|
|
107
|
+
case "assistant":
|
|
108
|
+
return Option.match(decode(payloads.assistant, data), {
|
|
109
|
+
onNone: () => unknown,
|
|
110
|
+
onSome: ({ callId, text }) => ({ _tag: "Assistant", callId, text })
|
|
111
|
+
});
|
|
112
|
+
case "tool_call":
|
|
113
|
+
return Option.match(decode(payloads.tool_call, data), {
|
|
114
|
+
onNone: () => unknown,
|
|
115
|
+
onSome: (call) => ({ _tag: "ToolCall", callId: call.callId, name: call.name, text: call.text ?? "" })
|
|
116
|
+
});
|
|
117
|
+
case "error":
|
|
118
|
+
return Option.match(decode(payloads.error, data), {
|
|
119
|
+
onNone: () => ({ _tag: "StreamError", code: "internal", message: frame.data }),
|
|
120
|
+
onSome: (error) => ({ _tag: "StreamError", code: error.code, message: error.message ?? error.code })
|
|
121
|
+
});
|
|
122
|
+
case "task":
|
|
123
|
+
return Option.match(decode(payloads.task, data), {
|
|
124
|
+
onNone: () => unknown,
|
|
125
|
+
onSome: (task) => ({ _tag: "Subagent", id: task.taskId, path: task.taskPath ?? undefined, status: task.status })
|
|
126
|
+
});
|
|
127
|
+
case "subagent":
|
|
128
|
+
return Option.match(decode(payloads.subagent, data), {
|
|
129
|
+
onNone: () => unknown,
|
|
130
|
+
onSome: (sub) => ({ _tag: "Subagent", id: sub.subagentId, path: sub.subagentPath ?? undefined, status: sub.status })
|
|
131
|
+
});
|
|
132
|
+
case "done":
|
|
133
|
+
return { _tag: "Done" };
|
|
134
|
+
case "heartbeat":
|
|
135
|
+
return { _tag: "Heartbeat" };
|
|
136
|
+
default:
|
|
137
|
+
return unknown;
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
//# sourceMappingURL=events.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/capy/events.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAGvC,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAA;AAkBjG,MAAM,QAAQ,GAAG,CAAuB,MAAS,EAAE,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAA;AAE/F,mGAAmG;AACnG,uFAAuF;AACvF,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;IAC/B,EAAE,EAAE,MAAM,CAAC,MAAM;IACjB,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC;IACtD,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC;IAC7B,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC;IAC7B,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC;IAC/B,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3G,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC;IAC9B,SAAS,EAAE,QAAQ,C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MAAM,EAAE,CAAC;aACjH,CAAC,CAAA;QACJ,KAAK,UAAU;YACb,OAAO,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE;gBACnD,MAAM,EAAE,GAAG,EAAE,CAAC,OAAO;gBACrB,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAE,GAAG,CAAC,UAAU,EAAE,IAAI,EAAE,GAAG,CAAC,YAAY,IAAI,SAAS,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC;aACrH,CAAC,CAAA;QACJ,KAAK,MAAM;YACT,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAA;QACzB,KAAK,WAAW;YACd,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,CAAA;QAC9B;YACE,OAAO,OAAO,CAAA;IAClB,CAAC;AACH,CAAC,CAAA","sourcesContent":["/**\n * Capy thread-stream events (`GET /threads/{id}/stream`), decoded from SSE frames.\n *\n * Event names this adapter does not know decode to `Unknown`, as Capy's docs ask: the\n * vocabulary grows over time. A known event whose payload fails to decode also becomes\n * `Unknown`, so one malformed frame never kills a session.\n */\nimport { Option, Schema } from \"effect\"\nimport type { SseFrame } from \"../sse.js\"\n\nexport const ThreadStatus = Schema.Literals([\"working\", \"waiting\", \"idle\", \"failed\", \"archived\"])\nexport type ThreadStatus = typeof ThreadStatus.Type\n\n/** One transcript entry, the same shape `GET /threads/{id}/messages` pages. */\nexport interface Message {\n readonly id: string\n readonly source: \"user\" | \"assistant\" | \"tool\"\n readonly text?: string\n readonly tool?: string\n readonly callId?: string\n readonly calls?: ReadonlyArray<{ readonly tool: string; readonly durationMs?: number }>\n readonly model?: string\n readonly clientKey?: string\n readonly createdAt?: string\n /** Decoded item by item (see `messageFiles`), so one odd attachment never drops the whole entry. */\n readonly attachments?: ReadonlyArray<unknown>\n}\n\nconst nullable = <S extends Schema.Top>(schema: S) => Schema.optionalKey(Schema.NullOr(schema))\n\n// The message list sends `null` for absent fields (`clientKey: null`) where the stream omits them,\n// and documents `durationMs` as a number or \"Infinity\". Only id and source are strict.\nconst RawMessage = Schema.Struct({\n id: Schema.String,\n source: Schema.Literals([\"user\", \"assistant\", \"tool\"]),\n text: nullable(Schema.String),\n tool: nullable(Schema.String),\n callId: nullable(Schema.String),\n calls: nullable(Schema.Array(Schema.Struct({ tool: Schema.String, durationMs: nullable(Schema.Unknown) }))),\n model: nullable(Schema.String),\n clientKey: nullable(Schema.String),\n createdAt: nullable(Schema.String),\n attachments: nullable(Schema.Array(Schema.Unknown))\n})\n\nconst present = <A>(key: string, value: A | null | undefined) => (value === null || value === undefined ? {} : { [key]: value })\n\nexport const decodeMessage = (data: unknown): Option.Option<Message> =>\n Option.map(Schema.decodeUnknownOption(RawMessage)(data), (raw) => ({\n id: raw.id,\n source: raw.source,\n ...present(\"text\", raw.text),\n ...present(\"tool\", raw.tool),\n ...present(\"callId\", raw.callId),\n ...present(\n \"calls\",\n raw.calls?.map((call) => ({\n tool: call.tool,\n ...(typeof call.durationMs === \"number\" && Number.isFinite(call.durationMs) ? { durationMs: call.durationMs } : {})\n }))\n ),\n ...present(\"model\", raw.model),\n ...present(\"clientKey\", raw.clientKey),\n ...present(\"createdAt\", raw.createdAt),\n ...present(\"attachments\", raw.attachments)\n }))\n\n/** A file a transcript entry carries: on assistant entries, a file the agent delivered. */\nexport interface MessageAttachment {\n readonly fileId: string\n readonly name: string\n readonly mediaType: string | undefined\n readonly sizeBytes: number | undefined\n /** Where the file came from on the agent's machine, when Capy knows. */\n readonly sourcePath: string | undefined\n readonly title: string | undefined\n}\n\nconst Attachment = Schema.Struct({\n file: Schema.Struct({\n fileId: Schema.String,\n name: Schema.String,\n mediaType: Schema.optionalKey(Schema.NullOr(Schema.String)),\n sizeBytes: Schema.optionalKey(Schema.Unknown),\n sourcePath: Schema.optionalKey(Schema.NullOr(Schema.String))\n }),\n title: Schema.optionalKey(Schema.NullOr(Schema.String))\n})\n\nexport const messageFiles = (message: Message): ReadonlyArray<MessageAttachment> =>\n (message.attachments ?? []).flatMap((item) =>\n Option.match(Schema.decodeUnknownOption(Attachment)(item), {\n onNone: () => [],\n onSome: ({ file, title }) => [{\n fileId: file.fileId,\n name: file.name,\n mediaType: file.mediaType ?? undefined,\n sizeBytes: typeof file.sizeBytes === \"number\" && Number.isFinite(file.sizeBytes) ? file.sizeBytes : undefined,\n sourcePath: file.sourcePath ?? undefined,\n title: title ?? undefined\n }]\n })\n )\n\nconst payloads = {\n status: Schema.Struct({ status: ThreadStatus }),\n run: Schema.Struct({ phase: Schema.Literals([\"start\", \"end\"]) }),\n turn: Schema.Struct({\n phase: Schema.Literals([\"start\", \"end\"]),\n outcome: Schema.optionalKey(Schema.String)\n }),\n assistant: Schema.Struct({ callId: Schema.String, text: Schema.String }),\n tool_call: Schema.Struct({ callId: Schema.String, name: Schema.String, text: Schema.optionalKey(Schema.String) }),\n error: Schema.Struct({ code: Schema.String, message: Schema.optionalKey(Schema.String) }),\n // Subagent lifecycle. Thread streams send `task` frames unless opened with `frames=subagent`.\n task: Schema.Struct({ taskId: Schema.String, taskPath: Schema.optionalKey(Schema.NullOr(Schema.String)), status: Schema.String }),\n subagent: Schema.Struct({ subagentId: Schema.String, subagentPath: Schema.optionalKey(Schema.NullOr(Schema.String)), status: Schema.String })\n} as const\n\nexport type CapyEvent =\n | { readonly _tag: \"Status\"; readonly status: ThreadStatus }\n | { readonly _tag: \"Transcript\"; readonly cursor: string | undefined; readonly message: Message }\n | { readonly _tag: \"Run\"; readonly phase: \"start\" | \"end\" }\n | { readonly _tag: \"Turn\"; readonly phase: \"start\" | \"end\"; readonly outcome: string | undefined }\n | { readonly _tag: \"Assistant\"; readonly callId: string; readonly text: string }\n | { readonly _tag: \"ToolCall\"; readonly callId: string; readonly name: string; readonly text: string }\n | { readonly _tag: \"StreamError\"; readonly code: string; readonly message: string }\n /** A subagent under the thread was created or changed status (`draft`, `working`, `waiting`, `idle`, `done`, `failed`). */\n | { readonly _tag: \"Subagent\"; readonly id: string; readonly path: string | undefined; readonly status: string }\n | { readonly _tag: \"Done\" }\n | { readonly _tag: \"Heartbeat\" }\n | { readonly _tag: \"Unknown\"; readonly event: string }\n\nconst decode = <S extends Schema.Decoder<unknown>>(schema: S, data: unknown): Option.Option<S[\"Type\"]> =>\n Schema.decodeUnknownOption(schema)(data)\n\nexport const decodeEvent = (frame: SseFrame): CapyEvent => {\n const unknown: CapyEvent = { _tag: \"Unknown\", event: frame.event }\n let data: unknown\n try {\n data = JSON.parse(frame.data)\n } catch {\n return unknown\n }\n switch (frame.event) {\n case \"status\":\n return Option.match(decode(payloads.status, data), {\n onNone: () => unknown,\n onSome: ({ status }) => ({ _tag: \"Status\", status })\n })\n case \"transcript\":\n return Option.match(decodeMessage(data), {\n onNone: () => unknown,\n onSome: (message) => ({ _tag: \"Transcript\", cursor: frame.id, message })\n })\n case \"run\":\n return Option.match(decode(payloads.run, data), {\n onNone: () => unknown,\n onSome: ({ phase }) => ({ _tag: \"Run\", phase })\n })\n case \"turn\":\n return Option.match(decode(payloads.turn, data), {\n onNone: () => unknown,\n onSome: (turn) => ({ _tag: \"Turn\", phase: turn.phase, outcome: turn.outcome })\n })\n case \"assistant\":\n return Option.match(decode(payloads.assistant, data), {\n onNone: () => unknown,\n onSome: ({ callId, text }) => ({ _tag: \"Assistant\", callId, text })\n })\n case \"tool_call\":\n return Option.match(decode(payloads.tool_call, data), {\n onNone: () => unknown,\n onSome: (call) => ({ _tag: \"ToolCall\", callId: call.callId, name: call.name, text: call.text ?? \"\" })\n })\n case \"error\":\n return Option.match(decode(payloads.error, data), {\n onNone: () => ({ _tag: \"StreamError\", code: \"internal\", message: frame.data }),\n onSome: (error) => ({ _tag: \"StreamError\", code: error.code, message: error.message ?? error.code })\n })\n case \"task\":\n return Option.match(decode(payloads.task, data), {\n onNone: () => unknown,\n onSome: (task) => ({ _tag: \"Subagent\", id: task.taskId, path: task.taskPath ?? undefined, status: task.status })\n })\n case \"subagent\":\n return Option.match(decode(payloads.subagent, data), {\n onNone: () => unknown,\n onSome: (sub) => ({ _tag: \"Subagent\", id: sub.subagentId, path: sub.subagentPath ?? undefined, status: sub.status })\n })\n case \"done\":\n return { _tag: \"Done\" }\n case \"heartbeat\":\n return { _tag: \"Heartbeat\" }\n default:\n return unknown\n }\n}\n"]}
|