@theokit/acp 4.0.3 → 4.2.2
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/CHANGELOG.md +47 -0
- package/README.md +32 -1
- package/dist/client.cjs +339 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +92 -0
- package/dist/client.d.ts +92 -0
- package/dist/client.js +316 -0
- package/dist/client.js.map +1 -0
- package/dist/index.cjs +176 -153
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +176 -153
- package/dist/index.js.map +1 -1
- package/package.json +13 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 4.2.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [[`4af5a9e`](https://github.com/usetheokit/theokit-sdk/commit/4af5a9ee1bed97e9a41ac719789bac0f05ae2939), [`b091ca2`](https://github.com/usetheokit/theokit-sdk/commit/b091ca2baa84295face7df3d592940fe9497369d)]:
|
|
8
|
+
- @theokit/sdk@10.0.0
|
|
9
|
+
|
|
10
|
+
## 4.2.1
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- Updated dependencies [[`f836198`](https://github.com/usetheokit/theokit-sdk/commit/f8361986f4366174486f903a8eea29abd1376cff)]:
|
|
15
|
+
- @theokit/sdk@9.0.0
|
|
16
|
+
|
|
17
|
+
## 4.2.0
|
|
18
|
+
|
|
19
|
+
### Minor Changes
|
|
20
|
+
|
|
21
|
+
- [#1471](https://github.com/usetheokit/theokit-sdk/pull/1471) [`7884ffb`](https://github.com/usetheokit/theokit-sdk/commit/7884ffbe11f78a09083a663ef82e0b12b18be590) Thanks [@aifactory-paulohenriquevn](https://github.com/apps/aifactory-paulohenriquevn)! - Add `@theokit/acp/client`: `connectAcpAgent` spawns an ACP agent and drives it through the ACP SDK's `ClientSideConnection` (streamed prompt updates, permission callback, `session/cancel` on abort, process-group cleanup). Commands resolve on absolute `PATH` entries only and `process.env` is never inherited. Also exports `AcpAgentSpawnError`.
|
|
22
|
+
|
|
23
|
+
## 4.1.3
|
|
24
|
+
|
|
25
|
+
### Patch Changes
|
|
26
|
+
|
|
27
|
+
- Updated dependencies [[`616082e`](https://github.com/usetheokit/theokit-sdk/commit/616082e1a6426e7c8fd6a02ab0a48ee117b88cc6), [`24110d0`](https://github.com/usetheokit/theokit-sdk/commit/24110d0406c4f0e595acac568d84ca1d281bc725), [`30fabe6`](https://github.com/usetheokit/theokit-sdk/commit/30fabe699a6efd189555ae77545256a2f0599ea7), [`30fabe6`](https://github.com/usetheokit/theokit-sdk/commit/30fabe699a6efd189555ae77545256a2f0599ea7)]:
|
|
28
|
+
- @theokit/sdk@8.0.0
|
|
29
|
+
|
|
30
|
+
## 4.1.2
|
|
31
|
+
|
|
32
|
+
### Patch Changes
|
|
33
|
+
|
|
34
|
+
- Updated dependencies [[`3365e10`](https://github.com/usetheokit/theokit-sdk/commit/3365e10f1889a962111fb7956aed017ce5bc9a5e), [`3467c6c`](https://github.com/usetheokit/theokit-sdk/commit/3467c6c4e200c79eb2d494f8e75bf6beb06b7984), [`273b354`](https://github.com/usetheokit/theokit-sdk/commit/273b354228b661473a2b7bb3e0eb87db0c6f8505), [`70eed5a`](https://github.com/usetheokit/theokit-sdk/commit/70eed5a1c78cfdc693e6fbd032834471efde4c38), [`9b7c142`](https://github.com/usetheokit/theokit-sdk/commit/9b7c142637e0944e7124851b47167b2835bbe899), [`2e0b1af`](https://github.com/usetheokit/theokit-sdk/commit/2e0b1afa300d46baa9f098a423f31e2908a0a59b), [`52ed77d`](https://github.com/usetheokit/theokit-sdk/commit/52ed77dee461a07c94535915659c76071850f79a), [`f327fe1`](https://github.com/usetheokit/theokit-sdk/commit/f327fe1b27f033765cfae46481d2c2a9ce6b0fcf), [`2f79474`](https://github.com/usetheokit/theokit-sdk/commit/2f79474d61f1e5198fcfed7fe03765be5e09752d), [`422629d`](https://github.com/usetheokit/theokit-sdk/commit/422629d43b7d261c4f8ae0ad02305af55091ee81), [`48205d6`](https://github.com/usetheokit/theokit-sdk/commit/48205d688a87831bf6c1f16be3f03a524a1cada3), [`20bbcdb`](https://github.com/usetheokit/theokit-sdk/commit/20bbcdb58b2f53153f484d7f0ad2f46dccb2bdb7), [`e476785`](https://github.com/usetheokit/theokit-sdk/commit/e47678530db226342f7097827f9315bbf317965b)]:
|
|
35
|
+
- @theokit/sdk@7.0.0
|
|
36
|
+
|
|
37
|
+
## 4.1.1
|
|
38
|
+
|
|
39
|
+
### Patch Changes
|
|
40
|
+
|
|
41
|
+
- Updated dependencies [[`0312049`](https://github.com/usetheokit/theokit-sdk/commit/03120492204a1db8ac0d2b4779e10119264c9f13), [`cd71b80`](https://github.com/usetheokit/theokit-sdk/commit/cd71b80eba1c27c39490d38a12060929de02dad4), [`0970314`](https://github.com/usetheokit/theokit-sdk/commit/0970314edc9d11174c9759641b2c63fe35f0ab83), [`5fe79be`](https://github.com/usetheokit/theokit-sdk/commit/5fe79be6f3c0e28eabcfceed07092185eb721cd6), [`d2a7000`](https://github.com/usetheokit/theokit-sdk/commit/d2a70005daf4008ff830de82b7cd4863680cd11b), [`18b1e2d`](https://github.com/usetheokit/theokit-sdk/commit/18b1e2d4e8e6d41adc98e62efe395f26e4f1c90d), [`dc51bf2`](https://github.com/usetheokit/theokit-sdk/commit/dc51bf231ab50000eadf57f77453c4179a9abf0d), [`b32a3f5`](https://github.com/usetheokit/theokit-sdk/commit/b32a3f591a37bf53518ed84754f76e4834bc31b2), [`dc51bf2`](https://github.com/usetheokit/theokit-sdk/commit/dc51bf231ab50000eadf57f77453c4179a9abf0d), [`656181b`](https://github.com/usetheokit/theokit-sdk/commit/656181be34a3b6234a28330dd2a37a528616d809), [`96f9b46`](https://github.com/usetheokit/theokit-sdk/commit/96f9b46ea1c590046e3bea92b773b49bcaa2f448), [`96f9b46`](https://github.com/usetheokit/theokit-sdk/commit/96f9b46ea1c590046e3bea92b773b49bcaa2f448), [`d699f50`](https://github.com/usetheokit/theokit-sdk/commit/d699f504ebd2e7c6ba8a2d0a87efe360f59765f0), [`4a8c1d4`](https://github.com/usetheokit/theokit-sdk/commit/4a8c1d4c22c5a72f17e488466926a0d2126cb762), [`a613a6d`](https://github.com/usetheokit/theokit-sdk/commit/a613a6d68e4e7bd349665ca1dfc07127b081484f), [`c0a23b3`](https://github.com/usetheokit/theokit-sdk/commit/c0a23b37c261bc740a6b71619f6249548a7c6a46), [`378b855`](https://github.com/usetheokit/theokit-sdk/commit/378b85541c9f8cb51122d8aa59e064da3013aee8), [`bf5b17e`](https://github.com/usetheokit/theokit-sdk/commit/bf5b17e53be219cfb848fb53f9a0624332c7936b), [`974277b`](https://github.com/usetheokit/theokit-sdk/commit/974277b6b781de2b390463a05221d26d4fcb6c3a), [`88604c7`](https://github.com/usetheokit/theokit-sdk/commit/88604c71de235aa960e79a52428b474b1454411b), [`a85e847`](https://github.com/usetheokit/theokit-sdk/commit/a85e84774873f4b62c36f3f826c7836ba756cb65), [`a85e847`](https://github.com/usetheokit/theokit-sdk/commit/a85e84774873f4b62c36f3f826c7836ba756cb65), [`ef69798`](https://github.com/usetheokit/theokit-sdk/commit/ef69798bc4ab6d5632ff265074a8163a2c7c7fec), [`fa3e29c`](https://github.com/usetheokit/theokit-sdk/commit/fa3e29c6d2bbff097dbd484e1045e46b74644bb8), [`91edaec`](https://github.com/usetheokit/theokit-sdk/commit/91edaec0131a8af18570bbfc1b3e1ebf4d011c37), [`5d9ab84`](https://github.com/usetheokit/theokit-sdk/commit/5d9ab84e2fb90374e5ec03f8ff268610c45a7433), [`712e132`](https://github.com/usetheokit/theokit-sdk/commit/712e1327974dc2e8c1f9889e2b2f2aaa3c50319e), [`237b277`](https://github.com/usetheokit/theokit-sdk/commit/237b277377f90551e159d4b07aba2baab1398a66), [`272eea6`](https://github.com/usetheokit/theokit-sdk/commit/272eea648d7654f41ce916410d95ccbc5a97a6a6), [`ef69798`](https://github.com/usetheokit/theokit-sdk/commit/ef69798bc4ab6d5632ff265074a8163a2c7c7fec)]:
|
|
42
|
+
- @theokit/sdk@6.0.0
|
|
43
|
+
|
|
44
|
+
## 4.1.0
|
|
45
|
+
|
|
46
|
+
### Minor Changes
|
|
47
|
+
|
|
48
|
+
- [#1302](https://github.com/usetheokit/theokit-sdk/pull/1302) [`60a12a3`](https://github.com/usetheokit/theokit-sdk/commit/60a12a385d90455a642cc6f296700d092f758951) Thanks [@aifactory-paulohenriquevn](https://github.com/apps/aifactory-paulohenriquevn)! - `serveAcp` now accepts any `AgentLike` (or a factory returning one) instead of requiring a full `SDKAgent`; `dispose` is optional, and `session/new` now fails closed with `permission_enforcement_unavailable` when `ask`/`deny` cannot be enforced ([#1019](https://github.com/usetheokit/theokit-sdk/issues/1019)).
|
|
49
|
+
|
|
3
50
|
## 4.0.3
|
|
4
51
|
|
|
5
52
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
Agent Client Protocol (ACP) server adapter for [`@theokit/sdk`](https://www.npmjs.com/package/@theokit/sdk).
|
|
4
4
|
|
|
5
|
-
Exposes
|
|
5
|
+
Exposes an agent over stdio JSON-RPC so any [ACP-compatible host](https://agentclientprotocol.com) can drive it as a coding agent — without writing any glue code.
|
|
6
|
+
|
|
7
|
+
`serveAcp` takes any `AgentLike` (from `@theokit/sdk`) or a `(sessionId) => AgentLike` factory, so a wrapper around an `SDKAgent` needs no cast; an `SDKAgent` still works. `dispose` is optional. With `permissionDefault: "ask"` or `"deny"` the agent must also expose a `pluginManager()`; otherwise `session/new` fails closed with `permission_enforcement_unavailable`.
|
|
6
8
|
|
|
7
9
|
```bash
|
|
8
10
|
npm i @theokit/acp @theokit/sdk @agentclientprotocol/sdk
|
|
@@ -82,3 +84,32 @@ rather than the version someone wrote a page about.
|
|
|
82
84
|
## License
|
|
83
85
|
|
|
84
86
|
Apache-2.0
|
|
87
|
+
|
|
88
|
+
## Client: drive another ACP agent
|
|
89
|
+
|
|
90
|
+
`@theokit/acp/client` is a separate entry (server-only consumers never load it). It spawns an ACP agent as a child process and drives it through the ACP SDK's `ClientSideConnection`.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { connectAcpAgent, AcpAgentSpawnError } from "@theokit/acp/client";
|
|
94
|
+
|
|
95
|
+
const agent = await connectAcpAgent({
|
|
96
|
+
command: "my-agent", // absolute path, or a bare name found on absolute PATH entries of `env`
|
|
97
|
+
args: ["--stdio"],
|
|
98
|
+
cwd: "/work/project",
|
|
99
|
+
env: { PATH: "/usr/local/bin:/usr/bin" }, // passed as is; nothing is inherited from process.env
|
|
100
|
+
onPermission: async (request) => ({ outcome: { outcome: "selected", optionId: "deny" } }),
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
const controller = new AbortController();
|
|
104
|
+
for await (const { update } of agent.prompt("hi", controller.signal)) {
|
|
105
|
+
console.log(update);
|
|
106
|
+
}
|
|
107
|
+
await agent.close();
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
- **Command resolution.** A relative `command` with a path separator is refused. A bare name is resolved only against `env.PATH`, and a relative or empty `PATH` entry (`.`, `::`) refuses it before anything is spawned.
|
|
111
|
+
- **Environment.** `env` is the child's whole environment; `process.env` is never merged in.
|
|
112
|
+
- **Permissions.** The agent's `session/request_permission` reaches `onPermission`; its answer is sent back unchanged.
|
|
113
|
+
- **Cancellation.** Aborting the `signal` passed to `prompt` sends `session/cancel`. One prompt may be in flight per connection.
|
|
114
|
+
- **Failures.** `AcpAgentSpawnError` is raised when the command is refused or not found, or when the child exits (or stalls past `initializeTimeoutMs`, default 10 s) during `initialize`. A child that exits mid-prompt ends the iterator with the same error, naming the exit code and the last (bounded) stderr lines.
|
|
115
|
+
- **Cleanup.** `close()` kills the child, and its whole process group on POSIX. It is idempotent.
|
package/dist/client.cjs
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var stream = require('stream');
|
|
4
|
+
var acp = require('@agentclientprotocol/sdk');
|
|
5
|
+
var child_process = require('child_process');
|
|
6
|
+
var fs = require('fs');
|
|
7
|
+
var path = require('path');
|
|
8
|
+
var sdk = require('@theokit/sdk');
|
|
9
|
+
|
|
10
|
+
function _interopNamespace(e) {
|
|
11
|
+
if (e && e.__esModule) return e;
|
|
12
|
+
var n = Object.create(null);
|
|
13
|
+
if (e) {
|
|
14
|
+
Object.keys(e).forEach(function (k) {
|
|
15
|
+
if (k !== 'default') {
|
|
16
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
17
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
18
|
+
enumerable: true,
|
|
19
|
+
get: function () { return e[k]; }
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
n.default = e;
|
|
25
|
+
return Object.freeze(n);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
var acp__namespace = /*#__PURE__*/_interopNamespace(acp);
|
|
29
|
+
|
|
30
|
+
// src/client.ts
|
|
31
|
+
var STDERR_MAX_LINES = 20;
|
|
32
|
+
var STDERR_MAX_LINE_CHARS = 500;
|
|
33
|
+
var KILL_GRACE_MS = 2e3;
|
|
34
|
+
var AcpAgentSpawnError = class extends sdk.TheokitAgentError {
|
|
35
|
+
name = "AcpAgentSpawnError";
|
|
36
|
+
/** Exit code of the child, when it exited with one. */
|
|
37
|
+
exitCode;
|
|
38
|
+
/** Signal that ended the child, when it was killed by one. */
|
|
39
|
+
exitSignal;
|
|
40
|
+
/** The last (bounded) stderr lines of the child. */
|
|
41
|
+
stderrTail;
|
|
42
|
+
constructor(message, details = {}) {
|
|
43
|
+
super(message, {
|
|
44
|
+
...details.cause !== void 0 ? { cause: details.cause } : {}
|
|
45
|
+
});
|
|
46
|
+
if (details.exitCode !== void 0) this.exitCode = details.exitCode;
|
|
47
|
+
if (details.exitSignal !== void 0) this.exitSignal = details.exitSignal;
|
|
48
|
+
if (details.stderrTail !== void 0) this.stderrTail = details.stderrTail;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
function isExecutableFile(path) {
|
|
52
|
+
try {
|
|
53
|
+
if (!fs.statSync(path).isFile()) return false;
|
|
54
|
+
fs.accessSync(path, fs.constants.X_OK);
|
|
55
|
+
return true;
|
|
56
|
+
} catch {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function resolveCommand(command, env) {
|
|
61
|
+
if (command.length === 0) throw new AcpAgentSpawnError("ACP agent command is empty");
|
|
62
|
+
if (path.isAbsolute(command)) {
|
|
63
|
+
if (isExecutableFile(command)) return command;
|
|
64
|
+
throw new AcpAgentSpawnError(`ACP agent command not found or not executable: ${command}`);
|
|
65
|
+
}
|
|
66
|
+
if (command.includes("/") || command.includes("\\")) {
|
|
67
|
+
throw new AcpAgentSpawnError(
|
|
68
|
+
`ACP agent command "${command}" is a relative path; use an absolute path or a bare command name`
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
return resolveOnPath(command, env.PATH ?? "");
|
|
72
|
+
}
|
|
73
|
+
function resolveOnPath(command, pathValue) {
|
|
74
|
+
const entries = pathValue.split(path.delimiter);
|
|
75
|
+
if (entries.some((entry) => entry === "" || !path.isAbsolute(entry))) {
|
|
76
|
+
throw new AcpAgentSpawnError(
|
|
77
|
+
`refusing to resolve "${command}": PATH has a relative or empty entry`
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
const found = entries.map((entry) => path.join(entry, command)).find(isExecutableFile);
|
|
81
|
+
if (found === void 0) {
|
|
82
|
+
throw new AcpAgentSpawnError(`ACP agent command not found on PATH: ${command}`);
|
|
83
|
+
}
|
|
84
|
+
return found;
|
|
85
|
+
}
|
|
86
|
+
function trackStderr(child) {
|
|
87
|
+
const lines = [];
|
|
88
|
+
let partial = "";
|
|
89
|
+
const push = (line) => {
|
|
90
|
+
lines.push(line.slice(0, STDERR_MAX_LINE_CHARS));
|
|
91
|
+
if (lines.length > STDERR_MAX_LINES) lines.shift();
|
|
92
|
+
};
|
|
93
|
+
child.stderr?.setEncoding("utf8");
|
|
94
|
+
child.stderr?.on("data", (chunk) => {
|
|
95
|
+
const parts = (partial + chunk).split("\n");
|
|
96
|
+
partial = (parts.pop() ?? "").slice(-STDERR_MAX_LINE_CHARS);
|
|
97
|
+
for (const part of parts) push(part);
|
|
98
|
+
});
|
|
99
|
+
return () => (partial.length > 0 ? [...lines, partial] : lines).slice(-STDERR_MAX_LINES).join("\n");
|
|
100
|
+
}
|
|
101
|
+
function signalGroup(child, signal) {
|
|
102
|
+
try {
|
|
103
|
+
if (process.platform !== "win32" && child.pid !== void 0) process.kill(-child.pid, signal);
|
|
104
|
+
else child.kill(signal);
|
|
105
|
+
} catch {
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function spawnAgentChild(file, args, options) {
|
|
109
|
+
return new Promise((resolve, reject) => {
|
|
110
|
+
const child = child_process.spawn(file, [...args], {
|
|
111
|
+
cwd: options.cwd,
|
|
112
|
+
env: options.env,
|
|
113
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
114
|
+
detached: process.platform !== "win32"
|
|
115
|
+
});
|
|
116
|
+
const stderrTail = trackStderr(child);
|
|
117
|
+
let exitedFlag = false;
|
|
118
|
+
const exited = new Promise((done) => {
|
|
119
|
+
child.once("close", (code, signal) => {
|
|
120
|
+
exitedFlag = true;
|
|
121
|
+
done({ code, signal });
|
|
122
|
+
});
|
|
123
|
+
child.once("error", () => {
|
|
124
|
+
if (child.pid === void 0) {
|
|
125
|
+
exitedFlag = true;
|
|
126
|
+
done({ code: null, signal: null });
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
child.once("error", (err) => {
|
|
131
|
+
if (child.pid === void 0) {
|
|
132
|
+
reject(new AcpAgentSpawnError(`failed to spawn ${file}: ${err.message}`, { cause: err }));
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
child.once("spawn", () => {
|
|
136
|
+
child.stdin?.on("error", () => {
|
|
137
|
+
});
|
|
138
|
+
resolve({
|
|
139
|
+
process: child,
|
|
140
|
+
exited,
|
|
141
|
+
stderrTail,
|
|
142
|
+
hasExited: () => exitedFlag,
|
|
143
|
+
async kill() {
|
|
144
|
+
if (!exitedFlag) {
|
|
145
|
+
signalGroup(child, "SIGTERM");
|
|
146
|
+
const timer = setTimeout(() => signalGroup(child, "SIGKILL"), KILL_GRACE_MS);
|
|
147
|
+
await exited;
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
}
|
|
150
|
+
signalGroup(child, "SIGKILL");
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// src/client.ts
|
|
158
|
+
var DEFAULT_INITIALIZE_TIMEOUT_MS = 1e4;
|
|
159
|
+
var EXIT_SETTLE_MS = 1e3;
|
|
160
|
+
var UpdateQueue = class {
|
|
161
|
+
items = [];
|
|
162
|
+
waiter;
|
|
163
|
+
done = false;
|
|
164
|
+
failure;
|
|
165
|
+
push(item) {
|
|
166
|
+
this.items.push(item);
|
|
167
|
+
this.wake();
|
|
168
|
+
}
|
|
169
|
+
end(failure) {
|
|
170
|
+
if (this.done) return;
|
|
171
|
+
this.done = true;
|
|
172
|
+
this.failure = failure;
|
|
173
|
+
this.wake();
|
|
174
|
+
}
|
|
175
|
+
wake() {
|
|
176
|
+
const w = this.waiter;
|
|
177
|
+
this.waiter = void 0;
|
|
178
|
+
w?.();
|
|
179
|
+
}
|
|
180
|
+
async *drain() {
|
|
181
|
+
for (; ; ) {
|
|
182
|
+
const next = this.items.shift();
|
|
183
|
+
if (next !== void 0) {
|
|
184
|
+
yield next;
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (this.done) {
|
|
188
|
+
if (this.failure !== void 0) throw this.failure;
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
await new Promise((resolve) => {
|
|
192
|
+
this.waiter = resolve;
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
var delay = (ms) => new Promise((resolve) => {
|
|
198
|
+
setTimeout(resolve, ms).unref();
|
|
199
|
+
});
|
|
200
|
+
async function exitError(child, phase, cause) {
|
|
201
|
+
const result = await Promise.race([child.exited, delay(EXIT_SETTLE_MS)]);
|
|
202
|
+
const tail = child.stderrTail();
|
|
203
|
+
const stderrPart = tail.length > 0 ? `; stderr:
|
|
204
|
+
${tail}` : "";
|
|
205
|
+
if (result === void 0) {
|
|
206
|
+
return new AcpAgentSpawnError(`ACP agent connection failed ${phase}${stderrPart}`, {
|
|
207
|
+
stderrTail: tail,
|
|
208
|
+
cause
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
const how = result.signal !== null ? `signal ${result.signal}` : `code ${result.code}`;
|
|
212
|
+
return new AcpAgentSpawnError(`ACP agent exited ${phase} (${how})${stderrPart}`, {
|
|
213
|
+
exitCode: result.code,
|
|
214
|
+
exitSignal: result.signal,
|
|
215
|
+
stderrTail: tail,
|
|
216
|
+
cause
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
var Connection = class {
|
|
220
|
+
constructor(child, conn, sessionId) {
|
|
221
|
+
this.child = child;
|
|
222
|
+
this.conn = conn;
|
|
223
|
+
this.sessionId = sessionId;
|
|
224
|
+
}
|
|
225
|
+
child;
|
|
226
|
+
conn;
|
|
227
|
+
sessionId;
|
|
228
|
+
active;
|
|
229
|
+
closing;
|
|
230
|
+
closed = false;
|
|
231
|
+
/** @internal */
|
|
232
|
+
dispatch(update) {
|
|
233
|
+
if (update.sessionId === this.sessionId) this.active?.push(update);
|
|
234
|
+
}
|
|
235
|
+
prompt(text, signal) {
|
|
236
|
+
return this.run(text, signal);
|
|
237
|
+
}
|
|
238
|
+
async *run(text, signal) {
|
|
239
|
+
if (this.closed) throw new AcpAgentSpawnError("ACP agent connection is closed");
|
|
240
|
+
if (this.active !== void 0)
|
|
241
|
+
throw new Error("a prompt is already in flight on this connection");
|
|
242
|
+
const queue = new UpdateQueue();
|
|
243
|
+
this.active = queue;
|
|
244
|
+
const onAbort = () => {
|
|
245
|
+
this.conn.cancel({ sessionId: this.sessionId }).catch(() => {
|
|
246
|
+
});
|
|
247
|
+
};
|
|
248
|
+
if (signal?.aborted) onAbort();
|
|
249
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
250
|
+
this.child.exited.then(async () => {
|
|
251
|
+
if (this.closed) return;
|
|
252
|
+
queue.end(await exitError(this.child, "during prompt"));
|
|
253
|
+
});
|
|
254
|
+
this.conn.prompt({ sessionId: this.sessionId, prompt: [{ type: "text", text }] }).then(
|
|
255
|
+
// Let notifications already read from the pipe reach the queue first.
|
|
256
|
+
() => new Promise((resolve) => setImmediate(resolve)).then(() => queue.end()),
|
|
257
|
+
async (err) => {
|
|
258
|
+
queue.end(this.closed ? void 0 : await exitError(this.child, "during prompt", err));
|
|
259
|
+
}
|
|
260
|
+
);
|
|
261
|
+
try {
|
|
262
|
+
yield* queue.drain();
|
|
263
|
+
} finally {
|
|
264
|
+
signal?.removeEventListener("abort", onAbort);
|
|
265
|
+
if (this.active === queue) this.active = void 0;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
close() {
|
|
269
|
+
this.closed = true;
|
|
270
|
+
this.closing ??= this.child.kill().then(() => this.active?.end());
|
|
271
|
+
return this.closing;
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
async function handshake(conn, cwd) {
|
|
275
|
+
await conn.initialize({ protocolVersion: acp__namespace.PROTOCOL_VERSION, clientCapabilities: {} });
|
|
276
|
+
const session = await conn.newSession({ cwd, mcpServers: [] });
|
|
277
|
+
return session.sessionId;
|
|
278
|
+
}
|
|
279
|
+
async function initialize(child, conn, options) {
|
|
280
|
+
const timeoutMs = options.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS;
|
|
281
|
+
let timer;
|
|
282
|
+
const timeout = new Promise((_, reject) => {
|
|
283
|
+
timer = setTimeout(
|
|
284
|
+
() => reject(new AcpAgentSpawnError(`ACP agent did not initialize within ${timeoutMs}ms`)),
|
|
285
|
+
timeoutMs
|
|
286
|
+
);
|
|
287
|
+
});
|
|
288
|
+
const exit = child.exited.then(
|
|
289
|
+
() => exitError(child, "during initialize").then((e) => Promise.reject(e))
|
|
290
|
+
);
|
|
291
|
+
try {
|
|
292
|
+
return await Promise.race([handshake(conn, options.cwd), timeout, exit]);
|
|
293
|
+
} catch (err) {
|
|
294
|
+
if (err instanceof AcpAgentSpawnError) throw err;
|
|
295
|
+
throw await exitError(child, "during initialize", err);
|
|
296
|
+
} finally {
|
|
297
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
async function connectAcpAgent(options) {
|
|
301
|
+
const file = resolveCommand(options.command, options.env);
|
|
302
|
+
const child = await spawnAgentChild(file, options.args ?? [], {
|
|
303
|
+
cwd: options.cwd,
|
|
304
|
+
env: options.env
|
|
305
|
+
});
|
|
306
|
+
const stdin = child.process.stdin;
|
|
307
|
+
const stdout = child.process.stdout;
|
|
308
|
+
if (stdin === null || stdout === null) {
|
|
309
|
+
await child.kill();
|
|
310
|
+
throw new AcpAgentSpawnError("ACP agent child has no stdio pipes");
|
|
311
|
+
}
|
|
312
|
+
const stream$1 = acp__namespace.ndJsonStream(
|
|
313
|
+
stream.Writable.toWeb(stdin),
|
|
314
|
+
stream.Readable.toWeb(stdout)
|
|
315
|
+
);
|
|
316
|
+
let connection;
|
|
317
|
+
const conn = new acp__namespace.ClientSideConnection(
|
|
318
|
+
() => ({
|
|
319
|
+
requestPermission: (request) => options.onPermission(request),
|
|
320
|
+
sessionUpdate: async (update) => {
|
|
321
|
+
connection?.dispatch(update);
|
|
322
|
+
}
|
|
323
|
+
}),
|
|
324
|
+
stream$1
|
|
325
|
+
);
|
|
326
|
+
try {
|
|
327
|
+
const sessionId = await initialize(child, conn, options);
|
|
328
|
+
connection = new Connection(child, conn, sessionId);
|
|
329
|
+
return connection;
|
|
330
|
+
} catch (err) {
|
|
331
|
+
await child.kill();
|
|
332
|
+
throw err;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
exports.AcpAgentSpawnError = AcpAgentSpawnError;
|
|
337
|
+
exports.connectAcpAgent = connectAcpAgent;
|
|
338
|
+
//# sourceMappingURL=client.cjs.map
|
|
339
|
+
//# sourceMappingURL=client.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client-spawn.ts","../src/client.ts"],"names":["TheokitAgentError","statSync","accessSync","constants","isAbsolute","delimiter","join","spawn","acp","stream","Writable","Readable"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,IAAM,gBAAA,GAAmB,EAAA;AAEzB,IAAM,qBAAA,GAAwB,GAAA;AAC9B,IAAM,aAAA,GAAgB,GAAA;AAQf,IAAM,kBAAA,GAAN,cAAiCA,qBAAA,CAAkB;AAAA,EACtC,IAAA,GAAe,oBAAA;AAAA;AAAA,EAExB,QAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,UAAA;AAAA,EAET,WAAA,CACE,OAAA,EACA,OAAA,GAKI,EAAC,EACL;AACA,IAAA,KAAA,CAAM,OAAA,EAAS;AAAA,MACb,GAAI,QAAQ,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI;AAAC,KAC/D,CAAA;AACD,IAAA,IAAI,OAAA,CAAQ,QAAA,KAAa,MAAA,EAAW,IAAA,CAAK,WAAW,OAAA,CAAQ,QAAA;AAC5D,IAAA,IAAI,OAAA,CAAQ,UAAA,KAAe,MAAA,EAAW,IAAA,CAAK,aAAa,OAAA,CAAQ,UAAA;AAChE,IAAA,IA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AAQ,GAAA;AAAA,IACb,KAAK,OAAA,CAAQ;AAAA,GACd,CAAA;AACD,EAAA,MAAM,KAAA,GAAQ,MAAM,OAAA,CAAQ,KAAA;AAC5B,EAAA,MAAM,MAAA,GAAS,MAAM,OAAA,CAAQ,MAAA;AAC7B,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,MAAA,KAAW,IAAA,EAAM;AACrC,IAAA,MAAM,MAAM,IAAA,EAAK;AACjB,IAAA,MAAM,IAAI,mBAAmB,oCAAoC,CAAA;AAAA,EACnE;AACA,EAAA,MAAMC,QAAA,GAAaD,cAAA,CAAA,YAAA;AAAA,IACjBE,eAAA,CAAS,MAAM,KAAK,CAAA;AAAA,IACpBC,eAAA,CAAS,MAAM,MAAM;AAAA,GACvB;AACA,EAAA,IAAI,UAAA;AACJ,EAAA,MAAM,OAAO,IAAQH,cAAA,CAAA,oBAAA;AAAA,IACnB,OAAO;AAAA,MACL,iBAAA,EAAmB,CAAC,OAAA,KAAY,OAAA,CAAQ,aAAa,OAAO,CAAA;AAAA,MAC5D,aAAA,EAAe,OAAO,MAAA,KAAW;AAC/B,QAAA,UAAA,EAAY,SAAS,MAAM,CAAA;AAAA,MAC7B;AAAA,KACF,CAAA;AAAA,IACAC;AAAA,GACF;AACA,EAAA,IAAI;AACF,IAAA,MAAM,SAAA,GAAY,MAAM,UAAA,CAAW,KAAA,EAAO,MAAM,OAAO,CAAA;AACvD,IAAA,UAAA,GAAa,IAAI,UAAA,CAAW,KAAA,EAAO,IAAA,EAAM,SAAS,CAAA;AAClD,IAAA,OAAO,UAAA;AAAA,EACT,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,MAAM,IAAA,EAAK;AACjB,IAAA,MAAM,GAAA;AAAA,EACR;AACF","file":"client.cjs","sourcesContent":["/**\n * Command resolution and child-process handling for `connectAcpAgent`.\n *\n * @internal\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { accessSync, constants, statSync } from \"node:fs\";\nimport { delimiter, isAbsolute, join } from \"node:path\";\nimport { TheokitAgentError } from \"@theokit/sdk\";\n\n/** Number of trailing stderr lines kept for diagnostics. */\nconst STDERR_MAX_LINES = 20;\n/** Cap on one kept stderr line, in characters. */\nconst STDERR_MAX_LINE_CHARS = 500;\nconst KILL_GRACE_MS = 2_000;\n\n/**\n * A child agent could not be started, was refused before starting, or exited before it finished\n * what it was asked to do.\n *\n * @public\n */\nexport class AcpAgentSpawnError extends TheokitAgentError {\n override readonly name: string = \"AcpAgentSpawnError\";\n /** Exit code of the child, when it exited with one. */\n readonly exitCode?: number | null;\n /** Signal that ended the child, when it was killed by one. */\n readonly exitSignal?: string | null;\n /** The last (bounded) stderr lines of the child. */\n readonly stderrTail?: string;\n\n constructor(\n message: string,\n details: {\n exitCode?: number | null;\n exitSignal?: string | null;\n stderrTail?: string;\n cause?: unknown;\n } = {},\n ) {\n super(message, {\n ...(details.cause !== undefined ? { cause: details.cause } : {}),\n });\n if (details.exitCode !== undefined) this.exitCode = details.exitCode;\n if (details.exitSignal !== undefined) this.exitSignal = details.exitSignal;\n if (details.stderrTail !== undefined) this.stderrTail = details.stderrTail;\n }\n}\n\nfunction isExecutableFile(path: string): boolean {\n try {\n if (!statSync(path).isFile()) return false;\n accessSync(path, constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve `command` to an absolute executable path. Throws `AcpAgentSpawnError` before anything is\n * spawned when the command is a relative path, when `PATH` holds a relative or empty entry, or when\n * nothing executable is found. Only the `PATH` of the supplied `env` is read, never `process.env`.\n */\nexport function resolveCommand(command: string, env: Record<string, string>): string {\n if (command.length === 0) throw new AcpAgentSpawnError(\"ACP agent command is empty\");\n if (isAbsolute(command)) {\n if (isExecutableFile(command)) return command;\n throw new AcpAgentSpawnError(`ACP agent command not found or not executable: ${command}`);\n }\n if (command.includes(\"/\") || command.includes(\"\\\\\")) {\n throw new AcpAgentSpawnError(\n `ACP agent command \"${command}\" is a relative path; use an absolute path or a bare command name`,\n );\n }\n return resolveOnPath(command, env.PATH ?? \"\");\n}\n\nfunction resolveOnPath(command: string, pathValue: string): string {\n const entries = pathValue.split(delimiter);\n if (entries.some((entry) => entry === \"\" || !isAbsolute(entry))) {\n throw new AcpAgentSpawnError(\n `refusing to resolve \"${command}\": PATH has a relative or empty entry`,\n );\n }\n const found = entries.map((entry) => join(entry, command)).find(isExecutableFile);\n if (found === undefined) {\n throw new AcpAgentSpawnError(`ACP agent command not found on PATH: ${command}`);\n }\n return found;\n}\n\n/** A spawned child with bounded stderr capture and an exit promise. */\nexport interface AgentChild {\n readonly process: ChildProcess;\n /** Resolves once, when the child has exited. Never rejects. */\n readonly exited: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;\n /** The last stderr lines, joined by newlines. */\n stderrTail(): string;\n /** Terminate the child (its process group on POSIX) and wait for it to exit. */\n kill(): Promise<void>;\n hasExited(): boolean;\n}\n\nfunction trackStderr(child: ChildProcess): () => string {\n const lines: string[] = [];\n let partial = \"\";\n const push = (line: string): void => {\n lines.push(line.slice(0, STDERR_MAX_LINE_CHARS));\n if (lines.length > STDERR_MAX_LINES) lines.shift();\n };\n child.stderr?.setEncoding(\"utf8\");\n child.stderr?.on(\"data\", (chunk: string) => {\n const parts = (partial + chunk).split(\"\\n\");\n partial = (parts.pop() ?? \"\").slice(-STDERR_MAX_LINE_CHARS);\n for (const part of parts) push(part);\n });\n return () =>\n (partial.length > 0 ? [...lines, partial] : lines).slice(-STDERR_MAX_LINES).join(\"\\n\");\n}\n\nfunction signalGroup(child: ChildProcess, signal: NodeJS.Signals): void {\n try {\n if (process.platform !== \"win32\" && child.pid !== undefined) process.kill(-child.pid, signal);\n else child.kill(signal);\n } catch {\n // the group or process is already gone\n }\n}\n\n/** Spawn the resolved command. Rejects with `AcpAgentSpawnError` when the OS refuses to start it. */\nexport function spawnAgentChild(\n file: string,\n args: readonly string[],\n options: { cwd: string; env: Record<string, string> },\n): Promise<AgentChild> {\n return new Promise((resolve, reject) => {\n const child = spawn(file, [...args], {\n cwd: options.cwd,\n env: options.env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n const stderrTail = trackStderr(child);\n let exitedFlag = false;\n const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((done) => {\n child.once(\"close\", (code, signal) => {\n exitedFlag = true;\n done({ code, signal });\n });\n child.once(\"error\", () => {\n if (child.pid === undefined) {\n exitedFlag = true;\n done({ code: null, signal: null });\n }\n });\n });\n child.once(\"error\", (err) => {\n if (child.pid === undefined) {\n reject(new AcpAgentSpawnError(`failed to spawn ${file}: ${err.message}`, { cause: err }));\n }\n });\n child.once(\"spawn\", () => {\n child.stdin?.on(\"error\", () => {});\n resolve({\n process: child,\n exited,\n stderrTail,\n hasExited: () => exitedFlag,\n async kill() {\n if (!exitedFlag) {\n signalGroup(child, \"SIGTERM\");\n const timer = setTimeout(() => signalGroup(child, \"SIGKILL\"), KILL_GRACE_MS);\n await exited;\n clearTimeout(timer);\n }\n // Descendants may outlive the leader; sweep the group once more.\n signalGroup(child, \"SIGKILL\");\n },\n });\n });\n });\n}\n","/**\n * `@theokit/acp/client` — drive another ACP agent over stdio.\n *\n * ```ts\n * import { connectAcpAgent } from \"@theokit/acp/client\";\n *\n * const agent = await connectAcpAgent({\n * command: \"/usr/local/bin/my-agent\",\n * cwd: process.cwd(),\n * env: { PATH: \"/usr/bin\" },\n * onPermission: async (req) => ({ outcome: { outcome: \"cancelled\" } }),\n * });\n * for await (const update of agent.prompt(\"hello\")) console.log(update.update);\n * await agent.close();\n * ```\n *\n * @packageDocumentation\n */\n\nimport { Readable, Writable } from \"node:stream\";\nimport * as acp from \"@agentclientprotocol/sdk\";\nimport {\n AcpAgentSpawnError,\n type AgentChild,\n resolveCommand,\n spawnAgentChild,\n} from \"./client-spawn.js\";\n\nexport { AcpAgentSpawnError } from \"./client-spawn.js\";\n\nconst DEFAULT_INITIALIZE_TIMEOUT_MS = 10_000;\n/** How long to wait for the child's exit event after a broken pipe, to learn its exit code. */\nconst EXIT_SETTLE_MS = 1_000;\n\n/**\n * Options for {@link connectAcpAgent}.\n *\n * @public\n */\nexport interface ConnectAcpAgentOptions {\n /** Absolute path, or a bare name resolved on absolute `PATH` entries of `env` only. */\n command: string;\n args?: readonly string[];\n cwd: string;\n /** Passed to the child as is. Nothing is inherited from `process.env`. */\n env: Record<string, string>;\n /** Answers the agent's `session/request_permission`. */\n onPermission(request: acp.RequestPermissionRequest): Promise<acp.RequestPermissionResponse>;\n /** Budget for the `initialize` + `session/new` handshake. Default 10_000. */\n initializeTimeoutMs?: number;\n}\n\n/**\n * A live connection to a spawned ACP agent with one open session.\n *\n * @public\n */\nexport interface AcpAgentConnection {\n /**\n * Send one prompt and stream the session updates it produces. Only one prompt may be in flight.\n * Aborting `signal` sends `session/cancel`. A child exiting mid-prompt ends the iterator with\n * `AcpAgentSpawnError`.\n */\n prompt(text: string, signal?: AbortSignal): AsyncIterable<acp.SessionNotification>;\n /** Ends the session and kills the child (its process group on POSIX). Idempotent. */\n close(): Promise<void>;\n}\n\nclass UpdateQueue {\n private items: acp.SessionNotification[] = [];\n private waiter: (() => void) | undefined;\n private done = false;\n private failure: unknown;\n\n push(item: acp.SessionNotification): void {\n this.items.push(item);\n this.wake();\n }\n\n end(failure?: unknown): void {\n if (this.done) return;\n this.done = true;\n this.failure = failure;\n this.wake();\n }\n\n private wake(): void {\n const w = this.waiter;\n this.waiter = undefined;\n w?.();\n }\n\n async *drain(): AsyncGenerator<acp.SessionNotification> {\n for (;;) {\n const next = this.items.shift();\n if (next !== undefined) {\n yield next;\n continue;\n }\n if (this.done) {\n if (this.failure !== undefined) throw this.failure;\n return;\n }\n await new Promise<void>((resolve) => {\n this.waiter = resolve;\n });\n }\n }\n}\n\nconst delay = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, ms).unref();\n });\n\nasync function exitError(child: AgentChild, phase: string, cause?: unknown): Promise<Error> {\n const result = await Promise.race([child.exited, delay(EXIT_SETTLE_MS)]);\n const tail = child.stderrTail();\n const stderrPart = tail.length > 0 ? `; stderr:\\n${tail}` : \"\";\n if (result === undefined) {\n return new AcpAgentSpawnError(`ACP agent connection failed ${phase}${stderrPart}`, {\n stderrTail: tail,\n cause,\n });\n }\n const how = result.signal !== null ? `signal ${result.signal}` : `code ${result.code}`;\n return new AcpAgentSpawnError(`ACP agent exited ${phase} (${how})${stderrPart}`, {\n exitCode: result.code,\n exitSignal: result.signal,\n stderrTail: tail,\n cause,\n });\n}\n\nclass Connection implements AcpAgentConnection {\n private active: UpdateQueue | undefined;\n private closing: Promise<void> | undefined;\n private closed = false;\n\n constructor(\n private readonly child: AgentChild,\n private readonly conn: acp.ClientSideConnection,\n private readonly sessionId: string,\n ) {}\n\n /** @internal */\n dispatch(update: acp.SessionNotification): void {\n if (update.sessionId === this.sessionId) this.active?.push(update);\n }\n\n prompt(text: string, signal?: AbortSignal): AsyncIterable<acp.SessionNotification> {\n return this.run(text, signal);\n }\n\n private async *run(text: string, signal?: AbortSignal): AsyncGenerator<acp.SessionNotification> {\n if (this.closed) throw new AcpAgentSpawnError(\"ACP agent connection is closed\");\n if (this.active !== undefined)\n throw new Error(\"a prompt is already in flight on this connection\");\n const queue = new UpdateQueue();\n this.active = queue;\n const onAbort = (): void => {\n this.conn.cancel({ sessionId: this.sessionId }).catch(() => {});\n };\n if (signal?.aborted) onAbort();\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const exitWatch = this.child.exited.then(async () => {\n if (this.closed) return;\n queue.end(await exitError(this.child, \"during prompt\"));\n });\n void exitWatch;\n this.conn.prompt({ sessionId: this.sessionId, prompt: [{ type: \"text\", text }] }).then(\n // Let notifications already read from the pipe reach the queue first.\n () => new Promise<void>((resolve) => setImmediate(resolve)).then(() => queue.end()),\n async (err: unknown) => {\n queue.end(this.closed ? undefined : await exitError(this.child, \"during prompt\", err));\n },\n );\n try {\n yield* queue.drain();\n } finally {\n signal?.removeEventListener(\"abort\", onAbort);\n if (this.active === queue) this.active = undefined;\n }\n }\n\n close(): Promise<void> {\n this.closed = true;\n this.closing ??= this.child.kill().then(() => this.active?.end());\n return this.closing;\n }\n}\n\nasync function handshake(conn: acp.ClientSideConnection, cwd: string): Promise<string> {\n await conn.initialize({ protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });\n const session = await conn.newSession({ cwd, mcpServers: [] });\n return session.sessionId;\n}\n\nasync function initialize(\n child: AgentChild,\n conn: acp.ClientSideConnection,\n options: ConnectAcpAgentOptions,\n): Promise<string> {\n const timeoutMs = options.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS;\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new AcpAgentSpawnError(`ACP agent did not initialize within ${timeoutMs}ms`)),\n timeoutMs,\n );\n });\n const exit = child.exited.then(() =>\n exitError(child, \"during initialize\").then((e) => Promise.reject(e)),\n );\n try {\n return await Promise.race([handshake(conn, options.cwd), timeout, exit]);\n } catch (err) {\n if (err instanceof AcpAgentSpawnError) throw err;\n throw await exitError(child, \"during initialize\", err);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\n/**\n * Spawn an ACP agent as a child process, complete the handshake and open one session.\n *\n * @throws AcpAgentSpawnError when the command is refused, cannot be started, or exits or stalls\n * during initialize.\n * @public\n */\nexport async function connectAcpAgent(\n options: ConnectAcpAgentOptions,\n): Promise<AcpAgentConnection> {\n const file = resolveCommand(options.command, options.env);\n const child = await spawnAgentChild(file, options.args ?? [], {\n cwd: options.cwd,\n env: options.env,\n });\n const stdin = child.process.stdin;\n const stdout = child.process.stdout;\n if (stdin === null || stdout === null) {\n await child.kill();\n throw new AcpAgentSpawnError(\"ACP agent child has no stdio pipes\");\n }\n const stream = acp.ndJsonStream(\n Writable.toWeb(stdin) as WritableStream<Uint8Array>,\n Readable.toWeb(stdout) as ReadableStream<Uint8Array>,\n );\n let connection: Connection | undefined;\n const conn = new acp.ClientSideConnection(\n () => ({\n requestPermission: (request) => options.onPermission(request),\n sessionUpdate: async (update) => {\n connection?.dispatch(update);\n },\n }),\n stream,\n );\n try {\n const sessionId = await initialize(child, conn, options);\n connection = new Connection(child, conn, sessionId);\n return connection;\n } catch (err) {\n await child.kill();\n throw err;\n }\n}\n"]}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import * as acp from '@agentclientprotocol/sdk';
|
|
2
|
+
import { TheokitAgentError } from '@theokit/sdk';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Command resolution and child-process handling for `connectAcpAgent`.
|
|
6
|
+
*
|
|
7
|
+
* @internal
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A child agent could not be started, was refused before starting, or exited before it finished
|
|
12
|
+
* what it was asked to do.
|
|
13
|
+
*
|
|
14
|
+
* @public
|
|
15
|
+
*/
|
|
16
|
+
declare class AcpAgentSpawnError extends TheokitAgentError {
|
|
17
|
+
readonly name: string;
|
|
18
|
+
/** Exit code of the child, when it exited with one. */
|
|
19
|
+
readonly exitCode?: number | null;
|
|
20
|
+
/** Signal that ended the child, when it was killed by one. */
|
|
21
|
+
readonly exitSignal?: string | null;
|
|
22
|
+
/** The last (bounded) stderr lines of the child. */
|
|
23
|
+
readonly stderrTail?: string;
|
|
24
|
+
constructor(message: string, details?: {
|
|
25
|
+
exitCode?: number | null;
|
|
26
|
+
exitSignal?: string | null;
|
|
27
|
+
stderrTail?: string;
|
|
28
|
+
cause?: unknown;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* `@theokit/acp/client` — drive another ACP agent over stdio.
|
|
34
|
+
*
|
|
35
|
+
* ```ts
|
|
36
|
+
* import { connectAcpAgent } from "@theokit/acp/client";
|
|
37
|
+
*
|
|
38
|
+
* const agent = await connectAcpAgent({
|
|
39
|
+
* command: "/usr/local/bin/my-agent",
|
|
40
|
+
* cwd: process.cwd(),
|
|
41
|
+
* env: { PATH: "/usr/bin" },
|
|
42
|
+
* onPermission: async (req) => ({ outcome: { outcome: "cancelled" } }),
|
|
43
|
+
* });
|
|
44
|
+
* for await (const update of agent.prompt("hello")) console.log(update.update);
|
|
45
|
+
* await agent.close();
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* @packageDocumentation
|
|
49
|
+
*/
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Options for {@link connectAcpAgent}.
|
|
53
|
+
*
|
|
54
|
+
* @public
|
|
55
|
+
*/
|
|
56
|
+
interface ConnectAcpAgentOptions {
|
|
57
|
+
/** Absolute path, or a bare name resolved on absolute `PATH` entries of `env` only. */
|
|
58
|
+
command: string;
|
|
59
|
+
args?: readonly string[];
|
|
60
|
+
cwd: string;
|
|
61
|
+
/** Passed to the child as is. Nothing is inherited from `process.env`. */
|
|
62
|
+
env: Record<string, string>;
|
|
63
|
+
/** Answers the agent's `session/request_permission`. */
|
|
64
|
+
onPermission(request: acp.RequestPermissionRequest): Promise<acp.RequestPermissionResponse>;
|
|
65
|
+
/** Budget for the `initialize` + `session/new` handshake. Default 10_000. */
|
|
66
|
+
initializeTimeoutMs?: number;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* A live connection to a spawned ACP agent with one open session.
|
|
70
|
+
*
|
|
71
|
+
* @public
|
|
72
|
+
*/
|
|
73
|
+
interface AcpAgentConnection {
|
|
74
|
+
/**
|
|
75
|
+
* Send one prompt and stream the session updates it produces. Only one prompt may be in flight.
|
|
76
|
+
* Aborting `signal` sends `session/cancel`. A child exiting mid-prompt ends the iterator with
|
|
77
|
+
* `AcpAgentSpawnError`.
|
|
78
|
+
*/
|
|
79
|
+
prompt(text: string, signal?: AbortSignal): AsyncIterable<acp.SessionNotification>;
|
|
80
|
+
/** Ends the session and kills the child (its process group on POSIX). Idempotent. */
|
|
81
|
+
close(): Promise<void>;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Spawn an ACP agent as a child process, complete the handshake and open one session.
|
|
85
|
+
*
|
|
86
|
+
* @throws AcpAgentSpawnError when the command is refused, cannot be started, or exits or stalls
|
|
87
|
+
* during initialize.
|
|
88
|
+
* @public
|
|
89
|
+
*/
|
|
90
|
+
declare function connectAcpAgent(options: ConnectAcpAgentOptions): Promise<AcpAgentConnection>;
|
|
91
|
+
|
|
92
|
+
export { type AcpAgentConnection, AcpAgentSpawnError, type ConnectAcpAgentOptions, connectAcpAgent };
|