The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | // @effect-diagnostics nodeBuiltinImport:off |
| 2 | import * as NodeCrypto from "node:crypto"; |
| 3 | import * as NodeFS from "node:fs"; |
| 4 | import * as NodePath from "node:path"; |
| 5 | |
| 6 | import * as Cause from "effect/Cause"; |
| 7 | import * as Clock from "effect/Clock"; |
| 8 | import * as Context from "effect/Context"; |
| 9 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 10 | import * as Deferred from "effect/Deferred"; |
| 11 | import * as Duration from "effect/Duration"; |
| 12 | import * as Effect from "effect/Effect"; |
| 13 | import * as Result from "effect/Result"; |
| 14 | import * as Exit from "effect/Exit"; |
| 15 | import * as Fiber from "effect/Fiber"; |
| 16 | import * as Layer from "effect/Layer"; |
| 17 | import * as Option from "effect/Option"; |
| 18 | import * as Queue from "effect/Queue"; |
| 19 | import * as Ref from "effect/Ref"; |
| 20 | import * as Schema from "effect/Schema"; |
| 21 | import * as Scope from "effect/Scope"; |
| 22 | import * as Semaphore from "effect/Semaphore"; |
| 23 | import * as Stream from "effect/Stream"; |
| 24 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 25 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 26 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 27 | import * as EffectAcpClient from "effect-acp/client"; |
| 28 | import * as EffectAcpErrors from "effect-acp/errors"; |
| 29 | import type * as EffectAcpSchema from "effect-acp/compat"; |
| 30 | import * as EffectAcpProtocol from "effect-acp/protocol"; |
| 31 | import { resolveSpawnCommand } from "@t3tools/shared/shell"; |
| 32 | import { AgentScope, AgentScopeThreadId, RAISE_OOM_SCORE_LINE } from "@t3tools/shared/AgentScope"; |
| 33 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 34 | |
| 35 | import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; |
| 36 | import { appendAcpStderrTail, sanitizeAcpStderrExcerpt } from "./stderr.ts"; |
| 37 | import { |
| 38 | collectSessionConfigOptionValues, |
| 39 | decideToolCallUpdateEmission, |
| 40 | extractModelConfigId, |
| 41 | findModelConfigOption, |
| 42 | findSessionConfigOption, |
| 43 | mergeToolCallState, |
| 44 | toolCallProgressLength, |
| 45 | parseSessionModeState, |
| 46 | parseSessionUpdateEvent, |
| 47 | sessionUpdateCountsAsLoadReplayActivity, |
| 48 | sessionUpdateIsReplay, |
| 49 | waitForSessionLoadReplayIdle, |
| 50 | type SessionLoadGate, |
| 51 | type AcpParsedSessionEvent, |
| 52 | type AcpSessionModeState, |
| 53 | type AcpToolCallState, |
| 54 | } from "./runtimeModel.ts"; |
| 55 | |
| 56 | const MAX_SHOWN_TOOL_CALL_IDS = 256; |
| 57 | |
| 58 | interface AcpToolCallTrackedState { |
| 59 | readonly state: AcpToolCallState; |
| 60 | readonly lastEmittedDetailLength: number | undefined; |
| 61 | readonly skippedSinceEmit: number; |
| 62 | } |
| 63 | |
| 64 | function formatConfigOptionValue(value: string | boolean): string { |
| 65 | return JSON.stringify(value); |
| 66 | } |
| 67 | |
| 68 | export interface AcpSessionEventStreamBarrier { |
| 69 | readonly _tag: "EventStreamBarrier"; |
| 70 | readonly acknowledge: Deferred.Deferred<void>; |
| 71 | } |
| 72 | |
| 73 | export type AcpSessionRuntimeEvent = |
| 74 | | AcpParsedSessionEvent |
| 75 | | AcpSessionEventStreamBarrier |
| 76 | | { |
| 77 | readonly _tag: "ConnectionTerminated"; |
| 78 | readonly error: EffectAcpErrors.AcpError; |
| 79 | } |
| 80 | | { |
| 81 | // A session/load response that arrived after replay idle replaced the |
| 82 | // provisional setup; its config/mode events were emitted just before. |
| 83 | readonly _tag: "SessionSetupAdopted"; |
| 84 | readonly result: AcpSessionRuntimeStartResult; |
| 85 | }; |
| 86 | |
| 87 | const defaultSessionLoadTimeout = Duration.seconds(90); |
| 88 | const defaultSessionLoadReplayIdleGap = Duration.seconds(2); |
| 89 | const defaultCancelTimeout = Duration.seconds(15); |
| 90 | const maxStartupMetadataUpdates = 32; |
| 91 | // Antigravity can emit an accepted 16 KiB Google authorization URL on stderr. |
| 92 | const maxStderrChunkLength = 32_768; |
| 93 | |
| 94 | export interface AcpSpawnInput { |
| 95 | readonly command: string; |
| 96 | readonly args: ReadonlyArray<string>; |
| 97 | readonly cwd?: string; |
| 98 | readonly env?: NodeJS.ProcessEnv; |
| 99 | readonly extendEnv?: boolean; |
| 100 | readonly shell?: false; |
| 101 | } |
| 102 | |
| 103 | export interface AcpSessionRuntimeOptions { |
| 104 | readonly spawn: AcpSpawnInput; |
| 105 | readonly cwd: string; |
| 106 | readonly resumeSessionId?: string; |
| 107 | readonly resumeMethod?: "load" | "resume"; |
| 108 | readonly sessionLoadTimeout?: Duration.Input; |
| 109 | readonly sessionLoadReplayIdleGap?: Duration.Input; |
| 110 | // Treat replay going quiet as loaded, for agents whose session/load may never reply. |
| 111 | readonly sessionLoadReplayIdleReadiness?: boolean; |
| 112 | readonly interruptPromptOnCancel?: boolean; |
| 113 | readonly cancelMeta?: EffectAcpSchema.CancelNotification["_meta"]; |
| 114 | readonly initializeMeta?: EffectAcpSchema.InitializeRequest["_meta"]; |
| 115 | readonly ownDetachedProcessGroup?: boolean; |
| 116 | readonly ownDescendantProcessGroups?: boolean; |
| 117 | readonly processGroupPlatform?: NodeJS.Platform; |
| 118 | readonly processGroupTerminationGrace?: Duration.Input; |
| 119 | readonly windowsProcessTreeTerminator?: ( |
| 120 | pid: number, |
| 121 | ) => Effect.Effect<void, AcpProcessGroupTerminationError>; |
| 122 | readonly posixProcessTreeController?: AcpPosixProcessTreeController; |
| 123 | readonly linuxCgroupController?: AcpLinuxCgroupController | null; |
| 124 | readonly cancelBehavior?: "interrupt" | "wait-for-prompt"; |
| 125 | readonly cancelTimeout?: Duration.Input; |
| 126 | readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"]; |
| 127 | readonly clientInfo: { |
| 128 | readonly name: string; |
| 129 | readonly title?: string; |
| 130 | readonly version: string; |
| 131 | }; |
| 132 | readonly authMethodId?: string; |
| 133 | /** Authenticate before opening: Antigravity selects its credential source from the method. */ |
| 134 | readonly authenticateEagerly?: boolean; |
| 135 | readonly mcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>; |
| 136 | /** Sent on every session/new, load, resume and fork; omitting them clears an agent's stored roots. */ |
| 137 | readonly additionalDirectories?: ReadonlyArray<string>; |
| 138 | /** Session `_meta`, chosen from the negotiated agent before each session setup or activation. */ |
| 139 | readonly sessionMeta?: ( |
| 140 | initializeResult: EffectAcpSchema.InitializeResponse, |
| 141 | ) => EffectAcpSchema.NewSessionRequest["_meta"] | undefined; |
| 142 | readonly transformStdout?: EffectAcpClient.AcpClientOptions["transformStdout"]; |
| 143 | readonly transformSessionUpdate?: ( |
| 144 | notification: EffectAcpSchema.SessionNotification, |
| 145 | ) => EffectAcpSchema.SessionNotification; |
| 146 | /** Redact secrets before logging. Failure closes the runtime. */ |
| 147 | readonly onStderr?: (text: string) => Effect.Effect<void, EffectAcpErrors.AcpError>; |
| 148 | /** Disable only for non-interactive discovery that must surface auth-required immediately. */ |
| 149 | readonly authenticateOnAuthRequired?: boolean; |
| 150 | readonly onInitialized?: ( |
| 151 | result: EffectAcpSchema.InitializeResponse, |
| 152 | ) => Effect.Effect<void, never>; |
| 153 | readonly acpMcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>; |
| 154 | readonly httpMcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>; |
| 155 | readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>; |
| 156 | readonly protocolLogging?: { |
| 157 | readonly logIncoming?: boolean; |
| 158 | readonly logOutgoing?: boolean; |
| 159 | readonly logger?: (event: EffectAcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>; |
| 160 | }; |
| 161 | readonly onIncomingRequest?: EffectAcpClient.AcpClientOptions["onIncomingRequest"]; |
| 162 | readonly onTermination?: (error: EffectAcpErrors.AcpError) => Effect.Effect<void>; |
| 163 | readonly onOutgoingResponseFailure?: EffectAcpClient.AcpClientOptions["onOutgoingResponseFailure"]; |
| 164 | readonly onOutgoingResponse?: EffectAcpClient.AcpClientOptions["onOutgoingResponse"]; |
| 165 | /** Unadvertised model IDs accepted by the config option; the agent validates them. */ |
| 166 | readonly customModels?: ReadonlyArray<string>; |
| 167 | } |
| 168 | |
| 169 | export interface AcpSessionRequestLogEvent { |
| 170 | readonly method: string; |
| 171 | readonly payload: unknown; |
| 172 | readonly status: "started" | "succeeded" | "failed"; |
| 173 | readonly result?: unknown; |
| 174 | readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>; |
| 175 | } |
| 176 | |
| 177 | export class AcpProcessGroupTerminationError extends Schema.TaggedError<AcpProcessGroupTerminationError>()( |
| 178 | "AcpProcessGroupTerminationError", |
| 179 | { |
| 180 | detail: Schema.String, |
| 181 | pid: Schema.optionalKey(Schema.Int), |
| 182 | exitCode: Schema.optionalKey(Schema.Number), |
| 183 | cause: Schema.optional(Schema.Defect()), |
| 184 | }, |
| 185 | ) { |
| 186 | override get message(): string { |
| 187 | return this.detail; |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | const isAcpProcessGroupTerminationError = Schema.is(AcpProcessGroupTerminationError); |
| 192 | |
| 193 | export interface AcpPosixProcessIdentity { |
| 194 | readonly executable: string | undefined; |
| 195 | readonly pgid: number; |
| 196 | readonly pid: number; |
| 197 | readonly ppid: number; |
| 198 | readonly sid: number; |
| 199 | readonly state?: string; |
| 200 | readonly startTime: string; |
| 201 | } |
| 202 | |
| 203 | export interface AcpPosixProcessTreeController { |
| 204 | readonly childPidsOf: (pid: number) => ReadonlyArray<number>; |
| 205 | readonly childrenOf: (pid: number) => ReadonlyArray<AcpPosixProcessIdentity>; |
| 206 | readonly identity: (pid: number) => AcpPosixProcessIdentity | undefined; |
| 207 | readonly snapshot: () => ReadonlyArray<AcpPosixProcessIdentity>; |
| 208 | readonly signalProcess: (pid: number, signal: NodeJS.Signals) => void; |
| 209 | } |
| 210 | |
| 211 | export interface AcpLinuxCgroupLease { |
| 212 | readonly contains: (pid: number) => boolean; |
| 213 | readonly exists: () => boolean; |
| 214 | readonly path: string; |
| 215 | readonly relativePath: string; |
| 216 | readonly kill: () => void; |
| 217 | readonly populated: () => boolean; |
| 218 | readonly remove: () => void; |
| 219 | } |
| 220 | |
| 221 | export interface AcpLinuxCgroupController { |
| 222 | readonly create: () => AcpLinuxCgroupLease | undefined; |
| 223 | } |
| 224 | |
| 225 | export interface AcpPosixOwnershipRoot { |
| 226 | captureAttempted?: boolean; |
| 227 | value: AcpOwnedPosixProcess | undefined; |
| 228 | } |
| 229 | |
| 230 | function decodeMountInfoPath(value: string): string { |
| 231 | return value.replace(/\\([0-7]{3})/g, (_match, octal: string) => |
| 232 | String.fromCharCode(Number.parseInt(octal, 8)), |
| 233 | ); |
| 234 | } |
| 235 | |
| 236 | export function parseUnifiedCgroupPath(contents: string): string | undefined { |
| 237 | const matches = [...contents.matchAll(/^0::(\/.*)$/gm)]; |
| 238 | return matches.length === 1 ? matches[0]![1] : undefined; |
| 239 | } |
| 240 | |
| 241 | export function isSafeCgroupPath(value: string): boolean { |
| 242 | return ( |
| 243 | value.startsWith("/") && |
| 244 | !value.includes("(deleted)") && |
| 245 | NodePath.posix.normalize(value) === value |
| 246 | ); |
| 247 | } |
| 248 | |
| 249 | export function parseCgroup2Mounts( |
| 250 | contents: string, |
| 251 | ): ReadonlyArray<{ readonly mountPoint: string; readonly root: string }> { |
| 252 | const mounts: Array<{ readonly mountPoint: string; readonly root: string }> = []; |
| 253 | for (const line of contents.split("\n")) { |
| 254 | const [mount, filesystem] = line.split(" - "); |
| 255 | if (mount === undefined || filesystem?.split(" ")[0] !== "cgroup2") continue; |
| 256 | const fields = mount.split(" "); |
| 257 | if (fields.length < 5) continue; |
| 258 | mounts.push({ |
| 259 | mountPoint: decodeMountInfoPath(fields[4]!), |
| 260 | root: decodeMountInfoPath(fields[3]!), |
| 261 | }); |
| 262 | } |
| 263 | return mounts; |
| 264 | } |
| 265 | |
| 266 | export function wrapCommandForLinuxCgroup( |
| 267 | lease: AcpLinuxCgroupLease, |
| 268 | command: string, |
| 269 | args: ReadonlyArray<string>, |
| 270 | ): { readonly command: string; readonly args: ReadonlyArray<string> } { |
| 271 | return { |
| 272 | command: "/bin/sh", |
| 273 | args: [ |
| 274 | "-c", |
| 275 | [ |
| 276 | "lease_path=$1; expected=$2; shift 2", |
| 277 | RAISE_OOM_SCORE_LINE, |
| 278 | 'printf "%s\\n" "$$" > "$lease_path/cgroup.procs" || exit 125', |
| 279 | "actual=", |
| 280 | "while IFS= read -r line; do", |
| 281 | ' case "$line" in 0::*) [ -z "$actual" ] || exit 126; actual=${line#0::};; esac', |
| 282 | "done < /proc/self/cgroup || exit 125", |
| 283 | '[ "$actual" = "$expected" ] || exit 126', |
| 284 | "unset ELECTRON_RUN_AS_NODE T3_ACP_CGROUP_WRAPPER", |
| 285 | "trap 'exit 125' 0", |
| 286 | // Bash can skip EXIT traps on failed exec; reject invalid targets with path and exit 125. |
| 287 | '[ -f "$1" ] && [ -x "$1" ] || { printf "%s: %s: not an executable file\\n" "$0" "$1" >&2; exit 125; }', |
| 288 | 'exec "$@"', |
| 289 | ].join("\n"), |
| 290 | "t3-acp-cgroup-wrapper", |
| 291 | lease.path, |
| 292 | lease.relativePath, |
| 293 | command, |
| 294 | ...args, |
| 295 | ], |
| 296 | }; |
| 297 | } |
| 298 | |
| 299 | export function resolveLinuxCgroupTargetCommand( |
| 300 | command: string, |
| 301 | cwd: string, |
| 302 | environment: NodeJS.ProcessEnv, |
| 303 | ): string | undefined { |
| 304 | // Match Node spawn: only undefined PATH gets a fallback; empty PATH searches cwd. |
| 305 | const pathEnv = environment.PATH === undefined ? "/usr/bin:/bin" : environment.PATH; |
| 306 | const candidates = command.includes(NodePath.sep) |
| 307 | ? [NodePath.resolve(cwd, command)] |
| 308 | : pathEnv |
| 309 | .split(NodePath.delimiter) |
| 310 | .map((entry) => |
| 311 | NodePath.join( |
| 312 | entry.length === 0 |
| 313 | ? cwd |
| 314 | : NodePath.isAbsolute(entry) |
| 315 | ? entry |
| 316 | : NodePath.resolve(cwd, entry), |
| 317 | command, |
| 318 | ), |
| 319 | ); |
| 320 | for (const candidate of candidates) { |
| 321 | try { |
| 322 | if (!NodeFS.statSync(candidate).isFile()) continue; |
| 323 | NodeFS.accessSync(candidate, NodeFS.constants.X_OK); |
| 324 | return candidate; |
| 325 | } catch {} |
| 326 | } |
| 327 | return undefined; |
| 328 | } |
| 329 | |
| 330 | const STALE_ACP_CGROUP_SIBLING = /^t3-acp-(\d+)-/; |
| 331 | |
| 332 | export interface SweepStaleLinuxCgroupSiblingsOptions { |
| 333 | readonly currentPid?: number; |
| 334 | readonly isProcessAlive?: (pid: number) => boolean; |
| 335 | readonly readPopulated?: (siblingPath: string) => "0" | "1" | undefined; |
| 336 | readonly remove?: (siblingPath: string) => void; |
| 337 | } |
| 338 | |
| 339 | function defaultCgroupOwnerIsAlive(pid: number): boolean { |
| 340 | try { |
| 341 | process.kill(pid, 0); |
| 342 | return true; |
| 343 | } catch (cause) { |
| 344 | return (cause as NodeJS.ErrnoException | undefined)?.code !== "ESRCH"; |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | function defaultReadCgroupPopulated(siblingPath: string): "0" | "1" | undefined { |
| 349 | const state = /(?:^|\n)populated ([01])(?:\n|$)/.exec( |
| 350 | NodeFS.readFileSync(NodePath.join(siblingPath, "cgroup.events"), "utf8"), |
| 351 | )?.[1]; |
| 352 | return state === "0" || state === "1" ? state : undefined; |
| 353 | } |
| 354 | |
| 355 | export function sweepStaleLinuxCgroupSiblings( |
| 356 | parentPath: string, |
| 357 | options: SweepStaleLinuxCgroupSiblingsOptions = {}, |
| 358 | ): void { |
| 359 | const currentPid = options.currentPid ?? process.pid; |
| 360 | const isProcessAlive = options.isProcessAlive ?? defaultCgroupOwnerIsAlive; |
| 361 | const readPopulated = options.readPopulated ?? defaultReadCgroupPopulated; |
| 362 | const remove = options.remove ?? ((siblingPath: string) => NodeFS.rmdirSync(siblingPath)); |
| 363 | try { |
| 364 | for (const entry of NodeFS.readdirSync(parentPath, { withFileTypes: true })) { |
| 365 | try { |
| 366 | if (!entry.isDirectory()) continue; |
| 367 | const match = STALE_ACP_CGROUP_SIBLING.exec(entry.name); |
| 368 | if (match === null) continue; |
| 369 | const ownerPid = Number(match[1]); |
| 370 | if (!Number.isSafeInteger(ownerPid) || ownerPid <= 1 || ownerPid === currentPid) continue; |
| 371 | if (isProcessAlive(ownerPid)) continue; |
| 372 | const siblingPath = NodePath.join(parentPath, entry.name); |
| 373 | if (NodePath.dirname(siblingPath) !== parentPath) continue; |
| 374 | if (readPopulated(siblingPath) !== "0") continue; |
| 375 | remove(siblingPath); |
| 376 | } catch {} |
| 377 | } |
| 378 | } catch {} |
| 379 | } |
| 380 | |
| 381 | function tryCreateLinuxCgroupLease( |
| 382 | currentRelative: string, |
| 383 | mount: { readonly mountPoint: string; readonly root: string }, |
| 384 | ): AcpLinuxCgroupLease | undefined { |
| 385 | if ( |
| 386 | !isSafeCgroupPath(mount.root) || |
| 387 | !isSafeCgroupPath(mount.mountPoint) || |
| 388 | !( |
| 389 | mount.root === "/" || |
| 390 | currentRelative === mount.root || |
| 391 | currentRelative.startsWith(`${mount.root}/`) |
| 392 | ) |
| 393 | ) { |
| 394 | return undefined; |
| 395 | } |
| 396 | const mountRelative = |
| 397 | mount.root === "/" ? currentRelative : currentRelative.slice(mount.root.length); |
| 398 | const currentPath = NodePath.resolve(mount.mountPoint, `.${mountRelative}`); |
| 399 | const resolvedMount = NodePath.resolve(mount.mountPoint); |
| 400 | if (currentPath !== resolvedMount && !currentPath.startsWith(`${resolvedMount}${NodePath.sep}`)) { |
| 401 | return undefined; |
| 402 | } |
| 403 | sweepStaleLinuxCgroupSiblings(currentPath); |
| 404 | const childName = `t3-acp-${process.pid}-${NodeCrypto.randomUUID().replaceAll("-", "")}`; |
| 405 | const childPath = NodePath.join(currentPath, childName); |
| 406 | const childRelative = NodePath.posix.join(currentRelative, childName); |
| 407 | if (NodePath.dirname(childPath) !== currentPath) return undefined; |
| 408 | try { |
| 409 | NodeFS.mkdirSync(childPath, { mode: 0o700 }); |
| 410 | NodeFS.accessSync(NodePath.join(childPath, "cgroup.procs"), NodeFS.constants.W_OK); |
| 411 | NodeFS.accessSync(NodePath.join(childPath, "cgroup.kill"), NodeFS.constants.W_OK); |
| 412 | NodeFS.accessSync(NodePath.join(childPath, "cgroup.events"), NodeFS.constants.R_OK); |
| 413 | if (NodeFS.readFileSync(NodePath.join(childPath, "cgroup.type"), "utf8").trim() !== "domain") { |
| 414 | throw new Error("ACP cgroup is not a domain cgroup"); |
| 415 | } |
| 416 | if (typeof process.execve !== "function") throw new Error("process.execve is unavailable"); |
| 417 | } catch { |
| 418 | try { |
| 419 | NodeFS.rmdirSync(childPath); |
| 420 | } catch {} |
| 421 | return undefined; |
| 422 | } |
| 423 | return { |
| 424 | contains: (pid) => |
| 425 | parseUnifiedCgroupPath(NodeFS.readFileSync(`/proc/${pid}/cgroup`, "utf8")) === childRelative, |
| 426 | exists: () => NodeFS.existsSync(childPath), |
| 427 | path: childPath, |
| 428 | relativePath: childRelative, |
| 429 | kill: () => NodeFS.writeFileSync(NodePath.join(childPath, "cgroup.kill"), "1\n"), |
| 430 | populated: () => { |
| 431 | const state = /(?:^|\n)populated ([01])(?:\n|$)/.exec( |
| 432 | NodeFS.readFileSync(NodePath.join(childPath, "cgroup.events"), "utf8"), |
| 433 | )?.[1]; |
| 434 | if (state === undefined) throw new Error("ACP cgroup.events has no populated state"); |
| 435 | return state === "1"; |
| 436 | }, |
| 437 | remove: () => { |
| 438 | const directories = (path: string): ReadonlyArray<string> => |
| 439 | NodeFS.readdirSync(path, { withFileTypes: true }).flatMap((entry) => |
| 440 | entry.isDirectory() |
| 441 | ? [...directories(NodePath.join(path, entry.name)), NodePath.join(path, entry.name)] |
| 442 | : [], |
| 443 | ); |
| 444 | for (const directory of directories(childPath)) NodeFS.rmdirSync(directory); |
| 445 | NodeFS.rmdirSync(childPath); |
| 446 | }, |
| 447 | }; |
| 448 | } |
| 449 | |
| 450 | export function makeLinuxCgroupController(): AcpLinuxCgroupController { |
| 451 | return { |
| 452 | create: () => { |
| 453 | let currentRelative: string | undefined; |
| 454 | let mounts: ReadonlyArray<{ readonly mountPoint: string; readonly root: string }> = []; |
| 455 | try { |
| 456 | currentRelative = parseUnifiedCgroupPath(NodeFS.readFileSync("/proc/self/cgroup", "utf8")); |
| 457 | mounts = parseCgroup2Mounts(NodeFS.readFileSync("/proc/self/mountinfo", "utf8")); |
| 458 | } catch { |
| 459 | return undefined; |
| 460 | } |
| 461 | if ( |
| 462 | currentRelative === undefined || |
| 463 | !currentRelative.startsWith("/") || |
| 464 | mounts.length === 0 |
| 465 | ) { |
| 466 | return undefined; |
| 467 | } |
| 468 | if (!isSafeCgroupPath(currentRelative)) return undefined; |
| 469 | // Multi-mount hosts often list a read-only view before the delegated one. |
| 470 | for (const mount of mounts) { |
| 471 | const lease = tryCreateLinuxCgroupLease(currentRelative, mount); |
| 472 | if (lease !== undefined) return lease; |
| 473 | } |
| 474 | return undefined; |
| 475 | }, |
| 476 | }; |
| 477 | } |
| 478 | |
| 479 | // OS-state polls need wall time; TestClock sleep requires explicit advancement. |
| 480 | const wallClock = Clock.Clock.defaultValue(); |
| 481 | const withWallClock = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => |
| 482 | Effect.provideService(effect, Clock.Clock, wallClock); |
| 483 | |
| 484 | export function terminateLinuxCgroupLease( |
| 485 | lease: AcpLinuxCgroupLease, |
| 486 | ): Effect.Effect<void, AcpProcessGroupTerminationError> { |
| 487 | const failure = (name: string, cause: unknown) => |
| 488 | new AcpProcessGroupTerminationError({ |
| 489 | cause, |
| 490 | detail: `Failed to ${name} ACP cgroup ${lease.path}`, |
| 491 | }); |
| 492 | return Effect.gen(function* () { |
| 493 | let lastRemovalFailure: { readonly cause: unknown } | null = null; |
| 494 | for (let attempt = 0; attempt < 200; attempt += 1) { |
| 495 | if (!lease.exists()) return; |
| 496 | const killed = Result.try(() => lease.kill()); |
| 497 | if (Result.isFailure(killed)) { |
| 498 | const cause = killed.failure; |
| 499 | const code = (cause as NodeJS.ErrnoException | undefined)?.code; |
| 500 | if (code !== "ENOENT") return yield* failure("kill", cause); |
| 501 | if (!lease.exists()) return; |
| 502 | yield* Effect.sleep("10 millis"); |
| 503 | continue; |
| 504 | } |
| 505 | const populated = Result.try(() => lease.populated()); |
| 506 | if (Result.isFailure(populated)) { |
| 507 | const cause = populated.failure; |
| 508 | const code = (cause as NodeJS.ErrnoException | undefined)?.code; |
| 509 | if (code === "ENOENT" && !lease.exists()) return; |
| 510 | if (code === "ENOENT") { |
| 511 | yield* Effect.sleep("10 millis"); |
| 512 | continue; |
| 513 | } |
| 514 | return yield* failure("read state for", cause); |
| 515 | } |
| 516 | if (populated.success) { |
| 517 | lastRemovalFailure = null; |
| 518 | yield* Effect.sleep("10 millis"); |
| 519 | continue; |
| 520 | } |
| 521 | const removed = Result.try(() => lease.remove()); |
| 522 | if (Result.isFailure(removed)) { |
| 523 | const cause = removed.failure; |
| 524 | const code = (cause as NodeJS.ErrnoException | undefined)?.code; |
| 525 | if (code === "ENOENT" && !lease.exists()) return; |
| 526 | if (code !== "EBUSY" && code !== "ENOTEMPTY" && code !== "ENOENT") { |
| 527 | return yield* failure("remove", cause); |
| 528 | } |
| 529 | lastRemovalFailure = { cause }; |
| 530 | } else { |
| 531 | lastRemovalFailure = null; |
| 532 | } |
| 533 | if (!lease.exists()) return; |
| 534 | yield* Effect.sleep("10 millis"); |
| 535 | } |
| 536 | if (lastRemovalFailure !== null) { |
| 537 | return yield* failure("remove", lastRemovalFailure.cause); |
| 538 | } |
| 539 | return yield* new AcpProcessGroupTerminationError({ |
| 540 | detail: `ACP cgroup ${lease.path} remained present after cgroup cleanup`, |
| 541 | }); |
| 542 | }).pipe(withWallClock); |
| 543 | } |
| 544 | |
| 545 | export function signalLinuxCgroupRootTerm(input: { |
| 546 | readonly controller: AcpPosixProcessTreeController; |
| 547 | readonly lease: AcpLinuxCgroupLease; |
| 548 | readonly root: AcpPosixOwnershipRoot; |
| 549 | }): void { |
| 550 | const root = input.root.value; |
| 551 | if (root === undefined) return; |
| 552 | try { |
| 553 | const observed = input.controller.identity(root.pid); |
| 554 | if (!samePosixProcessIdentity(root, observed) || !input.lease.contains(root.pid)) return; |
| 555 | input.controller.signalProcess(root.pid, "SIGTERM"); |
| 556 | } catch {} |
| 557 | } |
| 558 | |
| 559 | function readLinuxProcessIdentity(pid: number): AcpPosixProcessIdentity | undefined { |
| 560 | try { |
| 561 | const stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8"); |
| 562 | const commandEnd = stat.lastIndexOf(")"); |
| 563 | if (commandEnd < 0) return undefined; |
| 564 | const fields = stat |
| 565 | .slice(commandEnd + 2) |
| 566 | .trim() |
| 567 | .split(/\s+/); |
| 568 | // After comm: state, ppid, pgrp, session, … starttime (field 22 / index 19). |
| 569 | const state = fields[0]; |
| 570 | const ppid = Number(fields[1]); |
| 571 | const pgid = Number(fields[2]); |
| 572 | const sid = Number(fields[3]); |
| 573 | const startTime = fields[19]; |
| 574 | if ( |
| 575 | state === undefined || |
| 576 | !Number.isSafeInteger(ppid) || |
| 577 | !Number.isSafeInteger(pgid) || |
| 578 | !Number.isSafeInteger(sid) || |
| 579 | startTime === undefined |
| 580 | ) { |
| 581 | return undefined; |
| 582 | } |
| 583 | let executable: string | undefined; |
| 584 | try { |
| 585 | executable = NodeFS.readlinkSync(`/proc/${pid}/exe`); |
| 586 | } catch { |
| 587 | executable = undefined; |
| 588 | } |
| 589 | return { executable, pgid, pid, ppid, sid, startTime, state }; |
| 590 | } catch { |
| 591 | return undefined; |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | /** Linux zombies keep pid/starttime until reaped; they are not live survivors. */ |
| 596 | export function posixProcessIsZombie(process: AcpPosixProcessIdentity): boolean { |
| 597 | return process.state === "Z"; |
| 598 | } |
| 599 | |
| 600 | function readLinuxChildPids(pid: number): ReadonlyArray<number> { |
| 601 | const childPids = new Set<number>(); |
| 602 | let taskIds: ReadonlyArray<string> = []; |
| 603 | try { |
| 604 | taskIds = NodeFS.readdirSync(`/proc/${pid}/task`).filter((entry) => |
| 605 | /^[1-9][0-9]*$/.test(entry), |
| 606 | ); |
| 607 | } catch { |
| 608 | return []; |
| 609 | } |
| 610 | for (const taskId of taskIds) { |
| 611 | try { |
| 612 | for (const childPid of NodeFS.readFileSync(`/proc/${pid}/task/${taskId}/children`, "utf8") |
| 613 | .trim() |
| 614 | .split(/\s+/) |
| 615 | .filter(Boolean) |
| 616 | .map(Number)) { |
| 617 | childPids.add(childPid); |
| 618 | } |
| 619 | } catch {} |
| 620 | } |
| 621 | return [...childPids]; |
| 622 | } |
| 623 | |
| 624 | function makeLinuxProcessTreeController(): AcpPosixProcessTreeController { |
| 625 | return { |
| 626 | childPidsOf: readLinuxChildPids, |
| 627 | childrenOf: (pid) => |
| 628 | readLinuxChildPids(pid).flatMap((childPid) => { |
| 629 | const identity = readLinuxProcessIdentity(childPid); |
| 630 | return identity === undefined ? [] : [identity]; |
| 631 | }), |
| 632 | identity: readLinuxProcessIdentity, |
| 633 | snapshot: () => |
| 634 | // By name only: withFileTypes lstats entries, which throws when a process exits mid-scan. |
| 635 | NodeFS.readdirSync("/proc").flatMap((entry) => { |
| 636 | if (!/^[1-9][0-9]*$/.test(entry)) return []; |
| 637 | const identity = readLinuxProcessIdentity(Number(entry)); |
| 638 | return identity === undefined ? [] : [identity]; |
| 639 | }), |
| 640 | signalProcess: (pid, signal) => process.kill(pid, signal), |
| 641 | }; |
| 642 | } |
| 643 | |
| 644 | export function observePosixOwnershipLedger(input: { |
| 645 | readonly childQueues: Map<number, Array<number>>; |
| 646 | readonly controller: AcpPosixProcessTreeController; |
| 647 | readonly frontier: Map<number, AcpOwnedPosixProcess>; |
| 648 | readonly ledger: Map<string, AcpOwnedPosixProcess>; |
| 649 | readonly maxProcesses?: number; |
| 650 | readonly root: AcpPosixOwnershipRoot; |
| 651 | readonly rootPid: number; |
| 652 | }): void { |
| 653 | let rootIdentity: AcpPosixProcessIdentity | undefined = input.root.value; |
| 654 | if (rootIdentity === undefined) { |
| 655 | if (input.root.captureAttempted === true) { |
| 656 | throw new AcpProcessGroupTerminationError({ |
| 657 | detail: `ACP process ${input.rootPid} exited before its ownership ledger was captured`, |
| 658 | }); |
| 659 | } |
| 660 | input.root.captureAttempted = true; |
| 661 | rootIdentity = input.controller.identity(input.rootPid); |
| 662 | if (rootIdentity === undefined) { |
| 663 | throw new AcpProcessGroupTerminationError({ |
| 664 | detail: `ACP process ${input.rootPid} exited before its ownership ledger was captured`, |
| 665 | }); |
| 666 | } |
| 667 | const parent = input.controller.identity(rootIdentity.ppid); |
| 668 | const ownedRoot = { |
| 669 | ...rootIdentity, |
| 670 | parentExecutable: parent?.executable, |
| 671 | parentStartTime: parent?.startTime ?? "", |
| 672 | }; |
| 673 | input.ledger.set(processIdentityKey(rootIdentity), ownedRoot); |
| 674 | input.frontier.set(rootIdentity.pid, ownedRoot); |
| 675 | input.root.value = ownedRoot; |
| 676 | } |
| 677 | const maxProcesses = Math.max(1, input.maxProcesses ?? Number.POSITIVE_INFINITY); |
| 678 | let remainingBudget = maxProcesses; |
| 679 | const pending = [...input.frontier.entries()]; |
| 680 | const visited = new Set<number>(); |
| 681 | while (pending.length > 0 && remainingBudget > 0) { |
| 682 | const entry = pending.shift(); |
| 683 | if (entry === undefined) continue; |
| 684 | const [parentPid, parent] = entry; |
| 685 | input.frontier.delete(parentPid); |
| 686 | if (visited.has(parent.pid)) continue; |
| 687 | visited.add(parent.pid); |
| 688 | remainingBudget -= 1; |
| 689 | const observedParent = input.controller.identity(parent.pid); |
| 690 | if (!samePosixProcessIdentity(parent, observedParent)) { |
| 691 | input.childQueues.delete(parent.pid); |
| 692 | continue; |
| 693 | } |
| 694 | const refreshedParent = { ...parent, ...observedParent }; |
| 695 | input.ledger.set(processIdentityKey(refreshedParent), refreshedParent); |
| 696 | input.frontier.set(refreshedParent.pid, refreshedParent); |
| 697 | let queuedChildren = input.childQueues.get(refreshedParent.pid); |
| 698 | if (queuedChildren === undefined) { |
| 699 | if (remainingBudget === 0) continue; |
| 700 | remainingBudget -= 1; |
| 701 | queuedChildren = [...input.controller.childPidsOf(refreshedParent.pid)]; |
| 702 | } |
| 703 | while (queuedChildren.length > 0 && remainingBudget > 0) { |
| 704 | const childPid = queuedChildren.shift(); |
| 705 | if (childPid === undefined) continue; |
| 706 | remainingBudget -= 1; |
| 707 | const child = input.controller.identity(childPid); |
| 708 | if (child === undefined) continue; |
| 709 | if (child.ppid !== parent.pid) continue; |
| 710 | let reservedPid = input.frontier.get(child.pid); |
| 711 | if (reservedPid !== undefined && !samePosixProcessIdentity(reservedPid, child)) { |
| 712 | input.frontier.delete(child.pid); |
| 713 | for (const [key, owned] of input.ledger.entries()) { |
| 714 | if (owned.pid === child.pid) input.ledger.delete(key); |
| 715 | } |
| 716 | reservedPid = undefined; |
| 717 | } |
| 718 | const childKey = processIdentityKey(child); |
| 719 | const owned = |
| 720 | reservedPid === undefined |
| 721 | ? { |
| 722 | ...child, |
| 723 | parentExecutable: refreshedParent.executable, |
| 724 | parentStartTime: refreshedParent.startTime, |
| 725 | } |
| 726 | : { ...reservedPid, ...child }; |
| 727 | input.ledger.set(childKey, owned); |
| 728 | input.frontier.set(child.pid, owned); |
| 729 | } |
| 730 | if (queuedChildren.length === 0) input.childQueues.delete(refreshedParent.pid); |
| 731 | else input.childQueues.set(refreshedParent.pid, queuedChildren); |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | function observePosixOwnershipLedgerContinuously(input: { |
| 736 | readonly childQueues: Map<number, Array<number>>; |
| 737 | readonly controller: AcpPosixProcessTreeController; |
| 738 | readonly frontier: Map<number, AcpOwnedPosixProcess>; |
| 739 | readonly ledger: Map<string, AcpOwnedPosixProcess>; |
| 740 | readonly root: AcpPosixOwnershipRoot; |
| 741 | readonly rootPid: number; |
| 742 | }): Effect.Effect<never> { |
| 743 | return Effect.forever( |
| 744 | Effect.gen(function* () { |
| 745 | const startedAt = yield* Clock.currentTimeMillis; |
| 746 | yield* Effect.sync(() => observePosixOwnershipLedger({ ...input, maxProcesses: 64 })).pipe( |
| 747 | Effect.exit, |
| 748 | ); |
| 749 | const targetInterval = input.frontier.size <= 32 ? 25 : input.frontier.size <= 128 ? 50 : 100; |
| 750 | const completedAt = yield* Clock.currentTimeMillis; |
| 751 | yield* Effect.sleep(`${Math.max(5, targetInterval - (completedAt - startedAt))} millis`); |
| 752 | }), |
| 753 | ).pipe(withWallClock); |
| 754 | } |
| 755 | |
| 756 | export function makePosixProcessTreeController( |
| 757 | platform: NodeJS.Platform, |
| 758 | ): AcpPosixProcessTreeController { |
| 759 | if (platform === "linux") return makeLinuxProcessTreeController(); |
| 760 | throw new AcpProcessGroupTerminationError({ |
| 761 | detail: `Detached ACP descendant ownership is unsupported on ${platform}`, |
| 762 | }); |
| 763 | } |
| 764 | |
| 765 | function samePosixProcessIdentity( |
| 766 | expected: AcpPosixProcessIdentity, |
| 767 | observed: AcpPosixProcessIdentity | undefined, |
| 768 | ): boolean { |
| 769 | return ( |
| 770 | observed !== undefined && |
| 771 | observed.pid === expected.pid && |
| 772 | observed.startTime === expected.startTime |
| 773 | ); |
| 774 | } |
| 775 | |
| 776 | export interface AcpOwnedPosixProcess extends AcpPosixProcessIdentity { |
| 777 | readonly parentExecutable: string | undefined; |
| 778 | readonly parentStartTime: string; |
| 779 | } |
| 780 | |
| 781 | function processIdentityKey(process: AcpPosixProcessIdentity): string { |
| 782 | return `${process.pid}:${process.startTime}`; |
| 783 | } |
| 784 | |
| 785 | function processDepth( |
| 786 | process: AcpPosixProcessIdentity, |
| 787 | ledgerByPid: ReadonlyMap<number, AcpOwnedPosixProcess>, |
| 788 | ): number { |
| 789 | let depth = 0; |
| 790 | let current = process; |
| 791 | const seen = new Set<number>(); |
| 792 | while (!seen.has(current.pid)) { |
| 793 | seen.add(current.pid); |
| 794 | const parent = ledgerByPid.get(current.ppid); |
| 795 | if (parent === undefined) break; |
| 796 | depth += 1; |
| 797 | current = parent; |
| 798 | } |
| 799 | return depth; |
| 800 | } |
| 801 | |
| 802 | export function capturePosixOwnershipLedger(input: { |
| 803 | readonly controller: AcpPosixProcessTreeController; |
| 804 | readonly ledger: Map<string, AcpOwnedPosixProcess>; |
| 805 | readonly root?: AcpPosixOwnershipRoot; |
| 806 | readonly rootPid: number; |
| 807 | readonly table?: ReadonlyArray<AcpPosixProcessIdentity>; |
| 808 | }): ReadonlyArray<AcpPosixProcessIdentity> { |
| 809 | let table: ReadonlyArray<AcpPosixProcessIdentity>; |
| 810 | if (input.table === undefined) { |
| 811 | try { |
| 812 | table = input.controller.snapshot(); |
| 813 | } catch (cause) { |
| 814 | throw new AcpProcessGroupTerminationError({ |
| 815 | cause, |
| 816 | detail: `Failed to snapshot ACP process tree ${input.rootPid}`, |
| 817 | }); |
| 818 | } |
| 819 | } else { |
| 820 | table = input.table; |
| 821 | } |
| 822 | const byPid = new Map(table.map((process) => [process.pid, process])); |
| 823 | let rootIdentity: AcpPosixProcessIdentity | undefined = |
| 824 | input.root?.value ?? |
| 825 | [...input.ledger.values()].find((process) => process.pid === input.rootPid); |
| 826 | if (rootIdentity === undefined) { |
| 827 | rootIdentity = byPid.get(input.rootPid); |
| 828 | if (rootIdentity === undefined) { |
| 829 | throw new AcpProcessGroupTerminationError({ |
| 830 | detail: `ACP process ${input.rootPid} exited before its ownership ledger was captured`, |
| 831 | }); |
| 832 | } |
| 833 | const ownedRoot = { |
| 834 | ...rootIdentity, |
| 835 | parentExecutable: byPid.get(rootIdentity.ppid)?.executable, |
| 836 | parentStartTime: byPid.get(rootIdentity.ppid)?.startTime ?? "", |
| 837 | }; |
| 838 | input.ledger.set(processIdentityKey(rootIdentity), ownedRoot); |
| 839 | if (input.root !== undefined) input.root.value = ownedRoot; |
| 840 | } |
| 841 | // Expire stale identities to allow PID reuse; retain the root reservation for finalizer retries. |
| 842 | for (const [key, owned] of input.ledger.entries()) { |
| 843 | if (owned.pid === input.rootPid) continue; |
| 844 | const live = byPid.get(owned.pid); |
| 845 | if (live === undefined || !samePosixProcessIdentity(owned, live)) { |
| 846 | input.ledger.delete(key); |
| 847 | } |
| 848 | } |
| 849 | const children = new Map<number, Array<AcpPosixProcessIdentity>>(); |
| 850 | const retainedByPid = new Map( |
| 851 | [...input.ledger.values()] |
| 852 | .filter((owned) => samePosixProcessIdentity(owned, byPid.get(owned.pid))) |
| 853 | .map((owned) => [owned.pid, owned]), |
| 854 | ); |
| 855 | for (const process of table) { |
| 856 | const siblings = children.get(process.ppid) ?? []; |
| 857 | siblings.push(process); |
| 858 | children.set(process.ppid, siblings); |
| 859 | } |
| 860 | const pending = [...input.ledger.values()].filter((owned) => |
| 861 | samePosixProcessIdentity(owned, byPid.get(owned.pid)), |
| 862 | ); |
| 863 | const visited = new Set<number>(); |
| 864 | while (pending.length > 0) { |
| 865 | const parent = pending.shift(); |
| 866 | if (parent === undefined || visited.has(parent.pid)) continue; |
| 867 | visited.add(parent.pid); |
| 868 | const observedParent = byPid.get(parent.pid); |
| 869 | if (!samePosixProcessIdentity(parent, observedParent)) continue; |
| 870 | const refreshedParent = { ...parent, ...observedParent }; |
| 871 | input.ledger.set(processIdentityKey(parent), refreshedParent); |
| 872 | for (const process of children.get(refreshedParent.pid) ?? []) { |
| 873 | const reservedPid = retainedByPid.get(process.pid); |
| 874 | if (reservedPid !== undefined && !samePosixProcessIdentity(reservedPid, process)) continue; |
| 875 | const owned = |
| 876 | reservedPid === undefined |
| 877 | ? { |
| 878 | ...process, |
| 879 | parentExecutable: refreshedParent.executable, |
| 880 | parentStartTime: refreshedParent.startTime, |
| 881 | } |
| 882 | : { ...reservedPid, ...process }; |
| 883 | input.ledger.set(processIdentityKey(process), owned); |
| 884 | retainedByPid.set(process.pid, owned); |
| 885 | pending.push(owned); |
| 886 | } |
| 887 | } |
| 888 | return table; |
| 889 | } |
| 890 | |
| 891 | export function terminatePosixOwnedProcessTree(input: { |
| 892 | readonly controller: AcpPosixProcessTreeController; |
| 893 | readonly discoveryPasses?: number; |
| 894 | readonly grace?: Duration.Input; |
| 895 | readonly ledger?: Map<string, AcpOwnedPosixProcess>; |
| 896 | readonly root?: AcpPosixOwnershipRoot; |
| 897 | readonly rootPid: number; |
| 898 | }): Effect.Effect<void, AcpProcessGroupTerminationError> { |
| 899 | // Parent-chain discovery misses early double-forks; only pre-exec cgroups guarantee ownership. |
| 900 | const ledger = input.ledger ?? new Map<string, AcpOwnedPosixProcess>(); |
| 901 | |
| 902 | const fail = (detail: string, cause?: unknown) => |
| 903 | new AcpProcessGroupTerminationError({ detail, ...(cause === undefined ? {} : { cause }) }); |
| 904 | const snapshot = () => { |
| 905 | try { |
| 906 | return input.controller.snapshot(); |
| 907 | } catch (cause) { |
| 908 | throw fail(`Failed to snapshot ACP process tree ${input.rootPid}`, cause); |
| 909 | } |
| 910 | }; |
| 911 | const discover = (table: ReadonlyArray<AcpPosixProcessIdentity>) => |
| 912 | capturePosixOwnershipLedger({ |
| 913 | controller: input.controller, |
| 914 | ledger, |
| 915 | ...(input.root === undefined ? {} : { root: input.root }), |
| 916 | rootPid: input.rootPid, |
| 917 | table, |
| 918 | }); |
| 919 | const signalPhase = (signal: NodeJS.Signals, includeRoot: boolean) => { |
| 920 | const table = snapshot(); |
| 921 | discover(table); |
| 922 | const byPid = new Map(table.map((entry) => [entry.pid, entry])); |
| 923 | const current = input.controller.identity(process.pid); |
| 924 | if (current === undefined) throw fail("Cannot identify the current T3 process group"); |
| 925 | const ledgerByPid = new Map( |
| 926 | [...ledger.values()].map((process) => [process.pid, process] as const), |
| 927 | ); |
| 928 | const pending = [...ledger.values()].filter( |
| 929 | (candidate) => |
| 930 | (includeRoot || candidate.pid !== input.rootPid) && |
| 931 | samePosixProcessIdentity(candidate, byPid.get(candidate.pid)), |
| 932 | ); |
| 933 | const retainedByPid = new Map( |
| 934 | [...ledger.values()] |
| 935 | .filter((owned) => samePosixProcessIdentity(owned, byPid.get(owned.pid))) |
| 936 | .map((owned) => [owned.pid, owned]), |
| 937 | ); |
| 938 | const signalled = new Set<number>(); |
| 939 | while (pending.length > 0) { |
| 940 | pending.sort( |
| 941 | (left, right) => processDepth(right, ledgerByPid) - processDepth(left, ledgerByPid), |
| 942 | ); |
| 943 | const candidate = pending.shift(); |
| 944 | if (candidate === undefined || signalled.has(candidate.pid)) continue; |
| 945 | const observed = input.controller.identity(candidate.pid); |
| 946 | if ( |
| 947 | candidate.pid <= 1 || |
| 948 | candidate.pid === process.pid || |
| 949 | observed === undefined || |
| 950 | observed.pgid === current.pgid || |
| 951 | observed.sid === current.sid || |
| 952 | !samePosixProcessIdentity(candidate, observed) |
| 953 | ) { |
| 954 | continue; |
| 955 | } |
| 956 | for (const child of input.controller.childrenOf(candidate.pid)) { |
| 957 | if (child.ppid !== candidate.pid) continue; |
| 958 | const reservedPid = retainedByPid.get(child.pid); |
| 959 | if (reservedPid !== undefined && !samePosixProcessIdentity(reservedPid, child)) continue; |
| 960 | const owned = |
| 961 | reservedPid === undefined |
| 962 | ? { |
| 963 | ...child, |
| 964 | parentExecutable: observed.executable, |
| 965 | parentStartTime: observed.startTime, |
| 966 | } |
| 967 | : { ...reservedPid, ...child }; |
| 968 | ledger.set(processIdentityKey(child), owned); |
| 969 | ledgerByPid.set(child.pid, owned); |
| 970 | retainedByPid.set(child.pid, owned); |
| 971 | // Signal newly discovered children in this same pass (fork-during-kill). |
| 972 | if ( |
| 973 | (includeRoot || child.pid !== input.rootPid) && |
| 974 | !signalled.has(child.pid) && |
| 975 | samePosixProcessIdentity(owned, input.controller.identity(child.pid)) |
| 976 | ) { |
| 977 | pending.push(owned); |
| 978 | } |
| 979 | } |
| 980 | try { |
| 981 | // Node lacks pidfd_send_signal, so starttime checks still leave a read-to-kill race. |
| 982 | input.controller.signalProcess(candidate.pid, signal); |
| 983 | signalled.add(candidate.pid); |
| 984 | } catch (cause) { |
| 985 | if (samePosixProcessIdentity(candidate, input.controller.identity(candidate.pid))) { |
| 986 | throw fail(`Failed to signal ACP process ${candidate.pid}`, cause); |
| 987 | } |
| 988 | } |
| 989 | } |
| 990 | }; |
| 991 | |
| 992 | return Effect.gen(function* () { |
| 993 | const passes = Math.max(2, Math.min(input.discoveryPasses ?? 4, 8)); |
| 994 | for (let pass = 0; pass < passes; pass += 1) { |
| 995 | yield* Effect.try({ |
| 996 | try: () => signalPhase("SIGTERM", false), |
| 997 | catch: (cause) => cause as AcpProcessGroupTerminationError, |
| 998 | }); |
| 999 | yield* Effect.sleep("10 millis"); |
| 1000 | } |
| 1001 | yield* Effect.try({ |
| 1002 | try: () => signalPhase("SIGTERM", true), |
| 1003 | catch: (cause) => cause as AcpProcessGroupTerminationError, |
| 1004 | }); |
| 1005 | const grace = input.grace ?? "1 second"; |
| 1006 | if (grace !== 0) yield* Effect.sleep(grace); |
| 1007 | for (let pass = 0; pass < passes; pass += 1) { |
| 1008 | yield* Effect.try({ |
| 1009 | try: () => signalPhase("SIGKILL", true), |
| 1010 | catch: (cause) => cause as AcpProcessGroupTerminationError, |
| 1011 | }); |
| 1012 | yield* Effect.sleep("10 millis"); |
| 1013 | } |
| 1014 | const finalTable = snapshot(); |
| 1015 | discover(finalTable); |
| 1016 | const survivors = new Map(finalTable.map((entry) => [entry.pid, entry])); |
| 1017 | const residual = [...ledger.values()].filter((owned) => { |
| 1018 | const observed = survivors.get(owned.pid); |
| 1019 | if (!samePosixProcessIdentity(owned, observed) || observed === undefined) { |
| 1020 | return false; |
| 1021 | } |
| 1022 | return !posixProcessIsZombie(observed); |
| 1023 | }); |
| 1024 | if (residual.length > 0) { |
| 1025 | return yield* fail( |
| 1026 | `ACP process tree ${input.rootPid} retained owned processes: ${residual.map((entry) => entry.pid).join(", ")}`, |
| 1027 | ); |
| 1028 | } |
| 1029 | }).pipe(withWallClock); |
| 1030 | } |
| 1031 | |
| 1032 | function windowsTaskkillResultIsSuccess(exitCode: number, _output?: string): boolean { |
| 1033 | return exitCode === 0; |
| 1034 | } |
| 1035 | |
| 1036 | const terminateWindowsProcessTreeWithTaskkill = ( |
| 1037 | pid: number, |
| 1038 | ): Effect.Effect<void, AcpProcessGroupTerminationError, ChildProcessSpawner.ChildProcessSpawner> => |
| 1039 | Effect.scoped( |
| 1040 | Effect.gen(function* () { |
| 1041 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1042 | const taskkill = yield* spawner.spawn( |
| 1043 | ChildProcess.make("taskkill", ["/PID", String(pid), "/T", "/F"]), |
| 1044 | ); |
| 1045 | const outputFiber = yield* Stream.decodeText(taskkill.all).pipe( |
| 1046 | Stream.mkString, |
| 1047 | Effect.forkScoped, |
| 1048 | ); |
| 1049 | const exitCode = Number(yield* taskkill.exitCode); |
| 1050 | const output = yield* Fiber.join(outputFiber); |
| 1051 | // A missing leader cannot prove that inherited descendants exited. |
| 1052 | if (windowsTaskkillResultIsSuccess(exitCode, output)) return; |
| 1053 | const trimmedOutput = output.trim(); |
| 1054 | return yield* new AcpProcessGroupTerminationError({ |
| 1055 | detail: `taskkill exited ${exitCode} for ACP process tree ${pid}`, |
| 1056 | pid, |
| 1057 | exitCode, |
| 1058 | ...(trimmedOutput.length === 0 |
| 1059 | ? {} |
| 1060 | : { cause: trimmedOutput.length > 500 ? trimmedOutput.slice(0, 500) : trimmedOutput }), |
| 1061 | }); |
| 1062 | }), |
| 1063 | ).pipe( |
| 1064 | Effect.mapError((cause) => |
| 1065 | isAcpProcessGroupTerminationError(cause) |
| 1066 | ? cause |
| 1067 | : new AcpProcessGroupTerminationError({ |
| 1068 | cause, |
| 1069 | detail: `Failed to run taskkill for ACP process tree ${pid}`, |
| 1070 | pid, |
| 1071 | }), |
| 1072 | ), |
| 1073 | ); |
| 1074 | |
| 1075 | export function selectAcpAgentAuthMethod( |
| 1076 | authMethods: ReadonlyArray<EffectAcpSchema.AuthMethod> | undefined, |
| 1077 | preferredMethodId?: string, |
| 1078 | ): EffectAcpSchema.AuthMethod | undefined { |
| 1079 | const preferred = preferredMethodId?.trim(); |
| 1080 | if (preferred) { |
| 1081 | return authMethods?.find((method) => method.id === preferred); |
| 1082 | } |
| 1083 | return authMethods?.find((method) => method.type === undefined || method.type === "agent"); |
| 1084 | } |
| 1085 | |
| 1086 | function isAcpAuthenticationRequired(error: EffectAcpErrors.AcpError): boolean { |
| 1087 | return error._tag === "AcpRequestError" && error.code === -32000; |
| 1088 | } |
| 1089 | |
| 1090 | export interface AcpSessionRuntimeStartResult { |
| 1091 | readonly sessionId: string; |
| 1092 | readonly initializeResult: EffectAcpSchema.InitializeResponse; |
| 1093 | readonly sessionSetupResult: |
| 1094 | | EffectAcpSchema.ForkSessionResponse |
| 1095 | | EffectAcpSchema.LoadSessionResponse |
| 1096 | | EffectAcpSchema.NewSessionResponse |
| 1097 | | EffectAcpSchema.ResumeSessionResponse; |
| 1098 | readonly modelConfigId: string | undefined; |
| 1099 | } |
| 1100 | |
| 1101 | export interface AcpSessionActivationOptions { |
| 1102 | readonly mcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>; |
| 1103 | readonly acpMcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>; |
| 1104 | readonly httpMcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>; |
| 1105 | } |
| 1106 | |
| 1107 | export class AcpSessionRuntime extends Context.Service< |
| 1108 | AcpSessionRuntime, |
| 1109 | { |
| 1110 | readonly handleRequestPermission: EffectAcpClient.AcpClient["Service"]["handleRequestPermission"]; |
| 1111 | readonly handleElicitation: EffectAcpClient.AcpClient["Service"]["handleElicitation"]; |
| 1112 | readonly handleMcpConnect: EffectAcpClient.AcpClient["Service"]["handleMcpConnect"]; |
| 1113 | readonly handleMcpMessage: EffectAcpClient.AcpClient["Service"]["handleMcpMessage"]; |
| 1114 | readonly handleMcpDisconnect: EffectAcpClient.AcpClient["Service"]["handleMcpDisconnect"]; |
| 1115 | readonly handleMcpNotification: EffectAcpClient.AcpClient["Service"]["handleMcpNotification"]; |
| 1116 | readonly handleReadTextFile: EffectAcpClient.AcpClient["Service"]["handleReadTextFile"]; |
| 1117 | readonly handleWriteTextFile: EffectAcpClient.AcpClient["Service"]["handleWriteTextFile"]; |
| 1118 | readonly handleCreateTerminal: EffectAcpClient.AcpClient["Service"]["handleCreateTerminal"]; |
| 1119 | readonly handleTerminalOutput: EffectAcpClient.AcpClient["Service"]["handleTerminalOutput"]; |
| 1120 | readonly handleTerminalWaitForExit: EffectAcpClient.AcpClient["Service"]["handleTerminalWaitForExit"]; |
| 1121 | readonly handleTerminalKill: EffectAcpClient.AcpClient["Service"]["handleTerminalKill"]; |
| 1122 | readonly handleTerminalRelease: EffectAcpClient.AcpClient["Service"]["handleTerminalRelease"]; |
| 1123 | readonly handleSessionUpdate: EffectAcpClient.AcpClient["Service"]["handleSessionUpdate"]; |
| 1124 | readonly handleElicitationComplete: EffectAcpClient.AcpClient["Service"]["handleElicitationComplete"]; |
| 1125 | readonly handleUnknownExtRequest: EffectAcpClient.AcpClient["Service"]["handleUnknownExtRequest"]; |
| 1126 | readonly handleUnknownExtNotification: EffectAcpClient.AcpClient["Service"]["handleUnknownExtNotification"]; |
| 1127 | readonly handleExtRequest: EffectAcpClient.AcpClient["Service"]["handleExtRequest"]; |
| 1128 | readonly handleExtNotification: EffectAcpClient.AcpClient["Service"]["handleExtNotification"]; |
| 1129 | /** Reads capabilities without authentication, session creation, or MCP startup. */ |
| 1130 | readonly initialize: () => Effect.Effect< |
| 1131 | EffectAcpSchema.InitializeResponse, |
| 1132 | EffectAcpErrors.AcpError |
| 1133 | >; |
| 1134 | readonly authenticate?: (methodId: string) => Effect.Effect<void, EffectAcpErrors.AcpError>; |
| 1135 | readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>; |
| 1136 | readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>; |
| 1137 | readonly drainEvents: Effect.Effect<void>; |
| 1138 | readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>; |
| 1139 | readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>; |
| 1140 | /** The current configuration options, then each later change. */ |
| 1141 | readonly configOptionChanges: Stream.Stream<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>; |
| 1142 | readonly loadSession: ( |
| 1143 | sessionId: string, |
| 1144 | options?: AcpSessionActivationOptions, |
| 1145 | ) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>; |
| 1146 | readonly resumeSession: ( |
| 1147 | sessionId: string, |
| 1148 | options?: AcpSessionActivationOptions, |
| 1149 | ) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>; |
| 1150 | readonly forkSession: ( |
| 1151 | sessionId: string, |
| 1152 | options?: AcpSessionActivationOptions, |
| 1153 | meta?: NonNullable<EffectAcpSchema.ForkSessionRequest["_meta"]>, |
| 1154 | ) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>; |
| 1155 | readonly listSessions: ( |
| 1156 | cursor?: string, |
| 1157 | ) => Effect.Effect<EffectAcpSchema.ListSessionsResponse, EffectAcpErrors.AcpError>; |
| 1158 | readonly closeSession: ( |
| 1159 | sessionId?: string, |
| 1160 | ) => Effect.Effect<EffectAcpSchema.CloseSessionResponse, EffectAcpErrors.AcpError>; |
| 1161 | readonly deleteSession: ( |
| 1162 | sessionId: string, |
| 1163 | ) => Effect.Effect<EffectAcpSchema.DeleteSessionResponse, EffectAcpErrors.AcpError>; |
| 1164 | readonly listProviders: Effect.Effect< |
| 1165 | EffectAcpSchema.ListProvidersResponse, |
| 1166 | EffectAcpErrors.AcpError |
| 1167 | >; |
| 1168 | readonly setProvider: ( |
| 1169 | provider: EffectAcpSchema.SetProviderRequest, |
| 1170 | ) => Effect.Effect<EffectAcpSchema.SetProviderResponse, EffectAcpErrors.AcpError>; |
| 1171 | readonly disableProvider: ( |
| 1172 | providerId: string, |
| 1173 | ) => Effect.Effect<EffectAcpSchema.DisableProviderResponse, EffectAcpErrors.AcpError>; |
| 1174 | readonly logout: Effect.Effect<EffectAcpSchema.LogoutResponse, EffectAcpErrors.AcpError>; |
| 1175 | /** |
| 1176 | * options.dispatched settles when cancel can target this prompt. options.released lets the |
| 1177 | * next prompt go out while this one's response is still held; it still resolves this call. |
| 1178 | */ |
| 1179 | readonly prompt: ( |
| 1180 | payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">, |
| 1181 | options?: { |
| 1182 | readonly dispatched?: Deferred.Deferred<void>; |
| 1183 | readonly released?: Deferred.Deferred<void>; |
| 1184 | }, |
| 1185 | ) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>; |
| 1186 | readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>; |
| 1187 | readonly terminateProcessGroup?: Effect.Effect<void, AcpProcessGroupTerminationError>; |
| 1188 | readonly setMode: ( |
| 1189 | modeId: string, |
| 1190 | ) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>; |
| 1191 | readonly setSessionModel: ( |
| 1192 | modelId: string, |
| 1193 | meta?: EffectAcpSchema.SetSessionModelRequest["_meta"], |
| 1194 | ) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>; |
| 1195 | /** |
| 1196 | * Writes a session configuration option. A select value the option does |
| 1197 | * not list is refused unless `allowUnlistedValue` is set, for agents that |
| 1198 | * take any value and judge it themselves (a custom model id the agent |
| 1199 | * does not list). |
| 1200 | */ |
| 1201 | readonly setConfigOption: ( |
| 1202 | configId: string, |
| 1203 | value: string | boolean, |
| 1204 | options?: { |
| 1205 | readonly allowUnlistedValue?: boolean; |
| 1206 | /** Sends the write even when the cached value already matches it. */ |
| 1207 | readonly resendCurrentValue?: boolean; |
| 1208 | }, |
| 1209 | ) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>; |
| 1210 | readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>; |
| 1211 | readonly request: ( |
| 1212 | method: string, |
| 1213 | payload: unknown, |
| 1214 | ) => Effect.Effect<unknown, EffectAcpErrors.AcpError>; |
| 1215 | readonly notify: ( |
| 1216 | method: string, |
| 1217 | payload: unknown, |
| 1218 | ) => Effect.Effect<void, EffectAcpErrors.AcpError>; |
| 1219 | } |
| 1220 | >()("@t3tools/provider-acp/server/AcpSessionRuntime") {} |
| 1221 | |
| 1222 | interface AcpStartedState extends AcpSessionRuntimeStartResult {} |
| 1223 | |
| 1224 | type AcpStartState = |
| 1225 | | { readonly _tag: "NotStarted" } |
| 1226 | | { |
| 1227 | readonly _tag: "Starting"; |
| 1228 | readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>; |
| 1229 | } |
| 1230 | | { readonly _tag: "Started"; readonly result: AcpStartedState }; |
| 1231 | |
| 1232 | type AcpInitializeState = |
| 1233 | | { readonly _tag: "NotStarted" } |
| 1234 | | { |
| 1235 | readonly _tag: "Starting"; |
| 1236 | readonly deferred: Deferred.Deferred< |
| 1237 | EffectAcpSchema.InitializeResponse, |
| 1238 | EffectAcpErrors.AcpError |
| 1239 | >; |
| 1240 | } |
| 1241 | | { readonly _tag: "Started"; readonly result: EffectAcpSchema.InitializeResponse }; |
| 1242 | |
| 1243 | interface AcpAssistantSegmentState { |
| 1244 | readonly nextSegmentIndex: number; |
| 1245 | readonly activeItemId?: string; |
| 1246 | } |
| 1247 | |
| 1248 | interface EnsureActiveAssistantSegmentResult { |
| 1249 | readonly itemId: string; |
| 1250 | readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>; |
| 1251 | } |
| 1252 | |
| 1253 | interface AcpActivePrompt { |
| 1254 | readonly fiber: Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>; |
| 1255 | readonly completed: Deferred.Deferred<void>; |
| 1256 | /** Settles once the prompt is queued to the agent, or its call has ended without that. */ |
| 1257 | readonly queued: Deferred.Deferred<void>; |
| 1258 | } |
| 1259 | |
| 1260 | // A fiber stopped before its call began never settles queued, so its end counts too. |
| 1261 | const awaitPromptQueued = (prompt: AcpActivePrompt) => |
| 1262 | Effect.raceFirst(Deferred.await(prompt.queued), Fiber.await(prompt.fiber).pipe(Effect.asVoid)); |
| 1263 | |
| 1264 | export const make = Effect.fn("AcpSessionRuntime.make")(function* ( |
| 1265 | options: AcpSessionRuntimeOptions, |
| 1266 | ): Effect.fn.Return< |
| 1267 | AcpSessionRuntime["Service"], |
| 1268 | EffectAcpErrors.AcpError, |
| 1269 | ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope |
| 1270 | > { |
| 1271 | const random = yield* SecureRandom.SecureRandom; |
| 1272 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1273 | const hostPlatform = yield* HostProcess.Platform; |
| 1274 | const runtimeScope = yield* Scope.fork(yield* Scope.Scope); |
| 1275 | const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>(); |
| 1276 | const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined); |
| 1277 | const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallTrackedState>()); |
| 1278 | const shownToolCallIds = new Set<string>(); |
| 1279 | const assistantItemRuntimeId = yield* random.uuidV4().pipe( |
| 1280 | Effect.mapError( |
| 1281 | (cause) => |
| 1282 | new EffectAcpErrors.AcpTransportError({ |
| 1283 | detail: "Failed to generate an ACP assistant item runtime identifier.", |
| 1284 | cause, |
| 1285 | }), |
| 1286 | ), |
| 1287 | ); |
| 1288 | const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 }); |
| 1289 | const configOptionsRef = yield* SubscriptionRef.make(sessionConfigOptionsFromSetup(undefined)); |
| 1290 | const initializeStateRef = yield* Ref.make<AcpInitializeState>({ _tag: "NotStarted" }); |
| 1291 | const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" }); |
| 1292 | const startupMetadataRef = yield* Ref.make<ReadonlyArray<EffectAcpSchema.SessionNotification>>( |
| 1293 | [], |
| 1294 | ); |
| 1295 | const notificationSemaphore = yield* Semaphore.make(1); |
| 1296 | const terminationErrorRef = yield* Ref.make<Option.Option<EffectAcpErrors.AcpError>>( |
| 1297 | Option.none(), |
| 1298 | ); |
| 1299 | const stoppingRef = yield* Ref.make(false); |
| 1300 | const terminationRecorded = yield* Deferred.make<void>(); |
| 1301 | const stderrFailure = yield* Deferred.make<never, EffectAcpErrors.AcpError>(); |
| 1302 | const stderrTailRef = yield* Ref.make(""); |
| 1303 | const homeDirectory = yield* HostProcess.HomeDirectory; |
| 1304 | const stderrDrained = yield* Deferred.make<void>(); |
| 1305 | const runtimeClosed = yield* Deferred.make<void>(); |
| 1306 | const promptSerializationSemaphore = yield* Semaphore.make(1); |
| 1307 | const sessionLoadSemaphore = yield* Semaphore.make(1); |
| 1308 | const promptDispatchSemaphore = yield* Semaphore.make(1); |
| 1309 | const activePromptRef = yield* Ref.make<Option.Option<AcpActivePrompt>>(Option.none()); |
| 1310 | const assistantUpdatesOpenRef = yield* Ref.make(true); |
| 1311 | const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none()); |
| 1312 | // When replay idle makes a loaded session usable first, the agent's real |
| 1313 | // session/load response is still pending; it is adopted once it arrives. |
| 1314 | const lateSessionLoadRef = yield* Ref.make< |
| 1315 | Option.Option<{ |
| 1316 | readonly payload: EffectAcpSchema.LoadSessionRequest; |
| 1317 | readonly provisional: EffectAcpSchema.LoadSessionResponse; |
| 1318 | readonly response: Fiber.Fiber< |
| 1319 | Option.Option<EffectAcpSchema.LoadSessionResponse>, |
| 1320 | EffectAcpErrors.AcpError |
| 1321 | >; |
| 1322 | }> |
| 1323 | >(Option.none()); |
| 1324 | // Counts mode, config, and model writes sent to the agent and the mode and |
| 1325 | // config notifications it sent back. A late session/load response predates |
| 1326 | // all of them, even a write still pending or a notification that left the |
| 1327 | // mode state unchanged. |
| 1328 | const sessionChangeCountRef = yield* Ref.make(0); |
| 1329 | |
| 1330 | const ensureConnected = Effect.gen(function* () { |
| 1331 | const error = yield* Ref.get(terminationErrorRef); |
| 1332 | if (Option.isSome(error)) { |
| 1333 | return yield* error.value; |
| 1334 | } |
| 1335 | if (yield* Ref.get(stoppingRef)) { |
| 1336 | return yield* new EffectAcpErrors.AcpTransportError({ |
| 1337 | detail: "The ACP session runtime is closed.", |
| 1338 | cause: undefined, |
| 1339 | }); |
| 1340 | } |
| 1341 | }); |
| 1342 | |
| 1343 | const enrichProcessExitWithStderr = ( |
| 1344 | error: EffectAcpErrors.AcpError, |
| 1345 | ): Effect.Effect<EffectAcpErrors.AcpError> => |
| 1346 | error._tag !== "AcpProcessExitedError" || (error.stderr?.trim().length ?? 0) > 0 |
| 1347 | ? Effect.succeed(error) |
| 1348 | : Deferred.await(stderrDrained).pipe( |
| 1349 | Effect.timeout("250 millis"), |
| 1350 | Effect.ignore, |
| 1351 | Effect.andThen(Ref.get(stderrTailRef)), |
| 1352 | Effect.map((tail) => { |
| 1353 | const stderr = sanitizeAcpStderrExcerpt(tail, homeDirectory); |
| 1354 | return stderr.length === 0 |
| 1355 | ? error |
| 1356 | : new EffectAcpErrors.AcpProcessExitedError({ |
| 1357 | ...(error.code !== undefined ? { code: error.code } : {}), |
| 1358 | ...(error.signal !== undefined ? { signal: error.signal } : {}), |
| 1359 | ...(error.pid !== undefined ? { pid: error.pid } : {}), |
| 1360 | stderr, |
| 1361 | ...(error.cause !== undefined ? { cause: error.cause } : {}), |
| 1362 | }); |
| 1363 | }), |
| 1364 | ); |
| 1365 | |
| 1366 | const recordTermination = Effect.fn("AcpSessionRuntime.recordTermination")(function* ( |
| 1367 | error: EffectAcpErrors.AcpError, |
| 1368 | ) { |
| 1369 | if (yield* Ref.get(stoppingRef)) { |
| 1370 | return; |
| 1371 | } |
| 1372 | const enriched = yield* enrichProcessExitWithStderr(error); |
| 1373 | const firstTermination = yield* Ref.modify(terminationErrorRef, (current) => |
| 1374 | Option.isSome(current) |
| 1375 | ? ([false, current] as const) |
| 1376 | : ([true, Option.some(enriched)] as const), |
| 1377 | ); |
| 1378 | if (!firstTermination) { |
| 1379 | return yield* Deferred.await(terminationRecorded); |
| 1380 | } |
| 1381 | yield* Effect.gen(function* () { |
| 1382 | yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }); |
| 1383 | yield* Queue.offer(eventQueue, { _tag: "ConnectionTerminated", error: enriched }); |
| 1384 | yield* options.onTermination?.(enriched) ?? Effect.void; |
| 1385 | }).pipe(Effect.ensuring(Deferred.succeed(terminationRecorded, undefined))); |
| 1386 | }); |
| 1387 | |
| 1388 | const logRequest = (event: AcpSessionRequestLogEvent) => |
| 1389 | options.requestLogger ? options.requestLogger(event) : Effect.void; |
| 1390 | |
| 1391 | const runLoggedSessionWrite = <A>( |
| 1392 | method: string, |
| 1393 | payload: unknown, |
| 1394 | effect: Effect.Effect<A, EffectAcpErrors.AcpError>, |
| 1395 | ): Effect.Effect<A, EffectAcpErrors.AcpError> => |
| 1396 | Ref.update(sessionChangeCountRef, (count) => count + 1).pipe( |
| 1397 | Effect.andThen(runLoggedRequest(method, payload, effect)), |
| 1398 | ); |
| 1399 | |
| 1400 | const runLoggedRequest = <A>( |
| 1401 | method: string, |
| 1402 | payload: unknown, |
| 1403 | effect: Effect.Effect<A, EffectAcpErrors.AcpError>, |
| 1404 | ): Effect.Effect<A, EffectAcpErrors.AcpError> => |
| 1405 | logRequest({ method, payload, status: "started" }).pipe( |
| 1406 | Effect.flatMap(() => |
| 1407 | (options.onStderr ? Effect.raceFirst(effect, Deferred.await(stderrFailure)) : effect).pipe( |
| 1408 | Effect.catch((error) => |
| 1409 | enrichProcessExitWithStderr(error).pipe(Effect.flatMap(Effect.fail)), |
| 1410 | ), |
| 1411 | Effect.tap((result) => |
| 1412 | logRequest({ |
| 1413 | method, |
| 1414 | payload, |
| 1415 | status: "succeeded", |
| 1416 | result, |
| 1417 | }), |
| 1418 | ), |
| 1419 | Effect.onError((cause) => |
| 1420 | logRequest({ |
| 1421 | method, |
| 1422 | payload, |
| 1423 | status: "failed", |
| 1424 | cause, |
| 1425 | }), |
| 1426 | ), |
| 1427 | ), |
| 1428 | ), |
| 1429 | ); |
| 1430 | |
| 1431 | const spawnCommand = |
| 1432 | options.spawn.shell === false |
| 1433 | ? { command: options.spawn.command, args: options.spawn.args, shell: false } |
| 1434 | : yield* resolveSpawnCommand(options.spawn.command, options.spawn.args, { |
| 1435 | ...(options.spawn.env ? { env: options.spawn.env } : {}), |
| 1436 | extendEnv: options.spawn.extendEnv ?? true, |
| 1437 | }); |
| 1438 | const linuxCgroupLease = |
| 1439 | options.ownDescendantProcessGroups === true && options.processGroupPlatform === "linux" |
| 1440 | ? yield* Effect.sync(() => { |
| 1441 | try { |
| 1442 | if (options.linuxCgroupController === null) return undefined; |
| 1443 | return (options.linuxCgroupController ?? makeLinuxCgroupController()).create(); |
| 1444 | } catch { |
| 1445 | return undefined; |
| 1446 | } |
| 1447 | }) |
| 1448 | : undefined; |
| 1449 | // This is lifecycle containment for inherited provider work. It is not a |
| 1450 | // security boundary against a provider that can modify its delegated cgroup. |
| 1451 | if (linuxCgroupLease !== undefined) { |
| 1452 | yield* Scope.addFinalizer( |
| 1453 | runtimeScope, |
| 1454 | Effect.uninterruptible(terminateLinuxCgroupLease(linuxCgroupLease)).pipe( |
| 1455 | Effect.ignoreCause({ log: true }), |
| 1456 | ), |
| 1457 | ); |
| 1458 | } |
| 1459 | const containedTargetCommand = |
| 1460 | linuxCgroupLease === undefined || NodePath.isAbsolute(spawnCommand.command) |
| 1461 | ? spawnCommand.command |
| 1462 | : yield* Effect.gen(function* () { |
| 1463 | const resolved = resolveLinuxCgroupTargetCommand( |
| 1464 | spawnCommand.command, |
| 1465 | options.spawn.cwd ?? options.cwd, |
| 1466 | { ...process.env, ...options.spawn.env }, |
| 1467 | ); |
| 1468 | if (resolved !== undefined) return resolved; |
| 1469 | return yield* new EffectAcpErrors.AcpSpawnError({ |
| 1470 | command: options.spawn.command, |
| 1471 | cause: new Error("Contained ACP command was not found on PATH"), |
| 1472 | }); |
| 1473 | }); |
| 1474 | const agentScope = yield* AgentScope; |
| 1475 | const scopedLaunch = |
| 1476 | linuxCgroupLease !== undefined || spawnCommand.shell |
| 1477 | ? undefined |
| 1478 | : yield* agentScope.wrap({ |
| 1479 | command: spawnCommand.command, |
| 1480 | args: spawnCommand.args, |
| 1481 | name: "acp", |
| 1482 | threadId: yield* AgentScopeThreadId, |
| 1483 | env: { ...process.env, ...options.spawn.env }, |
| 1484 | }); |
| 1485 | const scopedSpawnCommand = |
| 1486 | scopedLaunch === undefined ? spawnCommand : { ...scopedLaunch, shell: false }; |
| 1487 | // Finalizers run in reverse order: reap detached work after terminating the agent. |
| 1488 | const scopeUnit = scopedLaunch?.unit; |
| 1489 | const stopScope = |
| 1490 | scopeUnit === undefined ? Effect.void : yield* Effect.cached(agentScope.stop(scopeUnit)); |
| 1491 | yield* Scope.addFinalizer(runtimeScope, stopScope); |
| 1492 | const containedSpawnCommand = |
| 1493 | linuxCgroupLease === undefined |
| 1494 | ? scopedSpawnCommand |
| 1495 | : { |
| 1496 | ...wrapCommandForLinuxCgroup(linuxCgroupLease, containedTargetCommand, spawnCommand.args), |
| 1497 | shell: false, |
| 1498 | }; |
| 1499 | const spawnEnvironment = |
| 1500 | linuxCgroupLease === undefined |
| 1501 | ? options.spawn.env |
| 1502 | : { |
| 1503 | ...options.spawn.env, |
| 1504 | ELECTRON_RUN_AS_NODE: "1", |
| 1505 | T3_ACP_CGROUP_WRAPPER: "1", |
| 1506 | }; |
| 1507 | const child = yield* spawner |
| 1508 | .spawn( |
| 1509 | ChildProcess.make(containedSpawnCommand.command, containedSpawnCommand.args, { |
| 1510 | ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}), |
| 1511 | ...(spawnEnvironment ? { env: spawnEnvironment } : {}), |
| 1512 | extendEnv: options.spawn.extendEnv ?? true, |
| 1513 | // Windows `detached` gives the child its own console, which breaks stdio pipes through |
| 1514 | // `.cmd` shims; taskkill /T cleans up the tree there without it. |
| 1515 | ...(options.ownDetachedProcessGroup === undefined |
| 1516 | ? {} |
| 1517 | : { detached: options.ownDetachedProcessGroup && hostPlatform !== "win32" }), |
| 1518 | shell: containedSpawnCommand.shell, |
| 1519 | }), |
| 1520 | ) |
| 1521 | .pipe( |
| 1522 | Effect.provideService(Scope.Scope, runtimeScope), |
| 1523 | Effect.mapError( |
| 1524 | (cause) => |
| 1525 | new EffectAcpErrors.AcpSpawnError({ |
| 1526 | command: options.spawn.command, |
| 1527 | cause, |
| 1528 | }), |
| 1529 | ), |
| 1530 | ); |
| 1531 | |
| 1532 | // Detached children can keep stdout open, delaying protocol termination. |
| 1533 | if (scopeUnit !== undefined) { |
| 1534 | yield* child.exitCode.pipe( |
| 1535 | Effect.matchEffect({ onFailure: () => stopScope, onSuccess: () => stopScope }), |
| 1536 | Effect.forkIn(runtimeScope), |
| 1537 | ); |
| 1538 | } |
| 1539 | |
| 1540 | const posixOwnershipLedger = new Map<string, AcpOwnedPosixProcess>(); |
| 1541 | const posixOwnershipFrontier = new Map<number, AcpOwnedPosixProcess>(); |
| 1542 | const posixOwnershipChildQueues = new Map<number, Array<number>>(); |
| 1543 | const posixOwnershipRoot: AcpPosixOwnershipRoot = { value: undefined }; |
| 1544 | const posixController = |
| 1545 | options.ownDescendantProcessGroups === true |
| 1546 | ? yield* Effect.try({ |
| 1547 | try: () => { |
| 1548 | if (options.posixProcessTreeController !== undefined) { |
| 1549 | return options.posixProcessTreeController; |
| 1550 | } |
| 1551 | if (options.processGroupPlatform === undefined) { |
| 1552 | throw new AcpProcessGroupTerminationError({ |
| 1553 | detail: "POSIX ACP descendant ownership requires a supported host platform", |
| 1554 | }); |
| 1555 | } |
| 1556 | return makePosixProcessTreeController(options.processGroupPlatform); |
| 1557 | }, |
| 1558 | catch: (cause) => |
| 1559 | new EffectAcpErrors.AcpSpawnError({ command: options.spawn.command, cause }), |
| 1560 | }) |
| 1561 | : undefined; |
| 1562 | if (posixController !== undefined) { |
| 1563 | const observeOwnership = () => |
| 1564 | observePosixOwnershipLedger({ |
| 1565 | childQueues: posixOwnershipChildQueues, |
| 1566 | controller: posixController, |
| 1567 | frontier: posixOwnershipFrontier, |
| 1568 | ledger: posixOwnershipLedger, |
| 1569 | root: posixOwnershipRoot, |
| 1570 | rootPid: Number(child.pid), |
| 1571 | }); |
| 1572 | yield* Effect.try({ |
| 1573 | try: observeOwnership, |
| 1574 | catch: (cause) => |
| 1575 | new EffectAcpErrors.AcpSpawnError({ command: options.spawn.command, cause }), |
| 1576 | }); |
| 1577 | // Cgroup teardown needs only the root identity captured above. |
| 1578 | if (linuxCgroupLease === undefined) { |
| 1579 | yield* observePosixOwnershipLedgerContinuously({ |
| 1580 | childQueues: posixOwnershipChildQueues, |
| 1581 | controller: posixController, |
| 1582 | frontier: posixOwnershipFrontier, |
| 1583 | ledger: posixOwnershipLedger, |
| 1584 | root: posixOwnershipRoot, |
| 1585 | rootPid: Number(child.pid), |
| 1586 | }).pipe(Effect.forkIn(runtimeScope)); |
| 1587 | } |
| 1588 | } |
| 1589 | |
| 1590 | const signalOwnedProcessGroup = (signal: NodeJS.Signals) => |
| 1591 | Effect.try({ |
| 1592 | try: () => { |
| 1593 | signalProcessGroup(Number(child.pid), signal); |
| 1594 | return true; |
| 1595 | }, |
| 1596 | catch: (cause) => |
| 1597 | new AcpProcessGroupTerminationError({ |
| 1598 | cause, |
| 1599 | detail: `Failed to signal ACP process group ${child.pid} with ${signal}`, |
| 1600 | }), |
| 1601 | }).pipe( |
| 1602 | Effect.catch((error) => { |
| 1603 | const cause = error.cause as NodeJS.ErrnoException | undefined; |
| 1604 | return cause?.code === "ESRCH" ? Effect.succeed(false) : Effect.fail(error); |
| 1605 | }), |
| 1606 | ); |
| 1607 | const terminateWindowsProcessTree = |
| 1608 | options.windowsProcessTreeTerminator ?? |
| 1609 | ((pid: number) => |
| 1610 | terminateWindowsProcessTreeWithTaskkill(pid).pipe( |
| 1611 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 1612 | )); |
| 1613 | const terminatePosixProcessTree = Effect.fn("AcpSessionRuntime.terminatePosixProcessTree")( |
| 1614 | function* (grace: Duration.Input, platformOverride?: NodeJS.Platform) { |
| 1615 | const platform = platformOverride ?? options.processGroupPlatform; |
| 1616 | if (platform === undefined || platform === "win32") { |
| 1617 | return yield* new AcpProcessGroupTerminationError({ |
| 1618 | detail: "POSIX ACP descendant ownership requires a supported host platform", |
| 1619 | }); |
| 1620 | } |
| 1621 | const controller = yield* Effect.try({ |
| 1622 | try: () => posixController ?? makePosixProcessTreeController(platform), |
| 1623 | catch: (cause) => |
| 1624 | isAcpProcessGroupTerminationError(cause) |
| 1625 | ? cause |
| 1626 | : new AcpProcessGroupTerminationError({ |
| 1627 | cause, |
| 1628 | detail: `Failed to initialize ACP descendant ownership on ${platform}`, |
| 1629 | }), |
| 1630 | }); |
| 1631 | yield* terminatePosixOwnedProcessTree({ |
| 1632 | controller, |
| 1633 | grace, |
| 1634 | ledger: posixOwnershipLedger, |
| 1635 | root: posixOwnershipRoot, |
| 1636 | rootPid: Number(child.pid), |
| 1637 | }); |
| 1638 | }, |
| 1639 | ); |
| 1640 | const terminateOwnedProcessGroupImpl = Effect.gen(function* () { |
| 1641 | if (options.ownDetachedProcessGroup !== true) return; |
| 1642 | if (options.processGroupPlatform === undefined) { |
| 1643 | return yield* new AcpProcessGroupTerminationError({ |
| 1644 | detail: "Detached ACP process-group ownership requires a host platform", |
| 1645 | }); |
| 1646 | } |
| 1647 | if (options.processGroupPlatform === "win32") { |
| 1648 | return yield* terminateWindowsProcessTree(Number(child.pid)); |
| 1649 | } |
| 1650 | if (linuxCgroupLease !== undefined) { |
| 1651 | if (posixController !== undefined) { |
| 1652 | yield* Effect.sync(() => |
| 1653 | signalLinuxCgroupRootTerm({ |
| 1654 | controller: posixController, |
| 1655 | lease: linuxCgroupLease, |
| 1656 | root: posixOwnershipRoot, |
| 1657 | }), |
| 1658 | ); |
| 1659 | } |
| 1660 | const grace = options.processGroupTerminationGrace ?? "1 second"; |
| 1661 | if (grace !== 0) yield* Effect.sleep(grace); |
| 1662 | return yield* terminateLinuxCgroupLease(linuxCgroupLease); |
| 1663 | } |
| 1664 | if (options.ownDescendantProcessGroups === true) { |
| 1665 | return yield* terminatePosixProcessTree(options.processGroupTerminationGrace ?? "1 second"); |
| 1666 | } |
| 1667 | const groupExisted = yield* signalOwnedProcessGroup("SIGTERM"); |
| 1668 | if (!groupExisted) return; |
| 1669 | const grace = options.processGroupTerminationGrace ?? "1 second"; |
| 1670 | if (grace !== 0) { |
| 1671 | yield* Effect.sleep(grace); |
| 1672 | } |
| 1673 | yield* signalOwnedProcessGroup("SIGKILL"); |
| 1674 | }).pipe(withWallClock); |
| 1675 | const terminateProcessGroup = yield* Effect.cached( |
| 1676 | Effect.uninterruptible(terminateOwnedProcessGroupImpl), |
| 1677 | ); |
| 1678 | if (options.ownDetachedProcessGroup === true) { |
| 1679 | const forceTerminateOwnedProcessGroup = |
| 1680 | hostPlatform === "win32" |
| 1681 | ? terminateWindowsProcessTreeWithTaskkill(Number(child.pid)).pipe( |
| 1682 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 1683 | ) |
| 1684 | : linuxCgroupLease !== undefined |
| 1685 | ? terminateLinuxCgroupLease(linuxCgroupLease) |
| 1686 | : options.ownDescendantProcessGroups === true |
| 1687 | ? terminatePosixProcessTree(0, hostPlatform) |
| 1688 | : signalOwnedProcessGroup("SIGKILL").pipe(Effect.asVoid); |
| 1689 | yield* Scope.addFinalizer( |
| 1690 | runtimeScope, |
| 1691 | Effect.uninterruptible(forceTerminateOwnedProcessGroup).pipe( |
| 1692 | Effect.ignoreCause({ log: true }), |
| 1693 | ), |
| 1694 | ); |
| 1695 | } |
| 1696 | yield* child.stderr.pipe( |
| 1697 | Stream.decodeText(), |
| 1698 | Stream.runForEach((chunk) => |
| 1699 | Ref.update(stderrTailRef, (current) => appendAcpStderrTail(current, chunk)).pipe( |
| 1700 | Effect.andThen( |
| 1701 | options.onStderr ? options.onStderr(chunk.slice(-maxStderrChunkLength)) : Effect.void, |
| 1702 | ), |
| 1703 | Effect.catch((error) => |
| 1704 | Effect.gen(function* () { |
| 1705 | yield* recordTermination(error); |
| 1706 | yield* Deferred.fail(stderrFailure, error); |
| 1707 | yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore); |
| 1708 | }), |
| 1709 | ), |
| 1710 | ), |
| 1711 | ), |
| 1712 | Effect.ensuring(Deferred.succeed(stderrDrained, undefined)), |
| 1713 | Effect.ignore, |
| 1714 | Effect.forkIn(runtimeScope), |
| 1715 | ); |
| 1716 | |
| 1717 | const acpContext = yield* Layer.build( |
| 1718 | EffectAcpClient.layerChildProcess(child, { |
| 1719 | ...(options.transformStdout ? { transformStdout: options.transformStdout } : {}), |
| 1720 | ...(options.transformSessionUpdate |
| 1721 | ? { transformSessionUpdate: options.transformSessionUpdate } |
| 1722 | : {}), |
| 1723 | ...(options.protocolLogging?.logIncoming !== undefined |
| 1724 | ? { logIncoming: options.protocolLogging.logIncoming } |
| 1725 | : {}), |
| 1726 | ...(options.protocolLogging?.logOutgoing !== undefined |
| 1727 | ? { logOutgoing: options.protocolLogging.logOutgoing } |
| 1728 | : {}), |
| 1729 | ...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}), |
| 1730 | ...(options.onIncomingRequest ? { onIncomingRequest: options.onIncomingRequest } : {}), |
| 1731 | onTermination: (error) => |
| 1732 | recordTermination(error).pipe( |
| 1733 | Effect.ensuring( |
| 1734 | Scope.close(runtimeScope, Exit.fail(error)).pipe(Effect.forkDetach, Effect.asVoid), |
| 1735 | ), |
| 1736 | ), |
| 1737 | ...(options.onOutgoingResponseFailure |
| 1738 | ? { onOutgoingResponseFailure: options.onOutgoingResponseFailure } |
| 1739 | : {}), |
| 1740 | ...(options.onOutgoingResponse ? { onOutgoingResponse: options.onOutgoingResponse } : {}), |
| 1741 | }), |
| 1742 | ).pipe(Effect.provideService(Scope.Scope, runtimeScope)); |
| 1743 | |
| 1744 | const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext)); |
| 1745 | |
| 1746 | // Counts applied `config_option_update`s; see setConfigOption. |
| 1747 | const configOptionUpdates = yield* Ref.make(0); |
| 1748 | const processSessionUpdate = (notification: EffectAcpSchema.SessionNotification) => |
| 1749 | (notification.update.sessionUpdate === "config_option_update" |
| 1750 | ? Ref.update(configOptionUpdates, (count) => count + 1).pipe( |
| 1751 | Effect.andThen(Ref.update(sessionChangeCountRef, (count) => count + 1)), |
| 1752 | ) |
| 1753 | : notification.update.sessionUpdate === "current_mode_update" |
| 1754 | ? Ref.update(sessionChangeCountRef, (count) => count + 1) |
| 1755 | : Effect.void |
| 1756 | ).pipe( |
| 1757 | Effect.andThen( |
| 1758 | handleSessionUpdate({ |
| 1759 | queue: eventQueue, |
| 1760 | modeStateRef, |
| 1761 | configOptionsRef, |
| 1762 | toolCallsRef, |
| 1763 | shownToolCallIds, |
| 1764 | assistantSegmentRef, |
| 1765 | assistantItemRuntimeId, |
| 1766 | params: notification, |
| 1767 | }), |
| 1768 | ), |
| 1769 | ); |
| 1770 | |
| 1771 | yield* acp.handleSessionUpdate((notification) => |
| 1772 | notificationSemaphore.withPermit( |
| 1773 | Effect.gen(function* () { |
| 1774 | if (Option.isSome(yield* Ref.get(terminationErrorRef))) { |
| 1775 | return; |
| 1776 | } |
| 1777 | const gate = yield* Ref.get(sessionLoadGateRef); |
| 1778 | // A different session can still have an in-flight prompt while this |
| 1779 | // load replays history, so quarantine only the loading session. |
| 1780 | const loadingThisSession = |
| 1781 | Option.isSome(gate) && |
| 1782 | gate.value.active && |
| 1783 | notification.sessionId === gate.value.sessionId; |
| 1784 | if ( |
| 1785 | loadingThisSession && |
| 1786 | sessionUpdateCountsAsLoadReplayActivity(notification, gate.value.sessionId) |
| 1787 | ) { |
| 1788 | const lastActivityAtMillis = yield* Clock.currentTimeMillis; |
| 1789 | yield* Ref.set( |
| 1790 | sessionLoadGateRef, |
| 1791 | Option.some({ |
| 1792 | ...gate.value, |
| 1793 | lastActivityAtMillis, |
| 1794 | }), |
| 1795 | ); |
| 1796 | } |
| 1797 | if (sessionUpdateIsReplay(notification)) { |
| 1798 | return; |
| 1799 | } |
| 1800 | const startState = yield* Ref.get(startStateRef); |
| 1801 | if (startState._tag === "Starting") { |
| 1802 | if (isStartupMetadataUpdate(notification)) { |
| 1803 | yield* Ref.update(startupMetadataRef, (current) => |
| 1804 | [ |
| 1805 | ...current.filter( |
| 1806 | (previous) => |
| 1807 | previous.sessionId !== notification.sessionId || |
| 1808 | previous.update.sessionUpdate !== notification.update.sessionUpdate, |
| 1809 | ), |
| 1810 | notification, |
| 1811 | ].slice(-maxStartupMetadataUpdates), |
| 1812 | ); |
| 1813 | } |
| 1814 | return; |
| 1815 | } |
| 1816 | if (loadingThisSession) { |
| 1817 | if (notification.update.sessionUpdate === "config_option_update") { |
| 1818 | const candidateConfigOptions = notification.update.configOptions; |
| 1819 | yield* Ref.update(sessionLoadGateRef, (current) => |
| 1820 | Option.isSome(current) |
| 1821 | ? Option.some({ ...current.value, candidateConfigOptions }) |
| 1822 | : current, |
| 1823 | ); |
| 1824 | } |
| 1825 | return; |
| 1826 | } |
| 1827 | // One runtime projects one root ACP session. Child-session updates need |
| 1828 | // explicit lineage routing and must never be flattened into this stream. |
| 1829 | if ( |
| 1830 | startState._tag !== "Started" || |
| 1831 | notification.sessionId !== startState.result.sessionId |
| 1832 | ) { |
| 1833 | return; |
| 1834 | } |
| 1835 | if ( |
| 1836 | !(yield* Ref.get(assistantUpdatesOpenRef)) && |
| 1837 | (notification.update.sessionUpdate === "agent_message_chunk" || |
| 1838 | notification.update.sessionUpdate === "agent_thought_chunk") |
| 1839 | ) { |
| 1840 | return; |
| 1841 | } |
| 1842 | yield* processSessionUpdate(notification); |
| 1843 | }), |
| 1844 | ), |
| 1845 | ); |
| 1846 | yield* Scope.addFinalizer( |
| 1847 | runtimeScope, |
| 1848 | Ref.set(stoppingRef, true).pipe(Effect.andThen(Deferred.succeed(runtimeClosed, undefined))), |
| 1849 | ); |
| 1850 | const initializeClientCapabilities = { |
| 1851 | fs: { |
| 1852 | readTextFile: false, |
| 1853 | writeTextFile: false, |
| 1854 | ...options.clientCapabilities?.fs, |
| 1855 | }, |
| 1856 | terminal: options.clientCapabilities?.terminal ?? false, |
| 1857 | // ACP v1 agents send session notices and compaction updates only to clients that advertise |
| 1858 | // them; v2 needs no capability. |
| 1859 | session: { ...options.clientCapabilities?.session, notices: {}, compaction: {} }, |
| 1860 | ...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}), |
| 1861 | ...(options.clientCapabilities?.elicitation |
| 1862 | ? { elicitation: options.clientCapabilities.elicitation } |
| 1863 | : {}), |
| 1864 | ...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}), |
| 1865 | } satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>; |
| 1866 | |
| 1867 | const getStartedState = Effect.gen(function* () { |
| 1868 | yield* ensureConnected; |
| 1869 | const state = yield* Ref.get(startStateRef); |
| 1870 | if (state._tag === "Started") { |
| 1871 | return state.result; |
| 1872 | } |
| 1873 | return yield* new EffectAcpErrors.AcpTransportError({ |
| 1874 | detail: "ACP session runtime has not been started", |
| 1875 | cause: "ACP session runtime has not been started", |
| 1876 | }); |
| 1877 | }); |
| 1878 | |
| 1879 | const validateConfigOptionValue = Effect.fn("AcpSessionRuntime.validateConfigOptionValue")( |
| 1880 | function* ( |
| 1881 | configId: string, |
| 1882 | value: string | boolean, |
| 1883 | allowUnlistedValue: boolean, |
| 1884 | ): Effect.fn.Return<void, EffectAcpErrors.AcpError> { |
| 1885 | const configOptions = yield* SubscriptionRef.get(configOptionsRef); |
| 1886 | const configOption = findSessionConfigOption(configOptions, configId); |
| 1887 | if (!configOption) { |
| 1888 | return; |
| 1889 | } |
| 1890 | if (configOption.type === "boolean") { |
| 1891 | if (typeof value === "boolean") { |
| 1892 | return; |
| 1893 | } |
| 1894 | return yield* new EffectAcpErrors.AcpRequestError({ |
| 1895 | code: -32602, |
| 1896 | errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected boolean`, |
| 1897 | data: { |
| 1898 | configId: configOption.id, |
| 1899 | expectedType: "boolean", |
| 1900 | receivedValue: value, |
| 1901 | }, |
| 1902 | }); |
| 1903 | } |
| 1904 | if (typeof value !== "string") { |
| 1905 | return yield* new EffectAcpErrors.AcpRequestError({ |
| 1906 | code: -32602, |
| 1907 | errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected string`, |
| 1908 | data: { |
| 1909 | configId: configOption.id, |
| 1910 | expectedType: "string", |
| 1911 | receivedValue: value, |
| 1912 | }, |
| 1913 | }); |
| 1914 | } |
| 1915 | const allowedValues = collectSessionConfigOptionValues(configOption); |
| 1916 | if (allowUnlistedValue || allowedValues.includes(value)) { |
| 1917 | return; |
| 1918 | } |
| 1919 | if ( |
| 1920 | configOption === findModelConfigOption(configOptions) && |
| 1921 | options.customModels?.includes(value) |
| 1922 | ) { |
| 1923 | return; |
| 1924 | } |
| 1925 | return yield* new EffectAcpErrors.AcpRequestError({ |
| 1926 | code: -32602, |
| 1927 | errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`, |
| 1928 | data: { |
| 1929 | configId: configOption.id, |
| 1930 | allowedValues, |
| 1931 | receivedValue: value, |
| 1932 | }, |
| 1933 | }); |
| 1934 | }, |
| 1935 | ); |
| 1936 | |
| 1937 | const updateConfigOptions = Effect.fn("AcpSessionRuntime.updateConfigOptions")(function* ( |
| 1938 | response: |
| 1939 | | EffectAcpSchema.SetSessionConfigOptionResponse |
| 1940 | | EffectAcpSchema.ForkSessionResponse |
| 1941 | | EffectAcpSchema.LoadSessionResponse |
| 1942 | | EffectAcpSchema.NewSessionResponse |
| 1943 | | EffectAcpSchema.ResumeSessionResponse, |
| 1944 | ) { |
| 1945 | const configOptions = sessionConfigOptionsFromSetup(response); |
| 1946 | yield* SubscriptionRef.set(configOptionsRef, configOptions); |
| 1947 | yield* Queue.offer(eventQueue, { |
| 1948 | _tag: "ConfigOptionsUpdated", |
| 1949 | configOptions, |
| 1950 | rawPayload: response, |
| 1951 | }); |
| 1952 | }); |
| 1953 | |
| 1954 | const updateCurrentModeId = (modeId: string): Effect.Effect<void> => |
| 1955 | Ref.update(modeStateRef, (current) => |
| 1956 | current ? { ...current, currentModeId: modeId } : current, |
| 1957 | ); |
| 1958 | |
| 1959 | const adoptSession = Effect.fn("AcpSessionRuntime.adoptSession")(function* ( |
| 1960 | sessionId: string, |
| 1961 | sessionSetupResult: |
| 1962 | | EffectAcpSchema.ForkSessionResponse |
| 1963 | | EffectAcpSchema.LoadSessionResponse |
| 1964 | | EffectAcpSchema.NewSessionResponse |
| 1965 | | EffectAcpSchema.ResumeSessionResponse, |
| 1966 | ): Effect.fn.Return<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError> { |
| 1967 | const current = yield* getStartedState; |
| 1968 | const meta = sessionSetupResult._meta; |
| 1969 | const syntheticReplayIdle = |
| 1970 | meta !== null && |
| 1971 | typeof meta === "object" && |
| 1972 | !Array.isArray(meta) && |
| 1973 | (meta as { readonly t3SessionLoadReady?: unknown }).t3SessionLoadReady === "replay_idle"; |
| 1974 | const extractedModelConfigId = extractModelConfigId(sessionSetupResult); |
| 1975 | const nextModelConfigId = |
| 1976 | extractedModelConfigId ?? (syntheticReplayIdle ? current.modelConfigId : undefined); |
| 1977 | const nextModeState = parseSessionModeState(sessionSetupResult); |
| 1978 | if (nextModeState !== undefined) { |
| 1979 | yield* Ref.set(modeStateRef, nextModeState); |
| 1980 | } else if (!syntheticReplayIdle) { |
| 1981 | yield* Ref.set(modeStateRef, undefined); |
| 1982 | } |
| 1983 | // Synthetic replay-idle load responses only carry initialize model/mode |
| 1984 | // meta; preserve live configOptions so setConfigOption still validates. |
| 1985 | if ( |
| 1986 | sessionSetupResult.configOptions !== undefined && |
| 1987 | sessionSetupResult.configOptions !== null |
| 1988 | ) { |
| 1989 | yield* SubscriptionRef.set( |
| 1990 | configOptionsRef, |
| 1991 | sessionConfigOptionsFromSetup(sessionSetupResult), |
| 1992 | ); |
| 1993 | } else if (!syntheticReplayIdle) { |
| 1994 | yield* SubscriptionRef.set( |
| 1995 | configOptionsRef, |
| 1996 | sessionConfigOptionsFromSetup(sessionSetupResult), |
| 1997 | ); |
| 1998 | } |
| 1999 | const nextState = { |
| 2000 | sessionId, |
| 2001 | initializeResult: current.initializeResult, |
| 2002 | sessionSetupResult, |
| 2003 | modelConfigId: nextModelConfigId, |
| 2004 | } satisfies AcpStartedState; |
| 2005 | yield* Ref.set(toolCallsRef, new Map()); |
| 2006 | yield* Ref.set(assistantSegmentRef, { nextSegmentIndex: 0 }); |
| 2007 | yield* Ref.set(startStateRef, { _tag: "Started", result: nextState }); |
| 2008 | return nextState; |
| 2009 | }); |
| 2010 | |
| 2011 | const cancelLateSessionLoad = Ref.getAndSet(lateSessionLoadRef, Option.none()).pipe( |
| 2012 | Effect.flatMap( |
| 2013 | Option.match({ |
| 2014 | onNone: () => Effect.void, |
| 2015 | onSome: (late) => Fiber.interrupt(late.response), |
| 2016 | }), |
| 2017 | ), |
| 2018 | Effect.asVoid, |
| 2019 | ); |
| 2020 | |
| 2021 | // Adopts the agent's real session/load response after a replay-idle start. |
| 2022 | // Anything that changed the session or its configuration in between is newer |
| 2023 | // than this response, so the response is dropped instead of applied. |
| 2024 | const followLateSessionLoad = Effect.fn("AcpSessionRuntime.followLateSessionLoad")(function* ( |
| 2025 | started: AcpStartedState, |
| 2026 | // Notifications counted after this baseline are newer than the response. |
| 2027 | provisionalChangeCount?: number, |
| 2028 | ) { |
| 2029 | const late = yield* Ref.get(lateSessionLoadRef); |
| 2030 | if (Option.isNone(late) || late.value.provisional !== started.sessionSetupResult) { |
| 2031 | return; |
| 2032 | } |
| 2033 | const { payload, response: lateFiber } = late.value; |
| 2034 | const provisionalConfigOptions = yield* SubscriptionRef.get(configOptionsRef); |
| 2035 | const provisionalModeState = yield* Ref.get(modeStateRef); |
| 2036 | const baselineChangeCount = provisionalChangeCount ?? (yield* Ref.get(sessionChangeCountRef)); |
| 2037 | const adoptLateResponse = Effect.fn("AcpSessionRuntime.adoptLateSessionLoad")(function* ( |
| 2038 | response: EffectAcpSchema.LoadSessionResponse, |
| 2039 | ) { |
| 2040 | const current = yield* Ref.get(lateSessionLoadRef); |
| 2041 | const startState = yield* Ref.get(startStateRef); |
| 2042 | if ( |
| 2043 | Option.isNone(current) || |
| 2044 | current.value.response !== lateFiber || |
| 2045 | startState._tag !== "Started" || |
| 2046 | startState.result !== started || |
| 2047 | (yield* Ref.get(stoppingRef)) || |
| 2048 | (yield* SubscriptionRef.get(configOptionsRef)) !== provisionalConfigOptions || |
| 2049 | (yield* Ref.get(modeStateRef)) !== provisionalModeState || |
| 2050 | (yield* Ref.get(sessionChangeCountRef)) !== baselineChangeCount |
| 2051 | ) { |
| 2052 | return; |
| 2053 | } |
| 2054 | yield* Ref.set(lateSessionLoadRef, Option.none()); |
| 2055 | const result = { |
| 2056 | ...started, |
| 2057 | sessionSetupResult: response, |
| 2058 | modelConfigId: extractModelConfigId(response) ?? started.modelConfigId, |
| 2059 | }; |
| 2060 | yield* Ref.set(startStateRef, { _tag: "Started", result }); |
| 2061 | const modeState = parseSessionModeState(response); |
| 2062 | if (modeState !== undefined) { |
| 2063 | yield* Ref.set(modeStateRef, modeState); |
| 2064 | } |
| 2065 | if (response.configOptions != null) { |
| 2066 | yield* processSessionUpdate({ |
| 2067 | sessionId: started.sessionId, |
| 2068 | update: { sessionUpdate: "config_option_update", configOptions: response.configOptions }, |
| 2069 | }); |
| 2070 | } else if (modeState !== undefined) { |
| 2071 | yield* processSessionUpdate({ |
| 2072 | sessionId: started.sessionId, |
| 2073 | update: { sessionUpdate: "current_mode_update", currentModeId: modeState.currentModeId }, |
| 2074 | }); |
| 2075 | } |
| 2076 | yield* Queue.offer(eventQueue, { _tag: "SessionSetupAdopted", result }); |
| 2077 | }); |
| 2078 | yield* Fiber.join(lateFiber).pipe( |
| 2079 | Effect.flatMap( |
| 2080 | Option.match({ |
| 2081 | onNone: () => |
| 2082 | Effect.fail( |
| 2083 | new EffectAcpErrors.AcpTransportError({ |
| 2084 | operation: "call-rpc", |
| 2085 | method: "session/load", |
| 2086 | detail: "session/load timed out after replay idle", |
| 2087 | cause: undefined, |
| 2088 | }), |
| 2089 | ), |
| 2090 | onSome: (response) => |
| 2091 | notificationSemaphore.withPermit(adoptLateResponse(response)).pipe( |
| 2092 | Effect.andThen( |
| 2093 | logRequest({ |
| 2094 | method: "session/load", |
| 2095 | payload, |
| 2096 | status: "succeeded", |
| 2097 | result: response, |
| 2098 | }), |
| 2099 | ), |
| 2100 | ), |
| 2101 | }), |
| 2102 | ), |
| 2103 | // Supersession and shutdown interrupt the request; only a real failure |
| 2104 | // or timeout is worth a failed log. |
| 2105 | Effect.onError((cause) => |
| 2106 | Cause.hasInterruptsOnly(cause) |
| 2107 | ? Effect.void |
| 2108 | : logRequest({ method: "session/load", payload, status: "failed", cause }), |
| 2109 | ), |
| 2110 | Effect.ignore, |
| 2111 | Effect.forkIn(runtimeScope), |
| 2112 | ); |
| 2113 | }); |
| 2114 | |
| 2115 | const runLoadSessionWithReplayIdle = ( |
| 2116 | loadPayload: EffectAcpSchema.LoadSessionRequest, |
| 2117 | initializeResult: EffectAcpSchema.InitializeResponse, |
| 2118 | ): Effect.Effect<EffectAcpSchema.LoadSessionResponse, EffectAcpErrors.AcpError> => |
| 2119 | sessionLoadSemaphore.withPermits(1)( |
| 2120 | Effect.gen(function* () { |
| 2121 | const sessionLoadTimeout = Duration.fromInputUnsafe( |
| 2122 | options.sessionLoadTimeout ?? defaultSessionLoadTimeout, |
| 2123 | ); |
| 2124 | const sessionLoadReplayIdleGap = Duration.fromInputUnsafe( |
| 2125 | options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap, |
| 2126 | ); |
| 2127 | |
| 2128 | yield* Ref.set( |
| 2129 | sessionLoadGateRef, |
| 2130 | Option.some({ |
| 2131 | active: true, |
| 2132 | sessionId: loadPayload.sessionId, |
| 2133 | lastActivityAtMillis: undefined, |
| 2134 | idleGap: sessionLoadReplayIdleGap, |
| 2135 | initializeResult, |
| 2136 | }), |
| 2137 | ); |
| 2138 | |
| 2139 | yield* cancelLateSessionLoad; |
| 2140 | return yield* Effect.gen(function* () { |
| 2141 | yield* logRequest({ |
| 2142 | method: "session/load", |
| 2143 | payload: loadPayload, |
| 2144 | status: "started", |
| 2145 | }); |
| 2146 | |
| 2147 | // Forked so a replay-idle win leaves the request running; the timeout |
| 2148 | // still bounds it and the runtime scope cancels it on shutdown. |
| 2149 | const responseFiber = yield* acp.agent |
| 2150 | .loadSession(loadPayload) |
| 2151 | .pipe(Effect.timeoutOption(sessionLoadTimeout), Effect.forkIn(runtimeScope)); |
| 2152 | const awaitResponse = Fiber.join(responseFiber).pipe( |
| 2153 | Effect.map(Option.map((response) => ({ response, provisional: false }))), |
| 2154 | ); |
| 2155 | const loadOrReplayIdle = |
| 2156 | options.sessionLoadReplayIdleReadiness === true |
| 2157 | ? Effect.gen(function* () { |
| 2158 | const idleFiber = yield* waitForSessionLoadReplayIdle({ |
| 2159 | gateRef: sessionLoadGateRef, |
| 2160 | }).pipe(Effect.forkIn(runtimeScope)); |
| 2161 | return yield* Effect.raceFirst( |
| 2162 | awaitResponse, |
| 2163 | Fiber.join(idleFiber).pipe( |
| 2164 | Effect.map((response) => Option.some({ response, provisional: true })), |
| 2165 | ), |
| 2166 | ).pipe(Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore))); |
| 2167 | }) |
| 2168 | : awaitResponse; |
| 2169 | const loaded = yield* loadOrReplayIdle.pipe( |
| 2170 | Effect.timeoutOption(sessionLoadTimeout), |
| 2171 | Effect.flatMap((result) => |
| 2172 | Effect.fromOption( |
| 2173 | Option.flatten(result), |
| 2174 | () => |
| 2175 | new EffectAcpErrors.AcpTransportError({ |
| 2176 | operation: "call-rpc", |
| 2177 | method: "session/load", |
| 2178 | detail: "session/load timed out waiting for RPC response or replay idle gap", |
| 2179 | cause: undefined, |
| 2180 | }), |
| 2181 | ), |
| 2182 | ), |
| 2183 | Effect.onExit((exit) => |
| 2184 | Exit.isSuccess(exit) && exit.value.provisional |
| 2185 | ? Effect.void |
| 2186 | : Fiber.interrupt(responseFiber).pipe(Effect.ignore), |
| 2187 | ), |
| 2188 | Effect.tap(({ response }) => |
| 2189 | logRequest({ |
| 2190 | method: "session/load", |
| 2191 | payload: loadPayload, |
| 2192 | status: "succeeded", |
| 2193 | result: response, |
| 2194 | }), |
| 2195 | ), |
| 2196 | Effect.onError((cause) => |
| 2197 | logRequest({ |
| 2198 | method: "session/load", |
| 2199 | payload: loadPayload, |
| 2200 | status: "failed", |
| 2201 | cause, |
| 2202 | }), |
| 2203 | ), |
| 2204 | ); |
| 2205 | |
| 2206 | const gate = yield* Ref.get(sessionLoadGateRef); |
| 2207 | const candidateConfigOptions = Option.isSome(gate) |
| 2208 | ? gate.value.candidateConfigOptions |
| 2209 | : undefined; |
| 2210 | const response = |
| 2211 | loaded.response.configOptions == null && candidateConfigOptions !== undefined |
| 2212 | ? { ...loaded.response, configOptions: candidateConfigOptions } |
| 2213 | : loaded.response; |
| 2214 | if (loaded.provisional) { |
| 2215 | yield* Ref.set( |
| 2216 | lateSessionLoadRef, |
| 2217 | Option.some({ payload: loadPayload, provisional: response, response: responseFiber }), |
| 2218 | ); |
| 2219 | } |
| 2220 | return response; |
| 2221 | }).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none()))); |
| 2222 | }), |
| 2223 | ); |
| 2224 | |
| 2225 | const setConfigOption = ( |
| 2226 | configId: string, |
| 2227 | value: string | boolean, |
| 2228 | options?: { |
| 2229 | readonly allowUnlistedValue?: boolean; |
| 2230 | readonly resendCurrentValue?: boolean; |
| 2231 | }, |
| 2232 | ): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> => |
| 2233 | validateConfigOptionValue(configId, value, options?.allowUnlistedValue === true).pipe( |
| 2234 | Effect.andThen(getStartedState), |
| 2235 | Effect.flatMap((started) => |
| 2236 | SubscriptionRef.get(configOptionsRef).pipe( |
| 2237 | Effect.flatMap((configOptions) => { |
| 2238 | const existing = findSessionConfigOption(configOptions, configId); |
| 2239 | if ( |
| 2240 | existing && |
| 2241 | options?.resendCurrentValue !== true && |
| 2242 | configOptionCurrentValueMatches(existing, value) |
| 2243 | ) { |
| 2244 | return Effect.succeed({ |
| 2245 | configOptions, |
| 2246 | } satisfies EffectAcpSchema.SetSessionConfigOptionResponse); |
| 2247 | } |
| 2248 | const requestPayload = |
| 2249 | typeof value === "boolean" |
| 2250 | ? ({ |
| 2251 | sessionId: started.sessionId, |
| 2252 | configId, |
| 2253 | type: "boolean", |
| 2254 | value, |
| 2255 | } satisfies EffectAcpSchema.SetSessionConfigOptionRequest) |
| 2256 | : ({ |
| 2257 | sessionId: started.sessionId, |
| 2258 | configId, |
| 2259 | value: String(value), |
| 2260 | } satisfies EffectAcpSchema.SetSessionConfigOptionRequest); |
| 2261 | // An update the agent pushed while the write was in flight is |
| 2262 | // newer than its result: Kiro 2.32 answers a `model` write |
| 2263 | // without `model`, then advertises it, and that update can be |
| 2264 | // handled before this fiber resumes. The result then stays out. |
| 2265 | return Ref.get(configOptionUpdates).pipe( |
| 2266 | Effect.flatMap((updatesBefore) => |
| 2267 | runLoggedSessionWrite( |
| 2268 | "session/set_config_option", |
| 2269 | requestPayload, |
| 2270 | acp.agent.setSessionConfigOption(requestPayload), |
| 2271 | ).pipe( |
| 2272 | Effect.tap((response) => |
| 2273 | Ref.get(configOptionUpdates).pipe( |
| 2274 | Effect.flatMap((updatesNow) => |
| 2275 | updatesNow === updatesBefore ? updateConfigOptions(response) : Effect.void, |
| 2276 | ), |
| 2277 | ), |
| 2278 | ), |
| 2279 | ), |
| 2280 | ), |
| 2281 | ); |
| 2282 | }), |
| 2283 | ), |
| 2284 | ), |
| 2285 | ); |
| 2286 | |
| 2287 | const initializeOnce = Effect.gen(function* () { |
| 2288 | const initializePayload = { |
| 2289 | protocolVersion: 2, |
| 2290 | clientCapabilities: initializeClientCapabilities, |
| 2291 | clientInfo: options.clientInfo, |
| 2292 | ...(options.initializeMeta === undefined ? {} : { _meta: options.initializeMeta }), |
| 2293 | } satisfies EffectAcpSchema.InitializeRequest; |
| 2294 | |
| 2295 | const initializeResult = yield* runLoggedRequest( |
| 2296 | "initialize", |
| 2297 | initializePayload, |
| 2298 | acp.agent.initialize(initializePayload), |
| 2299 | ); |
| 2300 | yield* options.onInitialized?.(initializeResult) ?? Effect.void; |
| 2301 | return initializeResult; |
| 2302 | }); |
| 2303 | |
| 2304 | const initialize = Effect.gen(function* () { |
| 2305 | yield* ensureConnected; |
| 2306 | const deferred = yield* Deferred.make< |
| 2307 | EffectAcpSchema.InitializeResponse, |
| 2308 | EffectAcpErrors.AcpError |
| 2309 | >(); |
| 2310 | const effect = yield* Ref.modify(initializeStateRef, (state) => { |
| 2311 | switch (state._tag) { |
| 2312 | case "Started": |
| 2313 | return [Effect.succeed(state.result), state] as const; |
| 2314 | case "Starting": |
| 2315 | return [Deferred.await(state.deferred), state] as const; |
| 2316 | case "NotStarted": |
| 2317 | return [ |
| 2318 | initializeOnce.pipe( |
| 2319 | Effect.tap((result) => |
| 2320 | Ref.set(initializeStateRef, { _tag: "Started", result }).pipe( |
| 2321 | Effect.andThen(Deferred.succeed(deferred, result)), |
| 2322 | ), |
| 2323 | ), |
| 2324 | Effect.onError((cause) => |
| 2325 | Deferred.failCause(deferred, cause).pipe( |
| 2326 | Effect.andThen(Ref.set(initializeStateRef, { _tag: "NotStarted" })), |
| 2327 | ), |
| 2328 | ), |
| 2329 | ), |
| 2330 | { _tag: "Starting", deferred } satisfies AcpInitializeState, |
| 2331 | ] as const; |
| 2332 | } |
| 2333 | }); |
| 2334 | return yield* effect; |
| 2335 | }); |
| 2336 | |
| 2337 | const sessionMcpServers = ( |
| 2338 | initializeResult: EffectAcpSchema.InitializeResponse, |
| 2339 | activationOptions?: AcpSessionActivationOptions, |
| 2340 | ): ReadonlyArray<EffectAcpSchema.McpServer> => { |
| 2341 | const mcpCapabilities = initializeResult.agentCapabilities?.mcpCapabilities; |
| 2342 | const acpServers = activationOptions?.acpMcpServers ?? options.acpMcpServers ?? []; |
| 2343 | if (mcpCapabilities?.acp === true && acpServers.length > 0) { |
| 2344 | return acpServers; |
| 2345 | } |
| 2346 | const httpServers = activationOptions?.httpMcpServers ?? options.httpMcpServers ?? []; |
| 2347 | if (mcpCapabilities?.http === true && httpServers.length > 0) { |
| 2348 | return httpServers; |
| 2349 | } |
| 2350 | return activationOptions?.mcpServers ?? options.mcpServers ?? []; |
| 2351 | }; |
| 2352 | |
| 2353 | const sessionSetupFields = (initializeResult: EffectAcpSchema.InitializeResponse) => { |
| 2354 | const meta = options.sessionMeta?.(initializeResult); |
| 2355 | return { |
| 2356 | ...(options.additionalDirectories?.length |
| 2357 | ? { additionalDirectories: options.additionalDirectories } |
| 2358 | : {}), |
| 2359 | ...(meta == null ? {} : { _meta: meta }), |
| 2360 | }; |
| 2361 | }; |
| 2362 | |
| 2363 | const startOnce = Effect.gen(function* () { |
| 2364 | const initializeResult = yield* initialize; |
| 2365 | |
| 2366 | const authenticateAfterRequired = Effect.fn("AcpSessionRuntime.authenticateAfterRequired")( |
| 2367 | function* ( |
| 2368 | authRequiredError: EffectAcpErrors.AcpError, |
| 2369 | ): Effect.fn.Return<void, EffectAcpErrors.AcpError> { |
| 2370 | const configuredAuthMethodId = options.authMethodId?.trim(); |
| 2371 | const authMethod = selectAcpAgentAuthMethod( |
| 2372 | initializeResult.authMethods, |
| 2373 | configuredAuthMethodId, |
| 2374 | ); |
| 2375 | if ( |
| 2376 | configuredAuthMethodId && |
| 2377 | initializeResult.authMethods !== undefined && |
| 2378 | authMethod === undefined |
| 2379 | ) { |
| 2380 | return yield* new EffectAcpErrors.AcpTransportError({ |
| 2381 | detail: `ACP agent did not advertise configured authentication method "${configuredAuthMethodId}"`, |
| 2382 | cause: { configuredAuthMethodId, authMethods: initializeResult.authMethods }, |
| 2383 | }); |
| 2384 | } |
| 2385 | if ( |
| 2386 | authMethod !== undefined && |
| 2387 | authMethod.type !== undefined && |
| 2388 | authMethod.type !== "agent" |
| 2389 | ) { |
| 2390 | return yield* new EffectAcpErrors.AcpTransportError({ |
| 2391 | detail: `ACP authentication method "${authMethod.id}" requires ${authMethod.type} authentication, which cannot run inside a headless provider session`, |
| 2392 | cause: authMethod, |
| 2393 | }); |
| 2394 | } |
| 2395 | |
| 2396 | const authMethodId = authMethod?.id ?? configuredAuthMethodId; |
| 2397 | if (!authMethodId) { |
| 2398 | return yield* authRequiredError; |
| 2399 | } |
| 2400 | |
| 2401 | const authenticatePayload = { |
| 2402 | methodId: authMethodId, |
| 2403 | } satisfies EffectAcpSchema.AuthenticateRequest; |
| 2404 | yield* runLoggedRequest( |
| 2405 | "authenticate", |
| 2406 | authenticatePayload, |
| 2407 | acp.agent.authenticate(authenticatePayload), |
| 2408 | ); |
| 2409 | }, |
| 2410 | ); |
| 2411 | |
| 2412 | const setupSession = Effect.gen(function* () { |
| 2413 | let sessionId: string; |
| 2414 | let sessionSetupResult: |
| 2415 | | EffectAcpSchema.LoadSessionResponse |
| 2416 | | EffectAcpSchema.NewSessionResponse |
| 2417 | | EffectAcpSchema.ResumeSessionResponse; |
| 2418 | const additionalDirectories = sessionSetupFields(initializeResult); |
| 2419 | if (options.resumeSessionId) { |
| 2420 | sessionId = options.resumeSessionId; |
| 2421 | if ( |
| 2422 | initializeResult.agentCapabilities?.loadSession === true && |
| 2423 | options.resumeMethod !== "resume" |
| 2424 | ) { |
| 2425 | const loadPayload = { |
| 2426 | sessionId, |
| 2427 | cwd: options.cwd, |
| 2428 | ...additionalDirectories, |
| 2429 | mcpServers: sessionMcpServers(initializeResult), |
| 2430 | } satisfies EffectAcpSchema.LoadSessionRequest; |
| 2431 | sessionSetupResult = yield* runLoadSessionWithReplayIdle(loadPayload, initializeResult); |
| 2432 | } else if (initializeResult.agentCapabilities?.sessionCapabilities?.resume != null) { |
| 2433 | const resumePayload = { |
| 2434 | sessionId, |
| 2435 | cwd: options.cwd, |
| 2436 | ...additionalDirectories, |
| 2437 | mcpServers: sessionMcpServers(initializeResult), |
| 2438 | } satisfies EffectAcpSchema.ResumeSessionRequest; |
| 2439 | sessionSetupResult = yield* runLoggedRequest( |
| 2440 | "session/resume", |
| 2441 | resumePayload, |
| 2442 | acp.agent.resumeSession(resumePayload), |
| 2443 | ); |
| 2444 | } else { |
| 2445 | return yield* new EffectAcpErrors.AcpRequestError({ |
| 2446 | code: -32601, |
| 2447 | errorMessage: "ACP agent does not advertise session/load or session/resume support", |
| 2448 | }); |
| 2449 | } |
| 2450 | } else { |
| 2451 | const createPayload = { |
| 2452 | cwd: options.cwd, |
| 2453 | mcpServers: sessionMcpServers(initializeResult), |
| 2454 | ...additionalDirectories, |
| 2455 | } satisfies EffectAcpSchema.NewSessionRequest; |
| 2456 | const created = yield* runLoggedRequest( |
| 2457 | "session/new", |
| 2458 | createPayload, |
| 2459 | acp.agent.createSession(createPayload), |
| 2460 | ); |
| 2461 | sessionId = created.sessionId; |
| 2462 | sessionSetupResult = created; |
| 2463 | } |
| 2464 | |
| 2465 | return { sessionId, sessionSetupResult }; |
| 2466 | }); |
| 2467 | |
| 2468 | if (options.authenticateEagerly === true) { |
| 2469 | // The configured method is authoritative here: Antigravity accepts |
| 2470 | // methods (API key, Vertex) it does not list in `initialize`. |
| 2471 | const authenticatePayload = { |
| 2472 | methodId: options.authMethodId ?? "", |
| 2473 | } satisfies EffectAcpSchema.AuthenticateRequest; |
| 2474 | yield* runLoggedRequest( |
| 2475 | "authenticate", |
| 2476 | authenticatePayload, |
| 2477 | acp.agent.authenticate(authenticatePayload), |
| 2478 | ); |
| 2479 | } |
| 2480 | const { sessionId, sessionSetupResult } = yield* setupSession.pipe( |
| 2481 | Effect.catchIf( |
| 2482 | (error) => |
| 2483 | !(!isAcpAuthenticationRequired(error) || options.authenticateOnAuthRequired === false), |
| 2484 | (error) => authenticateAfterRequired(error).pipe(Effect.andThen(setupSession)), |
| 2485 | ), |
| 2486 | ); |
| 2487 | |
| 2488 | yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult)); |
| 2489 | yield* SubscriptionRef.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult)); |
| 2490 | |
| 2491 | const nextState = { |
| 2492 | sessionId, |
| 2493 | initializeResult, |
| 2494 | sessionSetupResult, |
| 2495 | modelConfigId: extractModelConfigId(sessionSetupResult), |
| 2496 | } satisfies AcpStartedState; |
| 2497 | return nextState; |
| 2498 | }); |
| 2499 | |
| 2500 | const start = Effect.gen(function* () { |
| 2501 | yield* ensureConnected; |
| 2502 | const deferred = yield* Deferred.make<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>(); |
| 2503 | const effect = yield* Ref.modify(startStateRef, (state) => { |
| 2504 | switch (state._tag) { |
| 2505 | case "Started": |
| 2506 | return [Effect.succeed(state.result), state] as const; |
| 2507 | case "Starting": |
| 2508 | return [Deferred.await(state.deferred), state] as const; |
| 2509 | case "NotStarted": |
| 2510 | return [ |
| 2511 | startOnce.pipe( |
| 2512 | Effect.tap((result) => |
| 2513 | notificationSemaphore.withPermit( |
| 2514 | Effect.gen(function* () { |
| 2515 | const error = yield* Ref.get(terminationErrorRef); |
| 2516 | if (Option.isSome(error)) { |
| 2517 | return yield* error.value; |
| 2518 | } |
| 2519 | yield* Ref.set(startStateRef, { _tag: "Started", result }); |
| 2520 | const changeCountBeforeMetadata = yield* Ref.get(sessionChangeCountRef); |
| 2521 | const metadata = yield* Ref.getAndSet(startupMetadataRef, []); |
| 2522 | for (const notification of metadata) { |
| 2523 | if (notification.sessionId === result.sessionId) { |
| 2524 | yield* processSessionUpdate(notification); |
| 2525 | } |
| 2526 | } |
| 2527 | yield* followLateSessionLoad(result, changeCountBeforeMetadata); |
| 2528 | yield* Deferred.succeed(deferred, result); |
| 2529 | }), |
| 2530 | ), |
| 2531 | ), |
| 2532 | Effect.onError((cause) => |
| 2533 | Deferred.failCause(deferred, cause).pipe( |
| 2534 | Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })), |
| 2535 | Effect.andThen(Ref.set(startupMetadataRef, [])), |
| 2536 | ), |
| 2537 | ), |
| 2538 | ), |
| 2539 | { _tag: "Starting", deferred } satisfies AcpStartState, |
| 2540 | ] as const; |
| 2541 | } |
| 2542 | }); |
| 2543 | return yield* effect; |
| 2544 | }); |
| 2545 | |
| 2546 | const drainEvents = Effect.gen(function* () { |
| 2547 | if (yield* Ref.get(stoppingRef)) { |
| 2548 | return; |
| 2549 | } |
| 2550 | const acknowledge = yield* Deferred.make<void>(); |
| 2551 | yield* notificationSemaphore.withPermit( |
| 2552 | Effect.gen(function* () { |
| 2553 | if (Option.isNone(yield* Ref.get(activePromptRef))) { |
| 2554 | yield* Ref.set(assistantUpdatesOpenRef, false); |
| 2555 | yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }); |
| 2556 | } |
| 2557 | yield* Queue.offer(eventQueue, { _tag: "EventStreamBarrier", acknowledge }); |
| 2558 | }), |
| 2559 | ); |
| 2560 | yield* Effect.raceFirst(Deferred.await(acknowledge), Deferred.await(runtimeClosed)); |
| 2561 | }); |
| 2562 | |
| 2563 | const retireRuntime = Effect.fn("AcpSessionRuntime.retireRuntime")(function* ( |
| 2564 | error: EffectAcpErrors.AcpError, |
| 2565 | ) { |
| 2566 | yield* recordTermination(error); |
| 2567 | yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore); |
| 2568 | }); |
| 2569 | |
| 2570 | const joinPrompt = ( |
| 2571 | fiber: Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>, |
| 2572 | ) => |
| 2573 | Fiber.join(fiber).pipe( |
| 2574 | Effect.catchCauseIf( |
| 2575 | (cause) => options.cancelBehavior !== "wait-for-prompt" && Cause.hasInterruptsOnly(cause), |
| 2576 | (_cause) => |
| 2577 | Effect.succeed({ stopReason: "cancelled" } satisfies EffectAcpSchema.PromptResponse), |
| 2578 | ), |
| 2579 | ); |
| 2580 | |
| 2581 | const cancel = Effect.gen(function* () { |
| 2582 | const started = yield* getStartedState; |
| 2583 | const activePrompt = yield* Ref.get(activePromptRef); |
| 2584 | const cancelPayload = { |
| 2585 | sessionId: started.sessionId, |
| 2586 | ...(options.cancelMeta === undefined ? {} : { _meta: options.cancelMeta }), |
| 2587 | } satisfies EffectAcpSchema.CancelNotification; |
| 2588 | // An agent drops a cancel that reaches it before the prompt it targets, so the cancel waits |
| 2589 | // until the prompt is queued, for at most the cancel timeout. |
| 2590 | const promptQueued = Option.isSome(activePrompt) |
| 2591 | ? awaitPromptQueued(activePrompt.value).pipe( |
| 2592 | Effect.timeoutOption(options.cancelTimeout ?? defaultCancelTimeout), |
| 2593 | ) |
| 2594 | : Effect.void; |
| 2595 | if (options.cancelBehavior !== "wait-for-prompt") { |
| 2596 | if (options.interruptPromptOnCancel === false) { |
| 2597 | yield* promptQueued; |
| 2598 | return yield* acp.agent.cancel(cancelPayload); |
| 2599 | } |
| 2600 | if (Option.isSome(activePrompt)) { |
| 2601 | yield* Fiber.interrupt(activePrompt.value.fiber).pipe(Effect.ignore); |
| 2602 | } |
| 2603 | // Write cancel before a replacement prompt can reach the agent. |
| 2604 | yield* acp.agent.cancel(cancelPayload).pipe(Effect.ignore); |
| 2605 | return; |
| 2606 | } |
| 2607 | |
| 2608 | yield* promptQueued; |
| 2609 | yield* acp.agent.cancel(cancelPayload); |
| 2610 | if (Option.isNone(activePrompt)) { |
| 2611 | return; |
| 2612 | } |
| 2613 | const completed = yield* Effect.gen(function* () { |
| 2614 | const result = yield* Fiber.await(activePrompt.value.fiber); |
| 2615 | yield* Deferred.await(activePrompt.value.completed); |
| 2616 | if (Option.isNone(yield* Ref.get(terminationErrorRef))) { |
| 2617 | yield* drainEvents; |
| 2618 | } |
| 2619 | return result; |
| 2620 | }).pipe(Effect.timeoutOption(options.cancelTimeout ?? defaultCancelTimeout)); |
| 2621 | if (Option.isNone(completed)) { |
| 2622 | const error = new EffectAcpErrors.AcpTransportError({ |
| 2623 | operation: "call-rpc", |
| 2624 | method: "session/cancel", |
| 2625 | detail: "The ACP agent did not finish cancellation. Its process was stopped.", |
| 2626 | cause: undefined, |
| 2627 | }); |
| 2628 | yield* retireRuntime(error); |
| 2629 | return yield* error; |
| 2630 | } |
| 2631 | if (Exit.isFailure(completed.value)) { |
| 2632 | return yield* Effect.failCause(completed.value.cause); |
| 2633 | } |
| 2634 | }); |
| 2635 | |
| 2636 | return { |
| 2637 | handleRequestPermission: acp.handleRequestPermission, |
| 2638 | handleElicitation: acp.handleElicitation, |
| 2639 | handleMcpConnect: acp.handleMcpConnect, |
| 2640 | handleMcpMessage: acp.handleMcpMessage, |
| 2641 | handleMcpDisconnect: acp.handleMcpDisconnect, |
| 2642 | handleMcpNotification: acp.handleMcpNotification, |
| 2643 | handleReadTextFile: acp.handleReadTextFile, |
| 2644 | handleWriteTextFile: acp.handleWriteTextFile, |
| 2645 | handleCreateTerminal: acp.handleCreateTerminal, |
| 2646 | handleTerminalOutput: acp.handleTerminalOutput, |
| 2647 | handleTerminalWaitForExit: acp.handleTerminalWaitForExit, |
| 2648 | handleTerminalKill: acp.handleTerminalKill, |
| 2649 | handleTerminalRelease: acp.handleTerminalRelease, |
| 2650 | handleSessionUpdate: acp.handleSessionUpdate, |
| 2651 | handleElicitationComplete: acp.handleElicitationComplete, |
| 2652 | handleUnknownExtRequest: acp.handleUnknownExtRequest, |
| 2653 | handleUnknownExtNotification: acp.handleUnknownExtNotification, |
| 2654 | handleExtRequest: acp.handleExtRequest, |
| 2655 | handleExtNotification: acp.handleExtNotification, |
| 2656 | initialize: () => initialize, |
| 2657 | authenticate: (methodId) => |
| 2658 | initialize.pipe( |
| 2659 | Effect.andThen( |
| 2660 | runLoggedRequest("authenticate", { methodId }, acp.agent.authenticate({ methodId })), |
| 2661 | ), |
| 2662 | Effect.asVoid, |
| 2663 | ), |
| 2664 | start: () => start, |
| 2665 | getEvents: () => Stream.fromQueue(eventQueue), |
| 2666 | drainEvents, |
| 2667 | getModeState: Ref.get(modeStateRef), |
| 2668 | getConfigOptions: SubscriptionRef.get(configOptionsRef), |
| 2669 | configOptionChanges: SubscriptionRef.changes(configOptionsRef), |
| 2670 | loadSession: (sessionId, activationOptions) => |
| 2671 | start.pipe( |
| 2672 | Effect.flatMap((started) => { |
| 2673 | const requestPayload = { |
| 2674 | sessionId, |
| 2675 | cwd: options.cwd, |
| 2676 | ...sessionSetupFields(started.initializeResult), |
| 2677 | mcpServers: sessionMcpServers(started.initializeResult, activationOptions), |
| 2678 | } satisfies EffectAcpSchema.LoadSessionRequest; |
| 2679 | return runLoadSessionWithReplayIdle(requestPayload, started.initializeResult); |
| 2680 | }), |
| 2681 | Effect.flatMap((response) => adoptSession(sessionId, response)), |
| 2682 | Effect.tap((started) => followLateSessionLoad(started)), |
| 2683 | ), |
| 2684 | resumeSession: (sessionId, activationOptions) => |
| 2685 | start.pipe( |
| 2686 | Effect.tap(() => cancelLateSessionLoad), |
| 2687 | Effect.flatMap((started) => { |
| 2688 | const requestPayload = { |
| 2689 | sessionId, |
| 2690 | cwd: options.cwd, |
| 2691 | ...sessionSetupFields(started.initializeResult), |
| 2692 | mcpServers: sessionMcpServers(started.initializeResult, activationOptions), |
| 2693 | } satisfies EffectAcpSchema.ResumeSessionRequest; |
| 2694 | return runLoggedRequest( |
| 2695 | "session/resume", |
| 2696 | requestPayload, |
| 2697 | acp.agent.resumeSession(requestPayload), |
| 2698 | ); |
| 2699 | }), |
| 2700 | Effect.flatMap((response) => adoptSession(sessionId, response)), |
| 2701 | ), |
| 2702 | forkSession: (sessionId, activationOptions, meta) => |
| 2703 | start.pipe( |
| 2704 | Effect.tap(() => cancelLateSessionLoad), |
| 2705 | Effect.flatMap((started) => { |
| 2706 | const requestPayload = { |
| 2707 | sessionId, |
| 2708 | cwd: options.cwd, |
| 2709 | ...sessionSetupFields(started.initializeResult), |
| 2710 | mcpServers: sessionMcpServers(started.initializeResult, activationOptions), |
| 2711 | ...(meta === undefined ? {} : { _meta: meta }), |
| 2712 | } satisfies EffectAcpSchema.ForkSessionRequest; |
| 2713 | return runLoggedRequest( |
| 2714 | "session/fork", |
| 2715 | requestPayload, |
| 2716 | acp.agent.forkSession(requestPayload), |
| 2717 | ); |
| 2718 | }), |
| 2719 | Effect.flatMap((response) => adoptSession(response.sessionId, response)), |
| 2720 | ), |
| 2721 | listSessions: (cursor) => { |
| 2722 | const requestPayload = { |
| 2723 | cwd: options.cwd, |
| 2724 | ...(cursor === undefined ? {} : { cursor }), |
| 2725 | } satisfies EffectAcpSchema.ListSessionsRequest; |
| 2726 | return initialize.pipe( |
| 2727 | Effect.filterOrFail( |
| 2728 | (initialized) => initialized.agentCapabilities?.sessionCapabilities?.list != null, |
| 2729 | () => |
| 2730 | new EffectAcpErrors.AcpRequestError({ |
| 2731 | code: -32601, |
| 2732 | errorMessage: "ACP agent does not advertise session/list support", |
| 2733 | }), |
| 2734 | ), |
| 2735 | Effect.andThen( |
| 2736 | runLoggedRequest("session/list", requestPayload, acp.agent.listSessions(requestPayload)), |
| 2737 | ), |
| 2738 | ); |
| 2739 | }, |
| 2740 | closeSession: (sessionId) => |
| 2741 | start.pipe( |
| 2742 | Effect.flatMap((started) => { |
| 2743 | const requestPayload = { |
| 2744 | sessionId: sessionId ?? started.sessionId, |
| 2745 | } satisfies EffectAcpSchema.CloseSessionRequest; |
| 2746 | return runLoggedRequest( |
| 2747 | "session/close", |
| 2748 | requestPayload, |
| 2749 | acp.agent.closeSession(requestPayload), |
| 2750 | ); |
| 2751 | }), |
| 2752 | ), |
| 2753 | deleteSession: (sessionId) => |
| 2754 | initialize.pipe( |
| 2755 | Effect.filterOrFail( |
| 2756 | (initialized) => initialized.agentCapabilities?.sessionCapabilities?.delete != null, |
| 2757 | () => |
| 2758 | new EffectAcpErrors.AcpRequestError({ |
| 2759 | code: -32601, |
| 2760 | errorMessage: "ACP agent does not advertise session/delete support", |
| 2761 | }), |
| 2762 | ), |
| 2763 | Effect.andThen( |
| 2764 | runLoggedRequest("session/delete", { sessionId }, acp.agent.deleteSession({ sessionId })), |
| 2765 | ), |
| 2766 | ), |
| 2767 | listProviders: initialize.pipe( |
| 2768 | Effect.filterOrFail( |
| 2769 | (initialized) => initialized.agentCapabilities?.providers != null, |
| 2770 | () => |
| 2771 | new EffectAcpErrors.AcpRequestError({ |
| 2772 | code: -32601, |
| 2773 | errorMessage: "ACP agent does not advertise provider configuration support", |
| 2774 | }), |
| 2775 | ), |
| 2776 | Effect.andThen(runLoggedRequest("providers/list", {}, acp.agent.listProviders({}))), |
| 2777 | ), |
| 2778 | setProvider: (provider) => |
| 2779 | initialize.pipe( |
| 2780 | Effect.filterOrFail( |
| 2781 | (initialized) => initialized.agentCapabilities?.providers != null, |
| 2782 | () => |
| 2783 | new EffectAcpErrors.AcpRequestError({ |
| 2784 | code: -32601, |
| 2785 | errorMessage: "ACP agent does not advertise provider configuration support", |
| 2786 | }), |
| 2787 | ), |
| 2788 | Effect.andThen( |
| 2789 | runLoggedRequest( |
| 2790 | "providers/set", |
| 2791 | { |
| 2792 | ...provider, |
| 2793 | ...(provider.headers === undefined |
| 2794 | ? {} |
| 2795 | : { |
| 2796 | headers: Object.fromEntries( |
| 2797 | Object.keys(provider.headers).map((name) => [name, "[redacted]"]), |
| 2798 | ), |
| 2799 | }), |
| 2800 | }, |
| 2801 | acp.agent.setProvider(provider), |
| 2802 | ), |
| 2803 | ), |
| 2804 | ), |
| 2805 | disableProvider: (providerId) => { |
| 2806 | const request = { providerId } satisfies EffectAcpSchema.DisableProviderRequest; |
| 2807 | return initialize.pipe( |
| 2808 | Effect.filterOrFail( |
| 2809 | (initialized) => initialized.agentCapabilities?.providers != null, |
| 2810 | () => |
| 2811 | new EffectAcpErrors.AcpRequestError({ |
| 2812 | code: -32601, |
| 2813 | errorMessage: "ACP agent does not advertise provider configuration support", |
| 2814 | }), |
| 2815 | ), |
| 2816 | Effect.andThen( |
| 2817 | runLoggedRequest("providers/disable", request, acp.agent.disableProvider(request)), |
| 2818 | ), |
| 2819 | ); |
| 2820 | }, |
| 2821 | logout: initialize.pipe( |
| 2822 | Effect.filterOrFail( |
| 2823 | (initialized) => initialized.agentCapabilities?.auth?.logout != null, |
| 2824 | () => |
| 2825 | new EffectAcpErrors.AcpRequestError({ |
| 2826 | code: -32601, |
| 2827 | errorMessage: "ACP agent does not advertise logout support", |
| 2828 | }), |
| 2829 | ), |
| 2830 | Effect.andThen(runLoggedRequest("logout", {}, acp.agent.logout({}))), |
| 2831 | ), |
| 2832 | prompt: (payload, promptOptions?) => |
| 2833 | promptSerializationSemaphore |
| 2834 | .withPermit( |
| 2835 | Effect.acquireUseRelease( |
| 2836 | promptDispatchSemaphore.withPermit( |
| 2837 | Effect.gen(function* () { |
| 2838 | const started = yield* getStartedState; |
| 2839 | yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }); |
| 2840 | yield* Ref.set(assistantUpdatesOpenRef, true); |
| 2841 | const requestPayload = { |
| 2842 | sessionId: started.sessionId, |
| 2843 | ...payload, |
| 2844 | } satisfies EffectAcpSchema.PromptRequest; |
| 2845 | const completed = yield* Deferred.make<void>(); |
| 2846 | const queued = yield* Deferred.make<void>(); |
| 2847 | const fiber = yield* runLoggedRequest( |
| 2848 | "session/prompt", |
| 2849 | requestPayload, |
| 2850 | acp.agent |
| 2851 | .prompt(requestPayload) |
| 2852 | .pipe( |
| 2853 | Effect.provideService(EffectAcpProtocol.AcpOutgoingQueued, queued), |
| 2854 | Effect.ensuring(Deferred.succeed(queued, undefined)), |
| 2855 | ), |
| 2856 | ).pipe(Effect.forkIn(runtimeScope)); |
| 2857 | const active = { fiber, completed, queued } satisfies AcpActivePrompt; |
| 2858 | yield* Ref.set(activePromptRef, Option.some(active)); |
| 2859 | if (promptOptions?.dispatched) { |
| 2860 | yield* Deferred.succeed(promptOptions.dispatched, undefined); |
| 2861 | } |
| 2862 | return active; |
| 2863 | }).pipe(notificationSemaphore.withPermit), |
| 2864 | ), |
| 2865 | (activePrompt) => { |
| 2866 | const settled = joinPrompt(activePrompt.fiber).pipe( |
| 2867 | Effect.tap(() => |
| 2868 | closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }), |
| 2869 | ), |
| 2870 | Effect.map((response) => ({ _tag: "Settled" as const, response })), |
| 2871 | ); |
| 2872 | return promptOptions?.released === undefined |
| 2873 | ? settled |
| 2874 | : Effect.raceFirst( |
| 2875 | settled, |
| 2876 | Deferred.await(promptOptions.released).pipe( |
| 2877 | Effect.as({ _tag: "Released" as const, fiber: activePrompt.fiber }), |
| 2878 | ), |
| 2879 | ); |
| 2880 | }, |
| 2881 | (activePrompt, result) => |
| 2882 | Effect.gen(function* () { |
| 2883 | if (Exit.isSuccess(result) && result.value._tag === "Released") { |
| 2884 | yield* Ref.set(activePromptRef, Option.none()); |
| 2885 | yield* Deferred.succeed(activePrompt.completed, undefined); |
| 2886 | return; |
| 2887 | } |
| 2888 | if ( |
| 2889 | options.cancelBehavior === "wait-for-prompt" && |
| 2890 | Exit.isFailure(result) && |
| 2891 | Cause.hasInterrupts(result.cause) |
| 2892 | ) { |
| 2893 | yield* retireRuntime( |
| 2894 | new EffectAcpErrors.AcpTransportError({ |
| 2895 | method: "session/prompt", |
| 2896 | detail: "The ACP prompt stopped before the agent confirmed completion.", |
| 2897 | cause: undefined, |
| 2898 | }), |
| 2899 | ); |
| 2900 | } |
| 2901 | yield* Fiber.interrupt(activePrompt.fiber).pipe(Effect.ignore); |
| 2902 | yield* Ref.set(activePromptRef, Option.none()); |
| 2903 | yield* Deferred.succeed(activePrompt.completed, undefined); |
| 2904 | }), |
| 2905 | ), |
| 2906 | ) |
| 2907 | .pipe( |
| 2908 | Effect.flatMap((outcome) => |
| 2909 | outcome._tag === "Settled" |
| 2910 | ? Effect.succeed(outcome.response) |
| 2911 | : joinPrompt(outcome.fiber), |
| 2912 | ), |
| 2913 | ), |
| 2914 | // A cancel that waits for its prompt holds the dispatch permit, so a next prompt cannot reach |
| 2915 | // the agent ahead of it and take the cancel meant for the prompt before. |
| 2916 | cancel: |
| 2917 | options.cancelBehavior === "wait-for-prompt" || options.interruptPromptOnCancel === false |
| 2918 | ? promptDispatchSemaphore.withPermit(cancel) |
| 2919 | : cancel, |
| 2920 | ...(options.ownDetachedProcessGroup === true ? { terminateProcessGroup } : {}), |
| 2921 | // A session's mode is its `category: "mode"` config option. ACP v1 agents |
| 2922 | // that only advertise `modes` (gemini-cli) take `session/set_mode` |
| 2923 | // instead, which ACP v2 removed. |
| 2924 | setMode: Effect.fn("AcpSessionRuntime.setMode")(function* (modeId) { |
| 2925 | const modeState = yield* Ref.get(modeStateRef); |
| 2926 | if (modeState?.currentModeId === modeId) { |
| 2927 | return {} satisfies EffectAcpSchema.SetSessionModeResponse; |
| 2928 | } |
| 2929 | const modeConfigOption = (yield* SubscriptionRef.get(configOptionsRef))?.find( |
| 2930 | (option) => option.category === "mode" && option.type === "select", |
| 2931 | ); |
| 2932 | if (modeConfigOption === undefined && modeState !== undefined) { |
| 2933 | const started = yield* getStartedState; |
| 2934 | const payload = { sessionId: started.sessionId, modeId }; |
| 2935 | yield* runLoggedSessionWrite( |
| 2936 | "session/set_mode", |
| 2937 | payload, |
| 2938 | acp.agent.setSessionMode(payload), |
| 2939 | ); |
| 2940 | yield* updateCurrentModeId(modeId); |
| 2941 | return {} satisfies EffectAcpSchema.SetSessionModeResponse; |
| 2942 | } |
| 2943 | const response = yield* setConfigOption(modeConfigOption?.id ?? "mode", modeId); |
| 2944 | const reported = parseSessionModeState({ configOptions: response.configOptions }); |
| 2945 | if (reported === undefined) { |
| 2946 | yield* updateCurrentModeId(modeId); |
| 2947 | } else { |
| 2948 | yield* updateCurrentModeId(reported.currentModeId); |
| 2949 | } |
| 2950 | return {} satisfies EffectAcpSchema.SetSessionModeResponse; |
| 2951 | }), |
| 2952 | setSessionModel: (modelId, meta) => |
| 2953 | getStartedState.pipe( |
| 2954 | Effect.flatMap((started) => { |
| 2955 | const payload = { |
| 2956 | sessionId: started.sessionId, |
| 2957 | modelId, |
| 2958 | ...(meta === undefined ? {} : { _meta: meta }), |
| 2959 | }; |
| 2960 | return runLoggedSessionWrite( |
| 2961 | "session/set_model", |
| 2962 | payload, |
| 2963 | acp.agent.setSessionModel(payload), |
| 2964 | ); |
| 2965 | }), |
| 2966 | ), |
| 2967 | setConfigOption, |
| 2968 | setModel: (model) => |
| 2969 | getStartedState.pipe( |
| 2970 | Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)), |
| 2971 | Effect.asVoid, |
| 2972 | ), |
| 2973 | |
| 2974 | request: (method, payload) => |
| 2975 | ensureConnected.pipe( |
| 2976 | Effect.andThen(runLoggedRequest(method, payload, acp.raw.request(method, payload))), |
| 2977 | ), |
| 2978 | notify: (method, payload) => |
| 2979 | ensureConnected.pipe(Effect.andThen(acp.raw.notify(method, payload))), |
| 2980 | } satisfies AcpSessionRuntime["Service"]; |
| 2981 | }); |
| 2982 | |
| 2983 | export const layer = ( |
| 2984 | options: AcpSessionRuntimeOptions, |
| 2985 | ): Layer.Layer< |
| 2986 | AcpSessionRuntime, |
| 2987 | EffectAcpErrors.AcpError, |
| 2988 | ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom |
| 2989 | > => Layer.effect(AcpSessionRuntime, make(options)); |
| 2990 | |
| 2991 | function sessionConfigOptionsFromSetup( |
| 2992 | response: |
| 2993 | | { |
| 2994 | readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null; |
| 2995 | } |
| 2996 | | undefined, |
| 2997 | ): ReadonlyArray<EffectAcpSchema.SessionConfigOption> { |
| 2998 | return response?.configOptions ?? []; |
| 2999 | } |
| 3000 | |
| 3001 | function configOptionCurrentValueMatches( |
| 3002 | configOption: EffectAcpSchema.SessionConfigOption, |
| 3003 | value: string | boolean, |
| 3004 | ): boolean { |
| 3005 | const currentValue = configOption.currentValue; |
| 3006 | if (configOption.type === "boolean") { |
| 3007 | return currentValue === value; |
| 3008 | } |
| 3009 | if (typeof currentValue !== "string") { |
| 3010 | return false; |
| 3011 | } |
| 3012 | return currentValue.trim() === String(value).trim(); |
| 3013 | } |
| 3014 | |
| 3015 | function isStartupMetadataUpdate(notification: EffectAcpSchema.SessionNotification): boolean { |
| 3016 | switch (notification.update.sessionUpdate) { |
| 3017 | case "current_mode_update": |
| 3018 | case "config_option_update": |
| 3019 | case "available_commands_update": |
| 3020 | return true; |
| 3021 | default: |
| 3022 | return false; |
| 3023 | } |
| 3024 | } |
| 3025 | |
| 3026 | const handleSessionUpdate = |
| 3027 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3028 | Effect.fnUntraced(function* ({ |
| 3029 | queue, |
| 3030 | modeStateRef, |
| 3031 | configOptionsRef, |
| 3032 | toolCallsRef, |
| 3033 | shownToolCallIds, |
| 3034 | assistantSegmentRef, |
| 3035 | assistantItemRuntimeId, |
| 3036 | params, |
| 3037 | }: { |
| 3038 | readonly queue: Queue.Queue<AcpSessionRuntimeEvent>; |
| 3039 | readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>; |
| 3040 | readonly configOptionsRef: SubscriptionRef.SubscriptionRef< |
| 3041 | ReadonlyArray<EffectAcpSchema.SessionConfigOption> |
| 3042 | >; |
| 3043 | readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallTrackedState>>; |
| 3044 | readonly shownToolCallIds: Set<string>; |
| 3045 | readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>; |
| 3046 | readonly assistantItemRuntimeId: string; |
| 3047 | readonly params: EffectAcpSchema.SessionNotification; |
| 3048 | }): Effect.fn.Return<void> { |
| 3049 | if (params.update.sessionUpdate === "config_option_update") { |
| 3050 | const configOptions = params.update.configOptions; |
| 3051 | yield* SubscriptionRef.set(configOptionsRef, configOptions); |
| 3052 | yield* Ref.update( |
| 3053 | modeStateRef, |
| 3054 | (current) => parseSessionModeState({ configOptions }) ?? current, |
| 3055 | ); |
| 3056 | } |
| 3057 | const parsed = parseSessionUpdateEvent(params); |
| 3058 | if (parsed.modeId) { |
| 3059 | yield* Ref.update(modeStateRef, (current) => |
| 3060 | current === undefined ? current : updateModeState(current, parsed.modeId!), |
| 3061 | ); |
| 3062 | } |
| 3063 | for (const event of parsed.events) { |
| 3064 | if (event._tag === "ToolCallUpdated") { |
| 3065 | const { merged, decision, active } = yield* Ref.modify(toolCallsRef, (current) => { |
| 3066 | const tracked = current.get(event.toolCall.toolCallId); |
| 3067 | const previous = tracked?.state; |
| 3068 | const nextToolCall = mergeToolCallState(previous, event.toolCall); |
| 3069 | const decision = decideToolCallUpdateEmission({ |
| 3070 | previous, |
| 3071 | next: nextToolCall, |
| 3072 | lastEmittedDetailLength: tracked?.lastEmittedDetailLength, |
| 3073 | skippedSinceEmit: tracked?.skippedSinceEmit ?? 0, |
| 3074 | }); |
| 3075 | const next = new Map(current); |
| 3076 | if (nextToolCall.status === "completed" || nextToolCall.status === "failed") { |
| 3077 | next.delete(nextToolCall.toolCallId); |
| 3078 | } else { |
| 3079 | next.set(nextToolCall.toolCallId, { |
| 3080 | state: nextToolCall, |
| 3081 | lastEmittedDetailLength: decision.emit |
| 3082 | ? toolCallProgressLength(nextToolCall) |
| 3083 | : tracked?.lastEmittedDetailLength, |
| 3084 | skippedSinceEmit: decision.skippedSinceEmit, |
| 3085 | }); |
| 3086 | } |
| 3087 | return [{ merged: nextToolCall, decision, active: tracked !== undefined }, next] as const; |
| 3088 | }); |
| 3089 | if (!decision.emit) { |
| 3090 | continue; |
| 3091 | } |
| 3092 | if (!shownToolCallIds.has(merged.toolCallId)) { |
| 3093 | shownToolCallIds.add(merged.toolCallId); |
| 3094 | if (shownToolCallIds.size > MAX_SHOWN_TOOL_CALL_IDS) { |
| 3095 | shownToolCallIds.delete(shownToolCallIds.values().next().value!); |
| 3096 | } |
| 3097 | if (!active) yield* closeActiveAssistantSegment({ queue, assistantSegmentRef }); |
| 3098 | } |
| 3099 | yield* Queue.offer(queue, { |
| 3100 | _tag: "ToolCallUpdated", |
| 3101 | toolCall: merged, |
| 3102 | rawPayload: event.rawPayload, |
| 3103 | }); |
| 3104 | continue; |
| 3105 | } |
| 3106 | if (event._tag === "ContentDelta") { |
| 3107 | if (event.text.trim().length === 0) { |
| 3108 | const assistantSegmentState = yield* Ref.get(assistantSegmentRef); |
| 3109 | if (!assistantSegmentState.activeItemId) { |
| 3110 | continue; |
| 3111 | } |
| 3112 | } |
| 3113 | const itemId = yield* ensureActiveAssistantSegment({ |
| 3114 | queue, |
| 3115 | assistantSegmentRef, |
| 3116 | sessionId: params.sessionId, |
| 3117 | assistantItemRuntimeId, |
| 3118 | }); |
| 3119 | yield* Queue.offer(queue, { |
| 3120 | ...event, |
| 3121 | itemId, |
| 3122 | }); |
| 3123 | continue; |
| 3124 | } |
| 3125 | yield* Queue.offer(queue, event); |
| 3126 | } |
| 3127 | }); |
| 3128 | |
| 3129 | function updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState { |
| 3130 | const normalized = nextModeId.trim(); |
| 3131 | if (!normalized) { |
| 3132 | return modeState; |
| 3133 | } |
| 3134 | return modeState.availableModes.some((mode) => mode.id === normalized) |
| 3135 | ? { |
| 3136 | ...modeState, |
| 3137 | currentModeId: normalized, |
| 3138 | } |
| 3139 | : modeState; |
| 3140 | } |
| 3141 | |
| 3142 | const assistantItemId = (sessionId: string, runtimeId: string, segmentIndex: number) => |
| 3143 | `assistant:${sessionId}:runtime:${runtimeId}:segment:${segmentIndex}`; |
| 3144 | |
| 3145 | const ensureActiveAssistantSegment = ({ |
| 3146 | queue, |
| 3147 | assistantSegmentRef, |
| 3148 | sessionId, |
| 3149 | assistantItemRuntimeId, |
| 3150 | }: { |
| 3151 | readonly queue: Queue.Queue<AcpSessionRuntimeEvent>; |
| 3152 | readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>; |
| 3153 | readonly sessionId: string; |
| 3154 | readonly assistantItemRuntimeId: string; |
| 3155 | }) => |
| 3156 | Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>( |
| 3157 | assistantSegmentRef, |
| 3158 | (current) => { |
| 3159 | if (current.activeItemId) { |
| 3160 | return [{ itemId: current.activeItemId }, current] as const; |
| 3161 | } |
| 3162 | const itemId = assistantItemId(sessionId, assistantItemRuntimeId, current.nextSegmentIndex); |
| 3163 | return [ |
| 3164 | { |
| 3165 | itemId, |
| 3166 | startedEvent: { |
| 3167 | _tag: "AssistantItemStarted", |
| 3168 | itemId, |
| 3169 | } satisfies Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>, |
| 3170 | }, |
| 3171 | { |
| 3172 | nextSegmentIndex: current.nextSegmentIndex + 1, |
| 3173 | activeItemId: itemId, |
| 3174 | } satisfies AcpAssistantSegmentState, |
| 3175 | ] as const; |
| 3176 | }, |
| 3177 | ).pipe( |
| 3178 | Effect.flatMap((result) => |
| 3179 | result.startedEvent |
| 3180 | ? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId)) |
| 3181 | : Effect.succeed(result.itemId), |
| 3182 | ), |
| 3183 | ); |
| 3184 | |
| 3185 | const closeActiveAssistantSegment = ({ |
| 3186 | queue, |
| 3187 | assistantSegmentRef, |
| 3188 | }: { |
| 3189 | readonly queue: Queue.Queue<AcpSessionRuntimeEvent>; |
| 3190 | readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>; |
| 3191 | }) => |
| 3192 | Ref.modify(assistantSegmentRef, (current) => { |
| 3193 | if (!current.activeItemId) { |
| 3194 | return [undefined, current] as const; |
| 3195 | } |
| 3196 | return [ |
| 3197 | { |
| 3198 | _tag: "AssistantItemCompleted", |
| 3199 | itemId: current.activeItemId, |
| 3200 | } satisfies AcpParsedSessionEvent, |
| 3201 | { |
| 3202 | nextSegmentIndex: current.nextSegmentIndex, |
| 3203 | } satisfies AcpAssistantSegmentState, |
| 3204 | ] as const; |
| 3205 | }).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void))); |