@acryldev/driver-acp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +52 -2
- package/chat.ts +258 -0
- package/connection.ts +239 -0
- package/index.ts +67 -0
- package/lib/index.js +440 -0
- package/lib/index.js.map +1 -0
- package/lib/types/chat.d.ts +27 -0
- package/lib/types/connection.d.ts +30 -0
- package/lib/types/index.d.ts +27 -0
- package/lib/types/tsdown.config.d.ts +2 -0
- package/package.json +49 -3
- package/plugin.json +15 -0
- package/provenance.json +20 -0
- package/test/acp-v1/LICENSE +191 -0
- package/test/acp-v1/schema.json +6074 -0
- package/test/conformance.test.ts +203 -0
- package/test/driver-acp.test.ts +338 -0
- package/test/fake-agent.mjs +143 -0
- package/tsconfig.json +21 -0
- package/tsdown.config.ts +23 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 acrylblends
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
#
|
|
1
|
+
# driver-acp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Any agent that speaks the [Agent Client Protocol](https://agentclientprotocol.com) (ACP) as a chat in the agent panel (M8, spec 046 T028).
|
|
4
|
+
The agent runs in the app folder and acts through the door, as the panel's other agents do. An agent needs no code here: it is a preset,
|
|
5
|
+
the command line that starts its ACP server. DeepSeek Harness is the first one, and other ACP agents are added by config.
|
|
6
|
+
|
|
7
|
+
```yaml
|
|
8
|
+
- id: agent-panel
|
|
9
|
+
name: agent-panel
|
|
10
|
+
- id: driver-acp
|
|
11
|
+
name: driver-acp
|
|
12
|
+
config:
|
|
13
|
+
agents: # replaces the presets; default: the presets whose command is on the PATH
|
|
14
|
+
dsh: { command: dsh, args: [--profile, acp] }
|
|
15
|
+
permissions: reject # or allow: the answer to the agent's permission requests
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The row goes after the panel's, injects `drivers` and `appInstance`, and stays PENDING without the panel. Each agent becomes the
|
|
19
|
+
panel driver `acp:<name>`. An agent whose command is not on the PATH gets no driver, and the plugin logs one line saying why. With
|
|
20
|
+
`NODE_ENV=production` or `ACRYL_DOOR=off` the plugin starts nothing.
|
|
21
|
+
|
|
22
|
+
## How it talks
|
|
23
|
+
|
|
24
|
+
ACP v1 over the agent's stdin and stdout, as newline-delimited JSON-RPC 2.0 (`connection.ts`). At the first message the driver starts the
|
|
25
|
+
agent, sends `initialize` and `session/new` with the app folder as `cwd`, and keeps that session, so later messages continue the
|
|
26
|
+
conversation. Each message is one `session/prompt`. Stop sends `session/cancel`. The client offers no file system or terminal
|
|
27
|
+
capabilities, so the agent uses its own tools. A `session/request_permission` gets the agent's own "reject once" option, or "allow once"
|
|
28
|
+
with `permissions: allow`.
|
|
29
|
+
|
|
30
|
+
What the panel shows (`chat.ts`):
|
|
31
|
+
|
|
32
|
+
- each `agent_message_chunk` as text;
|
|
33
|
+
- each tool call once, when it completes or fails: its title, its input, and its result or error;
|
|
34
|
+
- an error when a turn stops short (`refusal`, `max_tokens`, `max_turn_requests`) or the agent ends.
|
|
35
|
+
|
|
36
|
+
Thoughts and plans stay out of the chat.
|
|
37
|
+
|
|
38
|
+
## Processes
|
|
39
|
+
|
|
40
|
+
Every agent process is started inside one `ctx.effect`. Its disposer closes the agent's stdin, then sends SIGTERM, then kills it (the
|
|
41
|
+
whole process tree on Windows), and waits until it is gone. Unloading or reloading the plugin leaves no agent running. An agent that ended
|
|
42
|
+
on its own is started again, with a new session, at the next message.
|
|
43
|
+
|
|
44
|
+
## Provenance
|
|
45
|
+
|
|
46
|
+
The client is written from the ACP v1 specification, not ported from an SDK: the official SDK (`@agentclientprotocol/sdk`) is 8 MB with
|
|
47
|
+
two required peers, too much for a plugin copied into every app. To keep it honest, `test/conformance.test.ts` checks every message of a
|
|
48
|
+
session, sent and received, against the official ACP v1 JSON schema. The schema is vendored unmodified in `test/acp-v1/` with its Apache-2.0
|
|
49
|
+
license. It comes from `@agentclientprotocol/sdk@2.0.2` (`schema/v1/schema.json`); the version, source and checksum are in
|
|
50
|
+
`provenance.json`. To follow a newer schema, replace the file, update `provenance.json`, and run the test.
|
|
51
|
+
|
|
52
|
+
Checked live: `node scripts/verify-agent-panel.mjs --driver acp:dsh` (dsh on the PATH, a DeepSeek key) builds `/hello` from the panel
|
|
53
|
+
through `dsh --profile acp`.
|
package/chat.ts
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An ACP agent as a chat driver of the panel. The agent process starts at the first message and keeps one ACP session, so later messages continue the same conversation;
|
|
3
|
+
* an agent that ended is started again, with a new session, at the next message. One message runs at a time; a second one waits for the first.
|
|
4
|
+
*
|
|
5
|
+
* What the panel gets from the ACP updates: the agent's message chunks as `text`, each finished tool call as one `tool` (its title, input, and result or error), and an
|
|
6
|
+
* `error` for a turn that stopped short (a refusal, a token or request limit, an agent that ended). Thoughts, plans and the rest stay out of the chat.
|
|
7
|
+
*/
|
|
8
|
+
import type { ChatDriver, ChatEvent } from '@acryldev/drivers'
|
|
9
|
+
import { type AcpAgent, type AcpConnection, AcpError } from './connection.ts'
|
|
10
|
+
|
|
11
|
+
/** Which answer a permission request gets: the agent's own "allow once" or "reject once" option. */
|
|
12
|
+
export type AcpPermissions = 'allow' | 'reject'
|
|
13
|
+
|
|
14
|
+
/** The ACP version this client speaks. */
|
|
15
|
+
const PROTOCOL_VERSION = 1
|
|
16
|
+
|
|
17
|
+
/** An agent connection with its session. */
|
|
18
|
+
interface Session {
|
|
19
|
+
readonly connection: AcpConnection
|
|
20
|
+
readonly id: string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Opens a connection to the agent and returns it with the function that closes it. The plugin acquires it inside one `ctx.effect`, so unloading the plugin ends the process.
|
|
25
|
+
*/
|
|
26
|
+
export type OpenAgent = (
|
|
27
|
+
agent: AcpAgent,
|
|
28
|
+
handle: (method: string, params: unknown) => unknown,
|
|
29
|
+
) => {
|
|
30
|
+
connection: AcpConnection
|
|
31
|
+
close(): Promise<void>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface ToolUpdate {
|
|
35
|
+
toolCallId: string
|
|
36
|
+
title?: string | null
|
|
37
|
+
status?: string | null
|
|
38
|
+
rawInput?: unknown
|
|
39
|
+
rawOutput?: unknown
|
|
40
|
+
content?: Array<{ type?: string; content?: { type?: string; text?: string } }> | null
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Why a turn stopped short, in the panel's words; `undefined` for a turn that ended normally or was cancelled. */
|
|
44
|
+
function stopMessage(name: string, stopReason: unknown): string | undefined {
|
|
45
|
+
switch (stopReason) {
|
|
46
|
+
case 'end_turn':
|
|
47
|
+
case 'cancelled':
|
|
48
|
+
return undefined
|
|
49
|
+
case 'refusal':
|
|
50
|
+
return `${name} refused to continue`
|
|
51
|
+
case 'max_tokens':
|
|
52
|
+
return `${name} stopped at its token limit`
|
|
53
|
+
case 'max_turn_requests':
|
|
54
|
+
return `${name} stopped at its limit of model requests for one message`
|
|
55
|
+
default:
|
|
56
|
+
return `${name} stopped (${String(stopReason)})`
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The text an ACP tool call produced, when it reports text content and no raw output. */
|
|
61
|
+
function toolText(update: ToolUpdate): string | undefined {
|
|
62
|
+
const text = (update.content ?? [])
|
|
63
|
+
.map((item) =>
|
|
64
|
+
item.type === 'content' && item.content?.type === 'text' ? item.content.text : undefined,
|
|
65
|
+
)
|
|
66
|
+
.filter((part): part is string => typeof part === 'string')
|
|
67
|
+
.join('\n')
|
|
68
|
+
return text || undefined
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The answer to `session/request_permission`: the agent's option of the wanted kind, or `cancelled` when it offers none or the turn was cancelled. */
|
|
72
|
+
function permissionAnswer(
|
|
73
|
+
params: unknown,
|
|
74
|
+
permissions: AcpPermissions,
|
|
75
|
+
cancelled: boolean,
|
|
76
|
+
): unknown {
|
|
77
|
+
const options = ((params as { options?: Array<{ optionId: string; kind: string }> }).options ??
|
|
78
|
+
[]) as Array<{ optionId: string; kind: string }>
|
|
79
|
+
const wanted =
|
|
80
|
+
permissions === 'allow' ? ['allow_once', 'allow_always'] : ['reject_once', 'reject_always']
|
|
81
|
+
const option = cancelled
|
|
82
|
+
? undefined
|
|
83
|
+
: wanted.map((kind) => options.find((o) => o.kind === kind)).find(Boolean)
|
|
84
|
+
return {
|
|
85
|
+
outcome: option ? { outcome: 'selected', optionId: option.optionId } : { outcome: 'cancelled' },
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function acpDriver(options: {
|
|
90
|
+
/** The driver's name in the panel (`acp:dsh`). */
|
|
91
|
+
name: string
|
|
92
|
+
agent: AcpAgent
|
|
93
|
+
/** The app folder: the agent's working directory and its session's `cwd`. */
|
|
94
|
+
cwd: string
|
|
95
|
+
permissions: AcpPermissions
|
|
96
|
+
open: OpenAgent
|
|
97
|
+
}): ChatDriver {
|
|
98
|
+
const { name, agent, cwd, permissions, open } = options
|
|
99
|
+
let session: Promise<Session> | undefined
|
|
100
|
+
/** The connection `session` belongs to, so only its own end clears it. */
|
|
101
|
+
let live: AcpConnection | undefined
|
|
102
|
+
let turnCancelled = false
|
|
103
|
+
let queue: Promise<void> = Promise.resolve()
|
|
104
|
+
|
|
105
|
+
const startSession = async (): Promise<Session> => {
|
|
106
|
+
const { connection, close } = open(agent, (method, params) => {
|
|
107
|
+
if (method === 'session/request_permission')
|
|
108
|
+
return permissionAnswer(params, permissions, turnCancelled)
|
|
109
|
+
throw new AcpError(`${method} is not offered by this client`, -32601)
|
|
110
|
+
})
|
|
111
|
+
// An agent that ends is started again at the next message.
|
|
112
|
+
live = connection
|
|
113
|
+
void connection.ended.then(() => {
|
|
114
|
+
if (live !== connection) return
|
|
115
|
+
live = undefined
|
|
116
|
+
session = undefined
|
|
117
|
+
})
|
|
118
|
+
try {
|
|
119
|
+
await connection.request('initialize', {
|
|
120
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
121
|
+
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
|
122
|
+
clientInfo: { name: 'acrylblends-driver-acp', version: '1' },
|
|
123
|
+
})
|
|
124
|
+
const created = await connection.request<{ sessionId: string }>('session/new', {
|
|
125
|
+
cwd,
|
|
126
|
+
mcpServers: [],
|
|
127
|
+
})
|
|
128
|
+
return { connection, id: created.sessionId }
|
|
129
|
+
} catch (error) {
|
|
130
|
+
await close()
|
|
131
|
+
throw error
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
kind: 'chat',
|
|
137
|
+
name,
|
|
138
|
+
async *start({ message, signal }) {
|
|
139
|
+
// One message at a time: this one waits for the one before it.
|
|
140
|
+
const previous = queue
|
|
141
|
+
let finished!: () => void
|
|
142
|
+
queue = new Promise((resolve) => (finished = resolve))
|
|
143
|
+
try {
|
|
144
|
+
await previous
|
|
145
|
+
if (signal.aborted) return
|
|
146
|
+
let current: Session
|
|
147
|
+
try {
|
|
148
|
+
session ??= startSession()
|
|
149
|
+
current = await session
|
|
150
|
+
} catch (error) {
|
|
151
|
+
session = undefined
|
|
152
|
+
yield {
|
|
153
|
+
event: 'error',
|
|
154
|
+
data: { message: error instanceof Error ? error.message : String(error) },
|
|
155
|
+
}
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
yield* turn(current, message, signal)
|
|
159
|
+
} finally {
|
|
160
|
+
finished()
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function* turn(
|
|
166
|
+
current: Session,
|
|
167
|
+
message: string,
|
|
168
|
+
signal: AbortSignal,
|
|
169
|
+
): AsyncGenerator<ChatEvent> {
|
|
170
|
+
const events: ChatEvent[] = []
|
|
171
|
+
let wake: (() => void) | undefined
|
|
172
|
+
let settled = false
|
|
173
|
+
const push = (event: ChatEvent): void => {
|
|
174
|
+
events.push(event)
|
|
175
|
+
wake?.()
|
|
176
|
+
}
|
|
177
|
+
/** What earlier updates said about each tool call: its title and its input arrive before its result. */
|
|
178
|
+
const calls = new Map<string, { title?: string; input?: unknown }>()
|
|
179
|
+
const off = current.connection.onNotification((method, params) => {
|
|
180
|
+
const { sessionId, update } = params as {
|
|
181
|
+
sessionId?: string
|
|
182
|
+
update?: { sessionUpdate?: string } & ToolUpdate & { content?: unknown }
|
|
183
|
+
}
|
|
184
|
+
if (method !== 'session/update' || sessionId !== current.id || !update) return
|
|
185
|
+
if (update.sessionUpdate === 'agent_message_chunk') {
|
|
186
|
+
const content = update.content as { type?: string; text?: string } | undefined
|
|
187
|
+
if (content?.type === 'text' && content.text)
|
|
188
|
+
push({ event: 'text', data: { text: content.text } })
|
|
189
|
+
return
|
|
190
|
+
}
|
|
191
|
+
if (update.sessionUpdate !== 'tool_call' && update.sessionUpdate !== 'tool_call_update')
|
|
192
|
+
return
|
|
193
|
+
const call = calls.get(update.toolCallId) ?? {}
|
|
194
|
+
if (update.title) call.title = update.title
|
|
195
|
+
if (update.rawInput !== undefined) call.input = update.rawInput
|
|
196
|
+
calls.set(update.toolCallId, call)
|
|
197
|
+
if (update.status !== 'completed' && update.status !== 'failed') return
|
|
198
|
+
const tool = call.title ?? update.toolCallId
|
|
199
|
+
const output = update.rawOutput ?? toolText(update)
|
|
200
|
+
push({
|
|
201
|
+
event: 'tool',
|
|
202
|
+
data: {
|
|
203
|
+
tool,
|
|
204
|
+
...(call.input === undefined ? {} : { input: call.input }),
|
|
205
|
+
...(update.status === 'failed'
|
|
206
|
+
? {
|
|
207
|
+
error:
|
|
208
|
+
output === undefined
|
|
209
|
+
? 'failed'
|
|
210
|
+
: String(typeof output === 'string' ? output : JSON.stringify(output)),
|
|
211
|
+
}
|
|
212
|
+
: { result: output }),
|
|
213
|
+
},
|
|
214
|
+
})
|
|
215
|
+
})
|
|
216
|
+
turnCancelled = false
|
|
217
|
+
const cancel = (): void => {
|
|
218
|
+
turnCancelled = true
|
|
219
|
+
current.connection.notify('session/cancel', { sessionId: current.id })
|
|
220
|
+
}
|
|
221
|
+
signal.addEventListener('abort', cancel, { once: true })
|
|
222
|
+
current.connection
|
|
223
|
+
.request<{ stopReason?: unknown }>('session/prompt', {
|
|
224
|
+
sessionId: current.id,
|
|
225
|
+
prompt: [{ type: 'text', text: message }],
|
|
226
|
+
})
|
|
227
|
+
.then(
|
|
228
|
+
(result) => {
|
|
229
|
+
const stopped = signal.aborted ? undefined : stopMessage(name, result.stopReason)
|
|
230
|
+
if (stopped) push({ event: 'error', data: { message: stopped } })
|
|
231
|
+
},
|
|
232
|
+
(error: unknown) => {
|
|
233
|
+
if (!signal.aborted)
|
|
234
|
+
push({
|
|
235
|
+
event: 'error',
|
|
236
|
+
data: { message: error instanceof Error ? error.message : String(error) },
|
|
237
|
+
})
|
|
238
|
+
},
|
|
239
|
+
)
|
|
240
|
+
.finally(() => {
|
|
241
|
+
settled = true
|
|
242
|
+
wake?.()
|
|
243
|
+
})
|
|
244
|
+
try {
|
|
245
|
+
for (;;) {
|
|
246
|
+
const next = events.shift()
|
|
247
|
+
if (next) yield next
|
|
248
|
+
else if (settled) return
|
|
249
|
+
else await new Promise<void>((resolve) => (wake = resolve))
|
|
250
|
+
}
|
|
251
|
+
} finally {
|
|
252
|
+
off()
|
|
253
|
+
signal.removeEventListener('abort', cancel)
|
|
254
|
+
// The panel stopped reading before the turn ended: the agent is told to stop it.
|
|
255
|
+
if (!settled) cancel()
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
package/connection.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One ACP agent process and the JSON-RPC 2.0 connection to it: newline-delimited messages over its stdin and stdout (the ACP stdio transport). The driver needs a handful of
|
|
3
|
+
* calls, so this is the whole client: requests with their answers, notifications both ways, and the agent's own requests answered by a handler. `close()` ends the process
|
|
4
|
+
* the way an ACP agent expects: stdin closed first, then SIGTERM, then a hard kill, and it resolves only once the process is gone.
|
|
5
|
+
*/
|
|
6
|
+
import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from 'node:child_process'
|
|
7
|
+
|
|
8
|
+
/** How to start an ACP agent: a program and its arguments, and what to add to the app's environment. */
|
|
9
|
+
export interface AcpAgent {
|
|
10
|
+
readonly command: string
|
|
11
|
+
readonly args: readonly string[]
|
|
12
|
+
readonly env?: Readonly<Record<string, string>>
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** An error the agent answered with, or the reason the connection ended. */
|
|
16
|
+
export class AcpError extends Error {
|
|
17
|
+
/** The JSON-RPC error code, for an error the agent answered with. */
|
|
18
|
+
readonly code: number | undefined
|
|
19
|
+
|
|
20
|
+
constructor(message: string, code?: number) {
|
|
21
|
+
super(message)
|
|
22
|
+
this.name = 'AcpError'
|
|
23
|
+
this.code = code
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Answers a request the agent sends (`session/request_permission`); throwing answers with an error. */
|
|
28
|
+
export type AgentRequestHandler = (method: string, params: unknown) => unknown
|
|
29
|
+
|
|
30
|
+
/** How long each step of `close()` waits before the next, harder one. */
|
|
31
|
+
const GRACE_MS = 2000
|
|
32
|
+
/** The most of the agent's stderr kept, to say why it ended. */
|
|
33
|
+
const STDERR_TAIL = 4000
|
|
34
|
+
|
|
35
|
+
interface Pending {
|
|
36
|
+
resolve(value: unknown): void
|
|
37
|
+
reject(error: Error): void
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export class AcpConnection {
|
|
41
|
+
readonly #child: ChildProcessWithoutNullStreams
|
|
42
|
+
readonly #pending = new Map<number, Pending>()
|
|
43
|
+
readonly #listeners = new Set<(method: string, params: unknown) => void>()
|
|
44
|
+
#nextId = 1
|
|
45
|
+
#buffer = ''
|
|
46
|
+
#stderr = ''
|
|
47
|
+
#ended: AcpError | undefined
|
|
48
|
+
/** Resolves with the reason once the process is gone. */
|
|
49
|
+
readonly ended: Promise<AcpError>
|
|
50
|
+
|
|
51
|
+
constructor(agent: AcpAgent, cwd: string, handle: AgentRequestHandler) {
|
|
52
|
+
this.#child = spawn(agent.command, [...agent.args], {
|
|
53
|
+
cwd,
|
|
54
|
+
env: { ...process.env, ...agent.env },
|
|
55
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
56
|
+
// An npm-installed agent is a `.cmd` shim on Windows, which only a shell can start.
|
|
57
|
+
shell: process.platform === 'win32',
|
|
58
|
+
// Its own process group on POSIX, so closing the connection also ends what the agent started (its tools, a shell): nothing is left behind when the plugin unloads.
|
|
59
|
+
detached: process.platform !== 'win32',
|
|
60
|
+
windowsHide: true,
|
|
61
|
+
})
|
|
62
|
+
this.ended = new Promise((resolve) => {
|
|
63
|
+
const end = (reason: AcpError): void => {
|
|
64
|
+
if (this.#ended) return
|
|
65
|
+
this.#ended = reason
|
|
66
|
+
for (const pending of this.#pending.values()) pending.reject(reason)
|
|
67
|
+
this.#pending.clear()
|
|
68
|
+
resolve(reason)
|
|
69
|
+
}
|
|
70
|
+
this.#child.on('error', (error) =>
|
|
71
|
+
end(new AcpError(`${agent.command} could not be started: ${error.message}`)),
|
|
72
|
+
)
|
|
73
|
+
this.#child.on('exit', (code, signal) => {
|
|
74
|
+
const tail = this.#stderr.trim().split('\n').slice(-3).join(' ').slice(-500)
|
|
75
|
+
end(
|
|
76
|
+
new AcpError(
|
|
77
|
+
`${agent.command} ended (${signal ?? `exit code ${String(code)}`})${tail ? `: ${tail}` : ''}`,
|
|
78
|
+
),
|
|
79
|
+
)
|
|
80
|
+
})
|
|
81
|
+
})
|
|
82
|
+
this.#child.stderr.setEncoding('utf8')
|
|
83
|
+
this.#child.stderr.on('data', (chunk: string) => {
|
|
84
|
+
this.#stderr = (this.#stderr + chunk).slice(-STDERR_TAIL)
|
|
85
|
+
})
|
|
86
|
+
this.#child.stdout.setEncoding('utf8')
|
|
87
|
+
this.#child.stdout.on('data', (chunk: string) => {
|
|
88
|
+
this.#buffer += chunk
|
|
89
|
+
for (let end = this.#buffer.indexOf('\n'); end !== -1; end = this.#buffer.indexOf('\n')) {
|
|
90
|
+
const line = this.#buffer.slice(0, end).trim()
|
|
91
|
+
this.#buffer = this.#buffer.slice(end + 1)
|
|
92
|
+
if (line) this.#receive(line, handle)
|
|
93
|
+
}
|
|
94
|
+
})
|
|
95
|
+
// A write after the agent went away fails here instead of throwing out of the process.
|
|
96
|
+
this.#child.stdin.on('error', () => {})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Sends a request and resolves with its result; rejects with the agent's error, or when the process ends first. */
|
|
100
|
+
request<T>(method: string, params: unknown): Promise<T> {
|
|
101
|
+
if (this.#ended) return Promise.reject(this.#ended)
|
|
102
|
+
const id = this.#nextId++
|
|
103
|
+
return new Promise<T>((resolve, reject) => {
|
|
104
|
+
this.#pending.set(id, { resolve: resolve as (value: unknown) => void, reject })
|
|
105
|
+
this.#send({ jsonrpc: '2.0', id, method, params })
|
|
106
|
+
})
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
notify(method: string, params: unknown): void {
|
|
110
|
+
if (!this.#ended) this.#send({ jsonrpc: '2.0', method, params })
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Hears every notification the agent sends; returns the function that stops listening. */
|
|
114
|
+
onNotification(listener: (method: string, params: unknown) => void): () => void {
|
|
115
|
+
this.#listeners.add(listener)
|
|
116
|
+
return () => void this.#listeners.delete(listener)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Ends the process and what it started: stdin closed, then SIGTERM, then a hard kill, each to the whole process group on POSIX (the tree, with `taskkill /T`, on Windows).
|
|
121
|
+
* Resolves once they are gone. Safe to call again, and after the agent ended on its own (its leftovers are still cleared).
|
|
122
|
+
*/
|
|
123
|
+
async close(): Promise<void> {
|
|
124
|
+
if (!this.#ended) {
|
|
125
|
+
const gone = (ms: number) =>
|
|
126
|
+
Promise.race([
|
|
127
|
+
this.ended.then(() => true),
|
|
128
|
+
new Promise<boolean>((done) => setTimeout(() => done(false), ms).unref()),
|
|
129
|
+
])
|
|
130
|
+
this.#child.stdin.end()
|
|
131
|
+
if (!(await gone(GRACE_MS))) {
|
|
132
|
+
this.#signal('SIGTERM')
|
|
133
|
+
if (!(await gone(GRACE_MS))) this.#signal('SIGKILL')
|
|
134
|
+
await this.ended
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
await this.#reapGroup()
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** A signal to the agent and, on POSIX, everything in its group. */
|
|
141
|
+
#signal(signal: 'SIGTERM' | 'SIGKILL'): void {
|
|
142
|
+
const pid = this.#child.pid
|
|
143
|
+
if (pid === undefined) return
|
|
144
|
+
if (process.platform === 'win32') {
|
|
145
|
+
if (signal === 'SIGKILL')
|
|
146
|
+
spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true })
|
|
147
|
+
else this.#child.kill(signal)
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
process.kill(-pid, signal)
|
|
152
|
+
} catch {
|
|
153
|
+
this.#child.kill(signal)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** On POSIX, processes the agent left in its group are ended too: SIGTERM, then SIGKILL after the grace. */
|
|
158
|
+
async #reapGroup(): Promise<void> {
|
|
159
|
+
const pid = this.#child.pid
|
|
160
|
+
if (process.platform === 'win32' || pid === undefined) return
|
|
161
|
+
const groupAlive = (): boolean => {
|
|
162
|
+
try {
|
|
163
|
+
process.kill(-pid, 0)
|
|
164
|
+
return true
|
|
165
|
+
} catch (error) {
|
|
166
|
+
return (error as NodeJS.ErrnoException).code === 'EPERM'
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
for (const signal of ['SIGTERM', 'SIGKILL'] as const) {
|
|
170
|
+
if (!groupAlive()) return
|
|
171
|
+
try {
|
|
172
|
+
process.kill(-pid, signal)
|
|
173
|
+
} catch {
|
|
174
|
+
return
|
|
175
|
+
}
|
|
176
|
+
for (let waited = 0; waited < GRACE_MS && groupAlive(); waited += 25)
|
|
177
|
+
await new Promise((done) => setTimeout(done, 25))
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
#send(message: unknown): void {
|
|
182
|
+
this.#child.stdin.write(`${JSON.stringify(message)}\n`)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
#receive(line: string, handle: AgentRequestHandler): void {
|
|
186
|
+
let message: {
|
|
187
|
+
id?: number | string
|
|
188
|
+
method?: string
|
|
189
|
+
params?: unknown
|
|
190
|
+
result?: unknown
|
|
191
|
+
error?: { code?: number; message?: string }
|
|
192
|
+
}
|
|
193
|
+
try {
|
|
194
|
+
message = JSON.parse(line)
|
|
195
|
+
} catch {
|
|
196
|
+
return // Not a protocol frame: an agent may print a stray line; it carries nothing to act on.
|
|
197
|
+
}
|
|
198
|
+
if (typeof message.method === 'string') {
|
|
199
|
+
if (message.id === undefined) {
|
|
200
|
+
for (const listener of this.#listeners) listener(message.method, message.params)
|
|
201
|
+
return
|
|
202
|
+
}
|
|
203
|
+
const id = message.id
|
|
204
|
+
Promise.resolve()
|
|
205
|
+
.then(() => handle(message.method as string, message.params))
|
|
206
|
+
.then(
|
|
207
|
+
(result) => this.#answer(id, result),
|
|
208
|
+
(error: unknown) =>
|
|
209
|
+
this.#send({
|
|
210
|
+
jsonrpc: '2.0',
|
|
211
|
+
id,
|
|
212
|
+
error:
|
|
213
|
+
error instanceof AcpError && error.code !== undefined
|
|
214
|
+
? { code: error.code, message: error.message }
|
|
215
|
+
: {
|
|
216
|
+
code: -32603,
|
|
217
|
+
message: error instanceof Error ? error.message : String(error),
|
|
218
|
+
},
|
|
219
|
+
}),
|
|
220
|
+
)
|
|
221
|
+
return
|
|
222
|
+
}
|
|
223
|
+
const pending = typeof message.id === 'number' ? this.#pending.get(message.id) : undefined
|
|
224
|
+
if (!pending) return
|
|
225
|
+
this.#pending.delete(message.id as number)
|
|
226
|
+
if (message.error)
|
|
227
|
+
pending.reject(
|
|
228
|
+
new AcpError(
|
|
229
|
+
message.error.message ?? 'the agent answered with an error',
|
|
230
|
+
message.error.code,
|
|
231
|
+
),
|
|
232
|
+
)
|
|
233
|
+
else pending.resolve(message.result)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
#answer(id: number | string, result: unknown): void {
|
|
237
|
+
if (!this.#ended) this.#send({ jsonrpc: '2.0', id, result: result ?? null })
|
|
238
|
+
}
|
|
239
|
+
}
|
package/index.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ACP driver (M8, spec 046 T028): any agent that speaks the Agent Client Protocol (ACP v1 over stdio) as a chat driver of the agent panel, started in the app folder.
|
|
3
|
+
* No agent gets code of its own here: an agent is a preset, a command line that starts its ACP server. `dsh` (DeepSeek Harness, `dsh --profile acp`) is the first preset;
|
|
4
|
+
* other ACP agents are added by config.
|
|
5
|
+
*
|
|
6
|
+
* - The drivers are `chat` entries of the panel's `drivers` service (`acp:dsh`, ...). A panel without this plugin lists none; this plugin without a panel is pending.
|
|
7
|
+
* - An agent whose command is not on the machine gets no driver, and the plugin says so in one line (as `driver-pty` does without node-pty).
|
|
8
|
+
* - Every agent process is acquired inside one `ctx.effect`; its disposer ends the process. Unloading or reloading the plugin leaves no agent running.
|
|
9
|
+
* - Development only, like the panel: with `NODE_ENV=production` (or `ACRYL_DOOR=off`) it starts nothing.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { existsSync } from 'node:fs'
|
|
13
|
+
import { isAbsolute } from 'node:path'
|
|
14
|
+
import { onPath } from '@acryldev/agent-panel/headless'
|
|
15
|
+
import type {} from '@acryldev/agent-panel/registry'
|
|
16
|
+
import type {} from '@acryldev/instance'
|
|
17
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
18
|
+
import { type AcpPermissions, acpDriver, type OpenAgent } from './chat.ts'
|
|
19
|
+
import { type AcpAgent, AcpConnection } from './connection.ts'
|
|
20
|
+
|
|
21
|
+
export const name = 'driver-acp'
|
|
22
|
+
export const inject = ['drivers', 'appInstance']
|
|
23
|
+
|
|
24
|
+
export type { AcpPermissions } from './chat.ts'
|
|
25
|
+
export { acpDriver } from './chat.ts'
|
|
26
|
+
export { type AcpAgent, AcpConnection, AcpError } from './connection.ts'
|
|
27
|
+
|
|
28
|
+
/** The ACP agents this plugin knows by name: the command line that starts each one's ACP server. */
|
|
29
|
+
export const PRESETS: Readonly<Record<string, AcpAgent>> = {
|
|
30
|
+
dsh: { command: 'dsh', args: ['--profile', 'acp'] },
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface DriverAcpConfig {
|
|
34
|
+
/** The agents to offer, by name (the driver is `acp:<name>`). Default: the presets whose command is on the machine. */
|
|
35
|
+
agents?: Record<string, AcpAgent>
|
|
36
|
+
/** The answer to an agent's permission request: its "allow once" or its "reject once" option. Default `reject`. */
|
|
37
|
+
permissions?: AcpPermissions
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function apply(ctx: Context, config: DriverAcpConfig = {}): void {
|
|
41
|
+
if (process.env.NODE_ENV === 'production' || process.env.ACRYL_DOOR === 'off') return
|
|
42
|
+
const root = ctx.appInstance.root
|
|
43
|
+
const open: OpenAgent = (agent, handle) => {
|
|
44
|
+
let connection!: AcpConnection
|
|
45
|
+
const close = ctx.effect(() => {
|
|
46
|
+
connection = new AcpConnection(agent, root, handle)
|
|
47
|
+
return () => connection.close()
|
|
48
|
+
}) as () => Promise<void>
|
|
49
|
+
// An agent that ended on its own gives its effect back at once instead of at unload.
|
|
50
|
+
void connection.ended.then(() => close())
|
|
51
|
+
return { connection, close }
|
|
52
|
+
}
|
|
53
|
+
for (const [agentName, agent] of Object.entries(config.agents ?? PRESETS)) {
|
|
54
|
+
if (!(isAbsolute(agent.command) ? existsSync(agent.command) : onPath(agent.command))) {
|
|
55
|
+
console.warn(`driver-acp: no acp:${agentName} driver, "${agent.command}" is not on the PATH`)
|
|
56
|
+
continue
|
|
57
|
+
}
|
|
58
|
+
const driver = acpDriver({
|
|
59
|
+
name: `acp:${agentName}`,
|
|
60
|
+
agent,
|
|
61
|
+
cwd: root,
|
|
62
|
+
permissions: config.permissions ?? 'reject',
|
|
63
|
+
open,
|
|
64
|
+
})
|
|
65
|
+
ctx.effect(() => ctx.drivers.register(driver))
|
|
66
|
+
}
|
|
67
|
+
}
|