Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/durable-agent-manager-terminals.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"kilo-code": patch
"@kilocode/cli": patch
---

Keep Agent Manager terminals and nested Kilo sessions alive across configuration reloads and location idle eviction, while cleaning them up on explicit close, worktree deletion, and server shutdown.
264 changes: 264 additions & 0 deletions packages/core/src/kilocode/pty/registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
import type { Disp, Proc } from "#pty"
import path from "node:path"
import { Log } from "../../util/log"
import type { Location } from "../../location"
import type { Info } from "../../pty"
import type { PtyID } from "../../pty/schema"
import { KiloPtyTermination } from "./termination"

const log = Log.create({ service: "pty.registry" })

export type Subscriber = {
readonly onData: (chunk: string) => void
readonly onEnd: (event: { exitCode?: number }) => void
active: boolean
detached: boolean
pending: string[]
end?: { exitCode?: number }
}

export type Active = {
info: Info
location: Location.Ref
process: Proc
buffer: string
bufferCursor: number
cursor: number
subscribers: Map<object, Subscriber>
listeners: Disp[]
stopping: boolean
terminated: boolean
closing?: Promise<void>
}

export const sessions = new Map<PtyID, Active>()
const exited = new Map<string, PtyID[]>()
const pending = new Map<number, Location.Ref>()
const blocked = new Map<string, Location.Ref>()
const removing = new Set<PtyID>()
const waiters = new Set<() => void>()
const directoryTasks = new Map<string, Promise<void>>()
let next = 0
let closing = false
let shutdownTask: Promise<void> | undefined
let owners = 0

export function sameLocation(a: Location.Ref, b: Location.Ref) {
return sameDirectory(a.directory, b.directory) && a.workspaceID === b.workspaceID
}

export function sameDirectory(a: string, b: string) {
const left = directoryKey(a)
const right = directoryKey(b)
return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right
}

function directoryKey(value: string) {
return path.resolve(value)
}

function locationKey(location: Location.Ref) {
const directory = directoryKey(location.directory)
return `${location.workspaceID ?? ""}\u0000${process.platform === "win32" ? directory.toLowerCase() : directory}`
}

function matchesDirectory(location: Location.Ref, target: Location.Ref) {
return sameDirectory(location.directory, target.directory) && location.workspaceID === target.workspaceID
}

function wake() {
const current = [...waiters]
waiters.clear()
for (const resolve of current) resolve()
}

function waitFor(check: () => boolean): Promise<void> {
if (check()) return Promise.resolve()
return new Promise<void>((resolve) => waiters.add(resolve)).then(() => waitFor(check))
}

export function beginCreate(location: Location.Ref) {
if (closing) throw new Error("PTY registry is shutting down")
for (const target of blocked.values()) {
if (matchesDirectory(location, target)) throw new Error("PTY directory is being removed")
}
const id = ++next
pending.set(id, location)
let released = false
return () => {
if (released) return
released = true
pending.delete(id)
wake()
}
}

export function claimRemoval(id: PtyID) {
if (removing.has(id)) return false
removing.add(id)
return true
}

export function releaseRemoval(id: PtyID) {
removing.delete(id)
}

export async function acquireOwner() {
if (shutdownTask) await shutdownTask.catch(() => undefined)
owners++
let released = false
return async () => {
if (released) return
released = true
owners--
if (owners === 0) await shutdown()
}
}

export function hasDirectory(location: Location.Ref) {
return Array.from(sessions.values()).some((session) => matchesDirectory(session.location, location))
}

export function markExited(session: Active) {
const key = locationKey(session.location)
const order = exited.get(key) ?? []
if (!exited.has(key)) exited.set(key, order)
order.push(session.info.id)
}

export function oldestExited(location: Location.Ref) {
return exited.get(locationKey(location))?.[0]
}

export function exitedCount(location: Location.Ref) {
return exited.get(locationKey(location))?.length ?? 0
}

