-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathagents.ts
More file actions
563 lines (499 loc) · 15.8 KB
/
agents.ts
File metadata and controls
563 lines (499 loc) · 15.8 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 { runCommandWithExitCodes } from "@effect-template/lib/shell/command-runner"
import { CommandFailedError } from "@effect-template/lib/shell/errors"
import { defaultProjectsRoot } from "@effect-template/lib/usecases/path-helpers"
import { Effect } from "effect"
import { randomUUID } from "node:crypto"
import { promises as fs } from "node:fs"
import { join } from "node:path"
import { spawn, type ChildProcess } from "node:child_process"
import type {
AgentLogLine,
AgentSession,
CreateAgentRequest,
ProjectDetails
} from "../api/contracts.js"
import { ApiBadRequestError, ApiConflictError, ApiNotFoundError } from "../api/errors.js"
import { emitProjectEvent } from "./events.js"
type AgentRecord = {
session: AgentSession
projectDir: string
logs: Array<AgentLogLine>
process: ChildProcess | null
stdoutRemainder: string
stderrRemainder: string
}
type SnapshotFile = {
readonly sessions: ReadonlyArray<AgentSession>
}
const records: Map<string, AgentRecord> = new Map()
const projectIndex: Map<string, Set<string>> = new Map()
const maxLogLines = 5000
let initialized = false
const nowIso = (): string => new Date().toISOString()
const stateFilePath = (): string =>
join(defaultProjectsRoot(process.cwd()), ".orch", "state", "api-agents.json")
const upsertProjectIndex = (projectId: string, agentId: string): void => {
const current = projectIndex.get(projectId)
if (current) {
current.add(agentId)
return
}
projectIndex.set(projectId, new Set([agentId]))
}
const shellEscape = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`
const agentEnvKeyPattern = /^[A-Za-z_][A-Za-z0-9_]*$/u
const simpleEnvAssignmentPattern = /^[A-Za-z_][A-Za-z0-9_]*=[^\s]+$/u
const agentHome = (sshUser: string): string => `/home/${sshUser}`
const sourceLabel = (request: CreateAgentRequest): string =>
request.label?.trim().length ? request.label.trim() : request.provider
const pickDefaultCommand = (provider: CreateAgentRequest["provider"]): string => {
if (provider === "codex") {
return "MCP_PLAYWRIGHT_ISOLATED=1 codex"
}
if (provider === "opencode") {
return "opencode"
}
if (provider === "claude") {
return "MCP_PLAYWRIGHT_ISOLATED=1 claude"
}
return ""
}
export const buildCommand = (request: CreateAgentRequest): string => {
const direct = request.command?.trim() ?? ""
if (direct.length > 0) {
return direct
}
const base = pickDefaultCommand(request.provider)
if (base.length === 0) {
throw new ApiBadRequestError({ message: "Custom provider requires a non-empty 'command'." })
}
const args = (request.args ?? []).map((arg) => shellEscape(arg))
return args.length === 0 ? base : `${base} ${args.join(" ")}`
}
const buildEnvExports = (
envEntries: ReadonlyArray<{ readonly key: string; readonly value: string }>
): string => envEntries
.map(({ key, value }) => {
if (!agentEnvKeyPattern.test(key)) {
throw new ApiBadRequestError({ message: `Invalid agent env key: ${key}` })
}
return `export ${key}=${shellEscape(value)}`
})
.join("\n")
const execLine = (command: string): string => {
const parts = command.trim().split(/\s+/u)
const firstCommandIndex = parts.findIndex((part) => !simpleEnvAssignmentPattern.test(part))
return firstCommandIndex > 0
? `exec env ${parts.slice(0, firstCommandIndex).join(" ")} ${parts.slice(firstCommandIndex).join(" ")}`
: `exec ${command}`
}
export const buildAgentScript = (
sessionId: string,
cwd: string,
sshUser: string,
codexHome: string,
envEntries: ReadonlyArray<{ readonly key: string; readonly value: string }>,
command: string
): string => {
const pidFile = `/tmp/docker-git-agent-${sessionId}.pid`
const home = agentHome(sshUser)
const sshEnvPath = `${home}/.ssh/environment`
const exports = buildEnvExports(envEntries)
return [
"set -eo pipefail",
`PID_FILE=${shellEscape(pidFile)}`,
"cleanup() { rm -f \"$PID_FILE\"; }",
"trap cleanup EXIT",
"echo $$ > \"$PID_FILE\"",
`export HOME=${shellEscape(home)}`,
`export USER=${shellEscape(sshUser)}`,
`export LOGNAME=${shellEscape(sshUser)}`,
`export CODEX_HOME=${shellEscape(codexHome)}`,
"export DOCKER_GIT_RTK_ENABLE=\"${DOCKER_GIT_RTK_ENABLE:-1}\"",
"if [ -f /etc/profile ]; then . /etc/profile >/dev/null 2>&1 || true; fi",
`if [ -f ${shellEscape(sshEnvPath)} ]; then`,
" set -a",
` . ${shellEscape(sshEnvPath)} >/dev/null 2>&1 || true`,
" set +a",
"fi",
"if [ -f /run/docker-git/agent-env.sh ]; then . /run/docker-git/agent-env.sh >/dev/null 2>&1 || true; fi",
`export HOME=${shellEscape(home)}`,
`export USER=${shellEscape(sshUser)}`,
`export LOGNAME=${shellEscape(sshUser)}`,
`export CODEX_HOME=${shellEscape(codexHome)}`,
"export DOCKER_GIT_RTK_ENABLE=\"${DOCKER_GIT_RTK_ENABLE:-1}\"",
"set -u",
`cd ${shellEscape(cwd)}`,
exports,
execLine(command)
]
.filter((line) => line.trim().length > 0)
.join("\n")
}
export const buildAgentDockerExecArgs = (
project: Pick<ProjectDetails, "containerName" | "sshUser" | "codexHome">,
script: string
): ReadonlyArray<string> => {
const home = agentHome(project.sshUser)
return [
"exec",
"-i",
"-u",
project.sshUser,
"-e",
`HOME=${home}`,
"-e",
`USER=${project.sshUser}`,
"-e",
`LOGNAME=${project.sshUser}`,
"-e",
`CODEX_HOME=${project.codexHome}`,
project.containerName,
"bash",
"-lc",
script
]
}
const trimLogs = (logs: Array<AgentLogLine>): Array<AgentLogLine> =>
logs.length <= maxLogLines ? logs : logs.slice(logs.length - maxLogLines)
const persistSnapshot = async (): Promise<void> => {
const filePath = stateFilePath()
await fs.mkdir(join(filePath, ".."), { recursive: true })
const payload: SnapshotFile = {
sessions: [...records.values()].map((record) => record.session)
}
await fs.writeFile(filePath, JSON.stringify(payload, null, 2), "utf8")
}
const persistSnapshotBestEffort = (): void => {
void persistSnapshot().catch(() => {
// best effort snapshot persistence
})
}
const updateSession = (
record: AgentRecord,
patch: Partial<AgentSession>
): void => {
record.session = {
...record.session,
...patch,
updatedAt: nowIso()
}
records.set(record.session.id, record)
persistSnapshotBestEffort()
}
const appendLog = (
record: AgentRecord,
stream: AgentLogLine["stream"],
line: string
): void => {
const entry: AgentLogLine = {
at: nowIso(),
stream,
line
}
record.logs = trimLogs([...record.logs, entry])
emitProjectEvent(record.session.projectId, "agent.output", {
agentId: record.session.id,
stream,
line,
at: entry.at
})
}
const flushRemainder = (record: AgentRecord, stream: AgentLogLine["stream"]): void => {
const remainder = stream === "stdout" ? record.stdoutRemainder : record.stderrRemainder
if (remainder.length === 0) {
return
}
appendLog(record, stream, remainder)
if (stream === "stdout") {
record.stdoutRemainder = ""
} else {
record.stderrRemainder = ""
}
}
const consumeChunk = (
record: AgentRecord,
stream: AgentLogLine["stream"],
chunk: Buffer
): void => {
const incoming = chunk.toString("utf8")
const withRemainder = (stream === "stdout" ? record.stdoutRemainder : record.stderrRemainder) + incoming
const lines = withRemainder.split(/\r?\n/u)
const tail = lines.pop() ?? ""
for (const line of lines) {
if (line.length > 0) {
appendLog(record, stream, line)
}
}
if (stream === "stdout") {
record.stdoutRemainder = tail
} else {
record.stderrRemainder = tail
}
}
const getProjectAgentIds = (projectId: string): ReadonlyArray<string> => {
const ids = projectIndex.get(projectId)
return ids ? [...ids] : []
}
const getRecordOrFail = (
projectId: string,
agentId: string
): Effect.Effect<AgentRecord, ApiNotFoundError> =>
Effect.gen(function*(_) {
const record = records.get(agentId)
if (!record || record.session.projectId !== projectId) {
return yield* _(
Effect.fail(
new ApiNotFoundError({ message: `Agent not found: ${agentId} in project ${projectId}` })
)
)
}
return record
})
const endedStatuses: ReadonlySet<AgentSession["status"]> = new Set(["stopped", "exited", "failed"])
const killAgentScript = (sessionId: string): string => {
const pidFile = `/tmp/docker-git-agent-${sessionId}.pid`
return [
"set -eu",
`PID_FILE=${shellEscape(pidFile)}`,
"if [ -f \"$PID_FILE\" ]; then",
" PID=$(cat \"$PID_FILE\" 2>/dev/null || true)",
" if [ -n \"$PID\" ]; then",
" kill -TERM \"$PID\" 2>/dev/null || true",
" sleep 2",
" if kill -0 \"$PID\" 2>/dev/null; then kill -KILL \"$PID\" 2>/dev/null || true; fi",
" fi",
"fi"
].join("\n")
}
const hydrateFromSnapshot = async (): Promise<void> => {
const filePath = stateFilePath()
const exists = await fs.stat(filePath).then(() => true).catch(() => false)
if (!exists) {
return
}
const raw = await fs.readFile(filePath, "utf8")
const parsed = JSON.parse(raw) as SnapshotFile
for (const session of parsed.sessions ?? []) {
const restored: AgentSession = {
...session,
status: endedStatuses.has(session.status) ? session.status : "exited",
hostPid: null,
stoppedAt: session.stoppedAt ?? nowIso(),
updatedAt: nowIso()
}
const record: AgentRecord = {
session: restored,
projectDir: "",
logs: [],
process: null,
stdoutRemainder: "",
stderrRemainder: ""
}
records.set(restored.id, record)
upsertProjectIndex(restored.projectId, restored.id)
}
}
export const initializeAgentState = () =>
Effect.tryPromise({
try: async () => {
if (initialized) {
return
}
await hydrateFromSnapshot()
initialized = true
},
catch: (error) => new Error(String(error))
}).pipe(
Effect.catchAll(() => Effect.void),
Effect.asVoid
)
// CHANGE: start an agent process inside a project container and register it for API control.
// WHY: issue #84 requires non-CLI lifecycle control for Codex/OpenCode/Claude runs.
// QUOTE(ТЗ): "Запускать агентов"
// REF: issue-84-agent-start
// SOURCE: n/a
// FORMAT THEOREM: forall req: valid(req) -> exists(session(req))
// PURITY: SHELL
// EFFECT: Effect<AgentSession, ApiBadRequestError | ApiConflictError>
// INVARIANT: agent ids are unique UUIDs and state snapshots are persisted best-effort
// COMPLEXITY: O(1)
export const startAgent = (
project: ProjectDetails,
request: CreateAgentRequest
)=>
Effect.try({
try: () => {
const command = buildCommand(request)
const sessionId = randomUUID()
const pidFile = `/tmp/docker-git-agent-${sessionId}.pid`
const label = sourceLabel(request)
const startedAt = nowIso()
const workingDir = request.cwd?.trim() || project.targetDir
const session: AgentSession = {
id: sessionId,
projectId: project.id,
provider: request.provider,
label,
command,
containerName: project.containerName,
status: "starting",
source: `provider:${request.provider}`,
pidFile,
hostPid: null,
startedAt,
updatedAt: startedAt
}
const script = buildAgentScript(
sessionId,
workingDir,
project.sshUser,
project.codexHome,
request.env ?? [],
command
)
const record: AgentRecord = {
session,
projectDir: project.projectDir,
logs: [],
process: null,
stdoutRemainder: "",
stderrRemainder: ""
}
records.set(sessionId, record)
upsertProjectIndex(project.id, sessionId)
const child = spawn(
"docker",
[...buildAgentDockerExecArgs(project, script)],
{
cwd: project.projectDir,
env: process.env,
stdio: ["ignore", "pipe", "pipe"]
}
)
record.process = child
updateSession(record, {
status: "running",
hostPid: child.pid ?? null
})
emitProjectEvent(project.id, "agent.started", {
agentId: sessionId,
provider: request.provider,
label,
command
})
child.stdout.on("data", (chunk: Buffer) => {
consumeChunk(record, "stdout", chunk)
})
child.stderr.on("data", (chunk: Buffer) => {
consumeChunk(record, "stderr", chunk)
})
child.on("error", (error) => {
updateSession(record, {
status: "failed",
stoppedAt: nowIso()
})
emitProjectEvent(project.id, "agent.error", {
agentId: sessionId,
message: error.message
})
})
child.on("close", (exitCode, signal) => {
flushRemainder(record, "stdout")
flushRemainder(record, "stderr")
const expectedStop = record.session.status === "stopping" || record.session.status === "stopped"
const nextStatus: AgentSession["status"] = expectedStop
? "stopped"
: (exitCode === 0 ? "exited" : "failed")
updateSession(record, {
status: nextStatus,
hostPid: null,
stoppedAt: nowIso(),
...(exitCode === null ? {} : { exitCode }),
...(signal === null ? {} : { signal })
})
emitProjectEvent(project.id, expectedStop ? "agent.stopped" : "agent.exited", {
agentId: sessionId,
exitCode,
signal,
status: nextStatus
})
})
persistSnapshotBestEffort()
return record.session
},
catch: (error) => {
if (error instanceof ApiBadRequestError) {
return error
}
if (error instanceof ApiConflictError) {
return error
}
return new ApiConflictError({ message: `Failed to start agent: ${String(error)}` })
}
})
export const listAgents = (projectId: string): ReadonlyArray<AgentSession> =>
getProjectAgentIds(projectId)
.map((id) => records.get(id))
.filter((record): record is AgentRecord => Boolean(record))
.map((record) => record.session)
export const getAgent = (
projectId: string,
agentId: string
) =>
getRecordOrFail(projectId, agentId).pipe(Effect.map((record) => record.session))
export const stopAgent = (
projectId: string,
projectDir: string,
containerName: string,
agentId: string
)=>
Effect.gen(function*(_) {
const record = yield* _(getRecordOrFail(projectId, agentId))
if (endedStatuses.has(record.session.status)) {
return record.session
}
updateSession(record, { status: "stopping" })
const command = killAgentScript(agentId)
yield* _(
runCommandWithExitCodes(
{
cwd: projectDir,
command: "docker",
args: ["exec", containerName, "bash", "-lc", command]
},
[0],
(exitCode) => new CommandFailedError({ command: "docker exec kill-agent", exitCode })
).pipe(Effect.catchAll(() => Effect.void))
)
if (record.process && !record.process.killed) {
record.process.kill("SIGTERM")
}
emitProjectEvent(projectId, "agent.stopped", { agentId, message: "Stop signal sent" })
return record.session
})
export const readAgentLogs = (
projectId: string,
agentId: string,
lines: number
)=>
getRecordOrFail(projectId, agentId).pipe(
Effect.map((record) => {
const safe = Number.isFinite(lines) && lines > 0 ? Math.min(Math.floor(lines), maxLogLines) : 200
return record.logs.slice(record.logs.length - safe)
})
)
export const getAgentAttachInfo = (
projectId: string,
agentId: string
)=>
getRecordOrFail(projectId, agentId).pipe(
Effect.map((record) => ({
projectId,
agentId,
containerName: record.session.containerName,
pidFile: record.session.pidFile,
inspectCommand: `docker exec ${record.session.containerName} bash -lc 'cat ${record.session.pidFile}'`,
shellCommand: `docker exec -it ${record.session.containerName} bash`
}))
)