-
Notifications
You must be signed in to change notification settings - Fork 648
Expand file tree
/
Copy pathacpProcessManager.ts
More file actions
563 lines (493 loc) · 18.5 KB
/
acpProcessManager.ts
File metadata and controls
563 lines (493 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
import spawn from 'cross-spawn'
import type { ChildProcessWithoutNullStreams } from 'child_process'
import { Readable, Writable } from 'node:stream'
import { app } from 'electron'
import * as fs from 'fs'
import * as path from 'path'
import { ClientSideConnection, PROTOCOL_VERSION, ndJsonStream } from '@agentclientprotocol/sdk'
import type {
ClientSideConnection as ClientSideConnectionType,
Client
} from '@agentclientprotocol/sdk'
import type * as schema from '@agentclientprotocol/sdk/dist/schema.js'
import type { Stream } from '@agentclientprotocol/sdk/dist/stream.js'
import type { AcpAgentConfig } from '@shared/presenter'
import type { AgentProcessHandle, AgentProcessManager } from './types'
import { getShellEnvironment } from './shellEnvHelper'
import { RuntimeHelper } from '@/lib/runtimeHelper'
export interface AcpProcessHandle extends AgentProcessHandle {
child: ChildProcessWithoutNullStreams
connection: ClientSideConnectionType
agent: AcpAgentConfig
readyAt: number
}
interface AcpProcessManagerOptions {
providerId: string
getUseBuiltinRuntime: () => Promise<boolean>
getNpmRegistry?: () => Promise<string | null>
getUvRegistry?: () => Promise<string | null>
}
export type SessionNotificationHandler = (notification: schema.SessionNotification) => void
export type PermissionResolver = (
request: schema.RequestPermissionRequest
) => Promise<schema.RequestPermissionResponse>
interface SessionListenerEntry {
agentId: string
handlers: Set<SessionNotificationHandler>
}
/**
* Check if running in Electron environment.
* Reference: @modelcontextprotocol/sdk/client/stdio.js
*/
function isElectron(): boolean {
return 'type' in process
}
interface PermissionResolverEntry {
agentId: string
resolver: PermissionResolver
}
export class AcpProcessManager implements AgentProcessManager<AcpProcessHandle, AcpAgentConfig> {
private readonly providerId: string
private readonly getUseBuiltinRuntime: () => Promise<boolean>
private readonly getNpmRegistry?: () => Promise<string | null>
private readonly getUvRegistry?: () => Promise<string | null>
private readonly handles = new Map<string, AcpProcessHandle>()
private readonly pendingHandles = new Map<string, Promise<AcpProcessHandle>>()
private readonly sessionListeners = new Map<string, SessionListenerEntry>()
private readonly permissionResolvers = new Map<string, PermissionResolverEntry>()
private readonly runtimeHelper = RuntimeHelper.getInstance()
constructor(options: AcpProcessManagerOptions) {
this.providerId = options.providerId
this.getUseBuiltinRuntime = options.getUseBuiltinRuntime
this.getNpmRegistry = options.getNpmRegistry
this.getUvRegistry = options.getUvRegistry
}
async getConnection(agent: AcpAgentConfig): Promise<AcpProcessHandle> {
const existing = this.handles.get(agent.id)
if (existing && this.isHandleAlive(existing)) {
return existing
}
const inflight = this.pendingHandles.get(agent.id)
if (inflight) {
return inflight
}
const handlePromise = this.spawnProcess(agent)
this.pendingHandles.set(agent.id, handlePromise)
try {
const handle = await handlePromise
this.handles.set(agent.id, handle)
return handle
} finally {
this.pendingHandles.delete(agent.id)
}
}
getProcess(agentId: string): AcpProcessHandle | null {
return this.handles.get(agentId) ?? null
}
listProcesses(): AcpProcessHandle[] {
return Array.from(this.handles.values())
}
async release(agentId: string): Promise<void> {
const handle = this.handles.get(agentId)
if (!handle) return
this.handles.delete(agentId)
this.clearSessionsForAgent(agentId)
this.killChild(handle.child)
}
async shutdown(): Promise<void> {
const releases = Array.from(this.handles.keys()).map((agentId) => this.release(agentId))
await Promise.allSettled(releases)
this.handles.clear()
this.sessionListeners.clear()
this.permissionResolvers.clear()
this.pendingHandles.clear()
}
registerSessionListener(
agentId: string,
sessionId: string,
handler: SessionNotificationHandler
): () => void {
const entry = this.sessionListeners.get(sessionId)
if (entry) {
entry.handlers.add(handler)
} else {
this.sessionListeners.set(sessionId, { agentId, handlers: new Set([handler]) })
}
return () => {
const existingEntry = this.sessionListeners.get(sessionId)
if (!existingEntry) return
existingEntry.handlers.delete(handler)
if (existingEntry.handlers.size === 0) {
this.sessionListeners.delete(sessionId)
}
}
}
registerPermissionResolver(
agentId: string,
sessionId: string,
resolver: PermissionResolver
): () => void {
if (this.permissionResolvers.has(sessionId)) {
console.warn(
`[ACP] Overwriting existing permission resolver for session "${sessionId}" (agent ${agentId})`
)
}
this.permissionResolvers.set(sessionId, { agentId, resolver })
return () => {
const entry = this.permissionResolvers.get(sessionId)
if (entry && entry.resolver === resolver) {
this.permissionResolvers.delete(sessionId)
}
}
}
clearSession(sessionId: string): void {
this.sessionListeners.delete(sessionId)
this.permissionResolvers.delete(sessionId)
}
private async spawnProcess(agent: AcpAgentConfig): Promise<AcpProcessHandle> {
const child = await this.spawnAgentProcess(agent)
const stream = this.createAgentStream(child)
const client = this.createClientProxy()
const connection = new ClientSideConnection(() => client, stream)
await connection.initialize({
protocolVersion: PROTOCOL_VERSION,
clientCapabilities: {},
clientInfo: { name: 'DeepChat', version: app.getVersion() }
})
const handle: AcpProcessHandle = {
providerId: this.providerId,
agentId: agent.id,
agent,
status: 'ready',
pid: child.pid ?? undefined,
restarts: (this.handles.get(agent.id)?.restarts ?? 0) + 1,
lastHeartbeatAt: Date.now(),
metadata: { command: agent.command },
child,
connection,
readyAt: Date.now()
}
child.on('exit', (code, signal) => {
console.warn(
`[ACP] Agent process for ${agent.id} exited (code=${code ?? 'null'}, signal=${signal ?? 'null'})`
)
if (this.handles.get(agent.id)?.child === child) {
this.handles.delete(agent.id)
}
this.clearSessionsForAgent(agent.id)
})
child.stderr?.on('data', (chunk: Buffer) => {
console.warn(`[ACP] ${agent.id} stderr: ${chunk.toString()}`)
})
return handle
}
private async spawnAgentProcess(agent: AcpAgentConfig): Promise<ChildProcessWithoutNullStreams> {
// Initialize runtime paths if not already done
this.runtimeHelper.initializeRuntimes()
// Get useBuiltinRuntime configuration
const useBuiltinRuntime = await this.getUseBuiltinRuntime()
// Validate command
if (!agent.command || agent.command.trim().length === 0) {
throw new Error(`[ACP] Invalid command for agent ${agent.id}: command is empty`)
}
// Handle path expansion (including ~ and environment variables)
let expandedCommand = this.runtimeHelper.expandPath(agent.command)
let expandedArgs = (agent.args ?? []).map((arg) =>
typeof arg === 'string' ? this.runtimeHelper.expandPath(arg) : arg
)
// Replace command with runtime version if needed
const processedCommand = this.runtimeHelper.replaceWithRuntimeCommand(
expandedCommand,
useBuiltinRuntime,
true
)
// Validate processed command
if (!processedCommand || processedCommand.trim().length === 0) {
throw new Error(
`[ACP] Invalid processed command for agent ${agent.id}: "${agent.command}" -> empty`
)
}
// Log command processing for debugging
console.info(`[ACP] Spawning process for agent ${agent.id}:`, {
originalCommand: agent.command,
processedCommand,
args: agent.args ?? []
})
if (processedCommand !== agent.command) {
console.info(
`[ACP] Command replaced for agent ${agent.id}: "${agent.command}" -> "${processedCommand}"`
)
}
// Use expanded args
const processedArgs = expandedArgs
// Determine if it's Node.js/UV related command
const isNodeCommand = ['node', 'npm', 'npx', 'uv', 'uvx'].some(
(cmd) =>
processedCommand.includes(cmd) ||
processedArgs.some((arg) => typeof arg === 'string' && arg.includes(cmd))
)
const HOME_DIR = app.getPath('home')
const env: Record<string, string> = {}
Object.entries(process.env).forEach(([key, value]) => {
if (value !== undefined && value !== '') {
env[key] = value
}
})
let pathKey = process.platform === 'win32' ? 'Path' : 'PATH'
let pathValue = ''
if (isNodeCommand) {
// Node.js/UV commands need full environment propagation similar to ACP init
const existingPaths: string[] = []
const pathKeys = ['PATH', 'Path', 'path']
pathKeys.forEach((key) => {
const value = env[key]
if (value) {
existingPaths.push(value)
}
})
// Get shell environment variables regardless of runtime choice
let shellEnv: Record<string, string> = {}
try {
shellEnv = await getShellEnvironment()
console.info(`[ACP] Retrieved shell environment variables for agent ${agent.id}`)
Object.entries(shellEnv).forEach(([key, value]) => {
if (value !== undefined && value !== '' && !pathKeys.includes(key)) {
env[key] = value
}
})
} catch (error) {
console.warn(
`[ACP] Failed to get shell environment variables for agent ${agent.id}, using fallback:`,
error
)
}
// Get shell PATH if available (priority: shell PATH > existing PATH)
const shellPath = shellEnv.PATH || shellEnv.Path || shellEnv.path
if (shellPath) {
const shellPaths = shellPath.split(process.platform === 'win32' ? ';' : ':')
existingPaths.unshift(...shellPaths)
console.info(`[ACP] Using shell PATH for agent ${agent.id} (length: ${shellPath.length})`)
}
// Get default paths
const defaultPaths = this.runtimeHelper.getDefaultPaths(HOME_DIR)
// Merge all paths (priority: shell PATH > existing PATH > default paths)
const allPaths = [...existingPaths, ...defaultPaths]
// Add runtime paths only when using builtin runtime
if (useBuiltinRuntime) {
const uvRuntimePath = this.runtimeHelper.getUvRuntimePath()
const nodeRuntimePath = this.runtimeHelper.getNodeRuntimePath()
if (process.platform === 'win32') {
// Windows platform only adds node and uv paths
if (uvRuntimePath) {
allPaths.unshift(uvRuntimePath)
console.info(`[ACP] Added UV runtime path to PATH: ${uvRuntimePath}`)
}
if (nodeRuntimePath) {
allPaths.unshift(nodeRuntimePath)
console.info(`[ACP] Added Node runtime path to PATH: ${nodeRuntimePath}`)
}
} else {
// Other platforms priority: node > uv
if (uvRuntimePath) {
allPaths.unshift(uvRuntimePath)
console.info(`[ACP] Added UV runtime path to PATH: ${uvRuntimePath}`)
}
if (nodeRuntimePath) {
const nodeBinPath = path.join(nodeRuntimePath, 'bin')
allPaths.unshift(nodeBinPath)
console.info(`[ACP] Added Node bin path to PATH: ${nodeBinPath}`)
}
}
}
// Normalize and set PATH
const normalized = this.runtimeHelper.normalizePathEnv(allPaths)
pathKey = normalized.key
pathValue = normalized.value
env[pathKey] = pathValue
} else {
// Non Node.js/UV commands, preserve all system environment variables, only supplement PATH
// Supplement PATH
const existingPaths: string[] = []
if (env.PATH) {
existingPaths.push(env.PATH)
}
if (env.Path) {
existingPaths.push(env.Path)
}
// Get default paths
const defaultPaths = this.runtimeHelper.getDefaultPaths(HOME_DIR)
// Merge all paths
const allPaths = [...existingPaths, ...defaultPaths]
// Add runtime paths only when using builtin runtime
if (useBuiltinRuntime) {
const uvRuntimePath = this.runtimeHelper.getUvRuntimePath()
const nodeRuntimePath = this.runtimeHelper.getNodeRuntimePath()
if (process.platform === 'win32') {
// Windows platform only adds node and uv paths
if (uvRuntimePath) {
allPaths.unshift(uvRuntimePath)
console.info(`[ACP] Added UV runtime path to PATH: ${uvRuntimePath}`)
}
if (nodeRuntimePath) {
allPaths.unshift(nodeRuntimePath)
console.info(`[ACP] Added Node runtime path to PATH: ${nodeRuntimePath}`)
}
} else {
// Other platforms priority: node > uv
if (uvRuntimePath) {
allPaths.unshift(uvRuntimePath)
console.info(`[ACP] Added UV runtime path to PATH: ${uvRuntimePath}`)
}
if (nodeRuntimePath) {
const nodeBinPath = path.join(nodeRuntimePath, 'bin')
allPaths.unshift(nodeBinPath)
console.info(`[ACP] Added Node bin path to PATH: ${nodeBinPath}`)
}
}
}
// Normalize and set PATH
const normalized = this.runtimeHelper.normalizePathEnv(allPaths)
pathKey = normalized.key
pathValue = normalized.value
env[pathKey] = pathValue
}
// Add custom environment variables
if (agent.env) {
Object.entries(agent.env).forEach(([key, value]) => {
if (value !== undefined && value !== '') {
// If it's a PATH-related variable, merge into main PATH
if (['PATH', 'Path', 'path'].includes(key)) {
const currentPathKey = process.platform === 'win32' ? 'Path' : 'PATH'
const separator = process.platform === 'win32' ? ';' : ':'
env[currentPathKey] = env[currentPathKey]
? `${value}${separator}${env[currentPathKey]}`
: value
} else {
env[key] = value
}
}
})
}
// Add registry environment variables when using builtin runtime
if (useBuiltinRuntime) {
if (this.getNpmRegistry) {
const npmRegistry = await this.getNpmRegistry()
if (npmRegistry && npmRegistry !== '') {
env.npm_config_registry = npmRegistry
}
}
if (this.getUvRegistry) {
const uvRegistry = await this.getUvRegistry()
if (uvRegistry && uvRegistry !== '') {
env.UV_DEFAULT_INDEX = uvRegistry
env.PIP_INDEX_URL = uvRegistry
}
}
}
const mergedEnv = env
console.info(`[ACP] Environment variables for agent ${agent.id}:`, {
pathKey,
pathValue,
hasCustomEnv: !!agent.env,
customEnvKeys: agent.env ? Object.keys(agent.env) : []
})
// Determine working directory (default to current working directory)
let cwd = process.cwd()
// Validate cwd exists
if (!fs.existsSync(cwd)) {
console.warn(`[ACP] Working directory does not exist: ${cwd}, using fallback`)
cwd = process.platform === 'win32' ? 'C:\\' : '/'
}
console.info(`[ACP] Spawning process with options:`, {
command: processedCommand,
args: processedArgs,
cwd,
platform: process.platform
})
const child = spawn(processedCommand, processedArgs, {
env: mergedEnv,
cwd,
stdio: ['pipe', 'pipe', 'pipe'],
shell: false,
windowsHide: process.platform === 'win32' && isElectron()
}) as ChildProcessWithoutNullStreams
console.info(`[ACP] Process spawned successfully for agent ${agent.id}, PID: ${child.pid}`)
return child
}
private createAgentStream(child: ChildProcessWithoutNullStreams): Stream {
// Add error handler for stdin to prevent EPIPE errors when process exits
child.stdin.on('error', (error: NodeJS.ErrnoException) => {
// EPIPE errors occur when trying to write to a closed pipe (process already exited)
// This is expected behavior and should be silently handled
if (error.code !== 'EPIPE') {
console.error('[ACP] write error:', error)
}
})
const writable = Writable.toWeb(child.stdin) as unknown as WritableStream<Uint8Array>
const readable = Readable.toWeb(child.stdout) as unknown as ReadableStream<Uint8Array>
return ndJsonStream(writable, readable)
}
private createClientProxy(): Client {
return {
requestPermission: async (params) => this.dispatchPermissionRequest(params),
sessionUpdate: async (notification) => {
this.dispatchSessionUpdate(notification)
}
}
}
private dispatchSessionUpdate(notification: schema.SessionNotification): void {
const entry = this.sessionListeners.get(notification.sessionId)
if (!entry) {
console.warn(`[ACP] Received session update for unknown session "${notification.sessionId}"`)
return
}
entry.handlers.forEach((handler) => {
try {
handler(notification)
} catch (error) {
console.warn(`[ACP] Session handler threw for session ${notification.sessionId}:`, error)
}
})
}
private async dispatchPermissionRequest(
params: schema.RequestPermissionRequest
): Promise<schema.RequestPermissionResponse> {
const entry = this.permissionResolvers.get(params.sessionId)
if (!entry) {
console.warn(
`[ACP] Missing permission resolver for session "${params.sessionId}", returning cancelled`
)
return { outcome: { outcome: 'cancelled' } }
}
try {
return await entry.resolver(params)
} catch (error) {
console.error('[ACP] Permission resolver failed:', error)
return { outcome: { outcome: 'cancelled' } }
}
}
private clearSessionsForAgent(agentId: string): void {
for (const [sessionId, entry] of this.sessionListeners.entries()) {
if (entry.agentId === agentId) {
this.sessionListeners.delete(sessionId)
}
}
for (const [sessionId, entry] of this.permissionResolvers.entries()) {
if (entry.agentId === agentId) {
this.permissionResolvers.delete(sessionId)
}
}
}
private killChild(child: ChildProcessWithoutNullStreams): void {
if (!child.killed) {
try {
child.kill()
} catch (error) {
console.warn('[ACP] Failed to kill agent process:', error)
}
}
}
private isHandleAlive(handle: AcpProcessHandle): boolean {
return !handle.child.killed && !handle.connection.signal.aborted
}
}