export function removeExitedID(location: Location.Ref, id: PtyID) {
const key = locationKey(location)
const order = exited.get(key)
if (!order) return
const index = order.indexOf(id)
if (index !== -1) order.splice(index, 1)
if (order.length === 0) exited.delete(key)
}

export function removeExited(session: Active) {
removeExitedID(session.location, session.info.id)
}

function notifyEnd(session: Active, event: { exitCode?: number }) {
for (const subscriber of session.subscribers.values()) {
if (!subscriber.active) {
subscriber.end = event
continue
}
try {
subscriber.onEnd(event)
} catch (error) {
log.debug("PTY subscriber end callback failed", { error, id: session.info.id })
}
}
session.subscribers.clear()
}

export function teardown(session: Active) {
if (session.closing) return session.closing
const task = (async () => {
session.stopping = true
try {
if (!session.terminated && session.info.status !== "exited") {
await KiloPtyTermination.terminate(session.process)
}
session.terminated = true
for (const listener of session.listeners) listener.dispose()
session.listeners.length = 0
notifyEnd(session, session.info.status === "exited" ? { exitCode: session.info.exitCode } : {})
} catch (error) {
session.stopping = false
throw error
}
})()
session.closing = task
void task.catch(() => {
if (session.closing === task) session.closing = undefined
})
return task
}

async function teardownMany(owned: Active[]) {
const results = await Promise.allSettled(owned.map(teardown))
const failed: unknown[] = []
for (let index = 0; index < owned.length; index++) {
const session = owned[index]
const result = results[index]
if (!session || !result) continue
if (result.status === "rejected") {
failed.push(result.reason)
continue
}
if (sessions.get(session.info.id) !== session) continue
sessions.delete(session.info.id)
removeExited(session)
}
if (failed.length > 0) throw new AggregateError(failed, "Failed to tear down one or more PTYs")
}

export function shutdown() {
if (shutdownTask) return shutdownTask
const task = (async () => {
closing = true
let success = false
try {
await waitFor(() => pending.size === 0)
await teardownMany(Array.from(sessions.values()))
success = true
} finally {
closing = false
wake()
}
})()
shutdownTask = task
void task.then(
() => {
if (shutdownTask === task) shutdownTask = undefined
},
() => {
if (shutdownTask === task) shutdownTask = undefined
},
)
return task
}

async function terminateDirectoryOnce(target: Location.Ref) {
const key = locationKey(target)
blocked.set(key, target)
let success = false
try {
await waitFor(() => ![...pending.values()].some((location) => matchesDirectory(location, target)))
const owned = Array.from(sessions.values()).filter((session) => matchesDirectory(session.location, target))
await teardownMany(owned)
success = true
} finally {
if (success) blocked.delete(key)
wake()
}
}

export function terminateDirectory(target: Location.Ref) {
const key = locationKey(target)
const current = directoryTasks.get(key)
if (current) return current
const task = terminateDirectoryOnce(target)
directoryTasks.set(key, task)
void task.then(
() => {
if (directoryTasks.get(key) === task) directoryTasks.delete(key)
},
(error) => {
log.warn("failed to tear down PTY for directory", { error, target })
if (directoryTasks.get(key) === task) directoryTasks.delete(key)
},
)
return task
}
31 changes: 17 additions & 14 deletions packages/core/src/kilocode/pty/termination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ function descendants(root: number, rows: Array<{ pid: number; parent: number }>)
}

async function family(root: number, input: Runtime) {
const rows = await input.tree().catch((err) => {
log.debug("failed to inspect PTY process tree", { err, pid: root })
return []
})
const rows = await input.tree()
return [...descendants(root, rows), root]
}

Expand All @@ -90,7 +87,7 @@ function signal(proc: Process, pids: number[], value: "SIGTERM" | "SIGKILL", inp
}

async function tree(file: string = "ps", args: string[] = ["-axo", "pid=,ppid="]) {
return await new Promise<Array<{ pid: number; parent: number }>>((resolve) => {
return await new Promise<Array<{ pid: number; parent: number }>>((resolve, reject) => {
try {
const child = spawn(file, args, {
stdio: ["ignore", "pipe", "ignore"],
Expand All @@ -100,9 +97,9 @@ async function tree(file: string = "ps", args: string[] = ["-axo", "pid=,ppid="]
})
const chunks: Buffer[] = []
child.stdout?.on("data", (chunk: Buffer) => chunks.push(chunk))
child.once("error", () => resolve([]))
child.once("error", reject)
child.once("close", (code) => {
if (code !== 0) return resolve([])
if (code !== 0) return reject(new Error(`process tree command exited with ${code}`))
const rows = Buffer.concat(chunks)
.toString("utf8")
.trim()
Expand All @@ -113,17 +110,13 @@ async function tree(file: string = "ps", args: string[] = ["-axo", "pid=,ppid="]
.map(([pid, parent]) => ({ pid: pid!, parent: parent! }))
resolve(rows)
})
} catch {
resolve([])
} catch (error) {
reject(error)
}
})
}

async function taskkill(
file: string,
args: string[],
opts: { stdio: "ignore"; windowsHide: true; timeout: number },
) {
async function taskkill(file: string, args: string[], opts: { stdio: "ignore"; windowsHide: true; timeout: number }) {
return await new Promise<boolean>((resolve) => {
try {
const child = spawn(file, args, opts)
Expand All @@ -148,6 +141,7 @@ export async function terminate(proc: Process, input: Runtime = runtime): Promis
if (!proc.pid) {
direct(proc)
if (!state.exited) await input.sleep(GRACE_MS)
await verify(proc, state.exited, input)
return
}

Expand All @@ -159,6 +153,7 @@ export async function terminate(proc: Process, input: Runtime = runtime): Promis
})
if (!killed && !state.exited) direct(proc)
if (!state.exited) await input.sleep(GRACE_MS)
await verify(proc, state.exited, input)
return
}

Expand All @@ -171,9 +166,17 @@ export async function terminate(proc: Process, input: Runtime = runtime): Promis
signal(proc, [...remaining], "SIGKILL", input)
await input.sleep(GRACE_MS)
}
await verify(proc, state.exited, input)
} finally {
listener.dispose()
}
}

async function verify(proc: Process, exited: boolean, input: Runtime) {
if (!proc.pid) return
const live = (await family(proc.pid, input)).filter((pid) => input.alive(pid) && !(pid === proc.pid && exited))
if (!exited && input.alive(proc.pid) && !live.includes(proc.pid)) live.push(proc.pid)
if (live.length > 0) throw new Error(`PTY process tree is still alive: ${live.join(", ")}`)
}

export * as KiloPtyTermination from "./termination"
5 changes: 3 additions & 2 deletions packages/core/src/location-services.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Effect, Layer, LayerMap } from "effect"
import { Duration, Effect, Layer, LayerMap } from "effect" // kilocode_change
import { AgentV2 } from "./agent"
import { AISDK } from "./aisdk"
import { Catalog } from "./catalog"
Expand Down Expand Up @@ -83,6 +83,7 @@ export type LocationError = LayerNode.Error<typeof locationServices>

export function buildLocationServiceMap(
replacements: LayerNode.Replacements = [],
options: { readonly idleTimeToLive?: Duration.Input } = {}, // kilocode_change
): Layer.Layer<LocationServiceMap.Service> {
return Layer.effect(
LocationServiceMap.Service,
Expand All @@ -106,7 +107,7 @@ export function buildLocationServiceMap(
Layer.provide(LayerNode.compile(location.hoisted)),
)
},
{ idleTimeToLive: "60 minutes" },
{ idleTimeToLive: options.idleTimeToLive ?? "60 minutes" }, // kilocode_change
),
)
}
Expand Down
Loading
Loading