diff --git a/apps/server/package.json b/apps/server/package.json index bea918f40787..2824a27b3499 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -67,6 +67,7 @@ "diff": "8.0.3", "effect": "catalog:", "ffi-rs": "1.3.2", + "koffi": "3.3.6", "node-pty": "^1.2.0-beta.15", "playwright-core": "1.64.1", "proper-lockfile": "4.1.2", diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index 439a2d19b9e7..0a413dd09114 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -14,9 +14,12 @@ import * as AcpError from "effect-acp/errors"; import * as AcpSchema from "effect-acp/schema"; import type * as AcpCompat from "effect-acp/compat"; +import { startDetachedCommand } from "./acpMockDetachedCommand.ts"; + import { beginAcpMockPrompt } from "./acpMockCancellationState.ts"; const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH; +const detachedReceipt = process.env.T3_ACP_DETACHED_COMMAND_RECEIPT; const antigravityProfile = process.env.T3_ACP_ANTIGRAVITY === "1"; // GitHub Copilot CLI advertises URL-shaped session mode ids. const copilotModesProfile = process.env.T3_ACP_COPILOT_MODES === "1"; @@ -888,6 +891,21 @@ const program = Effect.gen(function* () { } beginAcpMockPrompt(cancelledSessions, requestedSessionId); promptCount += 1; + if (detachedReceipt !== undefined) { + yield* Effect.promise(() => startDetachedCommand(detachedReceipt)); + yield* agent.client.sessionUpdate({ + sessionId: requestedSessionId, + update: { + sessionUpdate: "tool_call_update", + toolCallId: "watcher", + title: "Running run_command", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "sleep 53" }, + }, + }); + return yield* finishPrompt(requestedSessionId, "end_turn"); + } if (idleError === "grok-background" && promptCount === 1) { // The structured completion lands before the prompt settles, so it is buffered. const taskId = "call-idle-error-background"; diff --git a/apps/server/scripts/acpMockDetachedCommand.ts b/apps/server/scripts/acpMockDetachedCommand.ts new file mode 100644 index 000000000000..b6bf9bc24068 --- /dev/null +++ b/apps/server/scripts/acpMockDetachedCommand.ts @@ -0,0 +1,74 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the fixture captures real Linux process identities. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeReadline from "node:readline"; +import * as NodeURL from "node:url"; + +const identity = (pid: number | undefined) => { + if (pid === undefined) throw new Error("Command did not spawn"); + const stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8"); + const fields = stat + .slice(stat.lastIndexOf(")") + 2) + .trim() + .split(/\s+/); + return { + pid, + ppid: Number(fields[1]), + pgid: Number(fields[2]), + sid: Number(fields[3]), + startTime: fields[19], + }; +}; + +const writeReceipt = ( + pidFile: string, + receipt: { processes: Array> }, +) => { + NodeFS.writeFileSync(`${pidFile}.tmp`, JSON.stringify(receipt)); + NodeFS.renameSync(`${pidFile}.tmp`, pidFile); +}; + +if (process.argv[2] === "command") { + const pidFile = process.argv[3]; + if (pidFile === undefined) throw new Error("Missing process receipt path"); + const sleep = NodeChildProcess.spawn("/bin/sleep", ["53"], { stdio: "ignore" }); + await new Promise((resolve, reject) => { + sleep.once("spawn", resolve); + sleep.once("error", reject); + }); + const receipt = { + processes: [identity(process.ppid), identity(process.pid), identity(sleep.pid)], + }; + writeReceipt(pidFile, receipt); + process.stdout.on("error", (error: NodeJS.ErrnoException) => { + if (error.code !== "EPIPE") throw error; + }); + process.stdout.write(JSON.stringify(receipt) + "\n"); + await new Promise((resolve) => sleep.once("exit", () => resolve())); + process.exit(0); +} + +// Readiness follows the command's atomic receipt, independently of the ACP reader. +export async function startDetachedCommand(pidFile: string) { + const shell = NodeChildProcess.spawn( + "/bin/sh", + [ + "-c", + 'read -r start || exit 0; "$1" "$2" command "$3" & wait', + "fixture", + process.execPath, + NodeURL.fileURLToPath(import.meta.url), + pidFile, + ], + { detached: true, stdio: ["pipe", "pipe", "ignore"] }, + ); + writeReceipt(pidFile, { processes: [identity(shell.pid)] }); + shell.stdin.end("start\n"); + const lines = NodeReadline.createInterface({ input: shell.stdout }); + try { + const ready = await lines[Symbol.asyncIterator]().next(); + if (ready.done) throw new Error("Command exited before acknowledging child readiness"); + } finally { + lines.close(); + } +} diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5e3a971dba1c..5fe69521610c 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -12,6 +12,7 @@ import { RunId, ThreadId, } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -24,6 +25,7 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import { ChildProcessSpawner } from "effect/process"; @@ -34,7 +36,11 @@ import * as EffectAcpErrors from "effect-acp/errors"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; -import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import { + makeAcpAdapterV2, + type AcpAdapterV2RuntimeInput, +} from "@t3tools/provider-acp/server/adapter"; import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts"; import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts"; import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts"; @@ -897,216 +903,621 @@ describe("AntigravityAdapterV2 html_render pages", () => { describe("AntigravityAdapterV2 work after the prompt ends", () => { // Frames as agy 1.5.11 sent them for `run_command` with `WaitMsBeforeAsync`: the prompt returns // end_turn, the command finishes later, and the agent replies with no prompt open. - it.effect("continues in one run when a finished background command wakes the agent", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const crypto = yield* SecureRandom.SecureRandom; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdate: Parameters[0] | undefined; - let requestPermission: Parameters[0] | undefined; - const send = (update: EffectAcpSchema.SessionUpdate) => - sessionUpdate === undefined - ? Effect.die("the adapter must handle session updates") - : sessionUpdate( - normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }), - ); - const command = { - toolCallId: "call_fetch", - kind: "execute", - title: "node fetch_throughput.mjs", - rawInput: { CommandLine: "node fetch_throughput.mjs", WaitMsBeforeAsync: 10000 }, - } as const; - const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const; - const offers: Array = []; - const instanceId = ProviderInstanceId.make("antigravity-wake-test"); - const threadId = ThreadId.make("thread-antigravity-wake"); - const adapter = yield* makeAntigravityAdapterV2({ - instanceId, - selfInvocation: yield* resolveSelfInvocation(), - continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) }, - makeRuntime: (input) => - makeAntigravityAcpRuntime({ - ...input, - childProcessSpawner, - spawn: { - command: process.execPath, - args: [mockAgentPath], - cwd: input.cwd, - env: { T3_ACP_ANTIGRAVITY: "1" }, - }, - }).pipe( - Effect.provideService(SecureRandom.SecureRandom, crypto), - Effect.map((runtime): RuntimeService => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdate = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - handleRequestPermission: (handler) => - Effect.sync(() => { - requestPermission = handler; - }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))), - prompt: () => - Effect.gen(function* () { - yield* send({ sessionUpdate: "tool_call", ...command, status: "in_progress" }); - yield* send({ - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "I'll render once the fetch finishes." }, - }); - yield* send(usage); - return { stopReason: "end_turn" as const }; - }), - })), - ), - withProcess: (_stop, task) => task, - defaultModel: Effect.undefined, - }); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "gemini-test-low" } as const; - const session = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-antigravity-wake"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* session.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const throughTerminal = Effect.gen(function* () { - const seen: Array = []; - while (true) { - const event = yield* Queue.take(events); - seen.push(event); - if (event.type === "turn.terminal") return seen; - } - }); - const providerThread = yield* session.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - const startTurn = (ordinal: number, continuation: boolean) => - session.startTurn({ - appThread: { - createdBy: "user", - creationSource: "web", - id: threadId, - projectId: ProjectId.make("project-antigravity-wake"), - title: "Antigravity wake", - providerInstanceId: instanceId, - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: process.cwd(), - activeProviderThreadId: providerThread.id, - lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, - forkedFrom: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - lastVisitedAt: null, - deletedAt: null, + it.effect.each([true, false])( + "keeps the reply together when a command outlives its prompt (%s)", + (commandOutlivesPrompt) => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + let requestPermission: Parameters[0] | undefined; + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }), + ); + const command = { + toolCallId: "call_fetch", + kind: "execute", + title: "node fetch_throughput.mjs", + rawInput: { CommandLine: "node fetch_throughput.mjs", WaitMsBeforeAsync: 10000 }, + } as const; + const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const; + const offers: Array = []; + const instanceId = ProviderInstanceId.make("antigravity-wake-test"); + const threadId = ThreadId.make("thread-antigravity-wake"); + const promptSettled = yield* Deferred.make(); + const selfInvocation = yield* resolveSelfInvocation(); + const adapterFlavor = makeAntigravityAcpAdapterFlavor({ + random: crypto, + fileSystem: yield* FileSystem.FileSystem, + path, + host: yield* ProviderHost.ProviderHost, + instanceId, + selfInvocation, + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + handleRequestPermission: (handler) => + Effect.sync(() => { + requestPermission = handler; + }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))), + prompt: () => + Effect.gen(function* () { + if (commandOutlivesPrompt) { + yield* send({ + sessionUpdate: "tool_call", + ...command, + status: "in_progress", + }); + } + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "I'll render once the fetch finishes." }, + }); + yield* send(usage); + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: adapterFlavor, + continuationRequests: { + offer: (request) => Effect.sync(() => void offers.push(request)), }, - threadId, - runId: RunId.make(`run-antigravity-wake-${ordinal}`), - runOrdinal: ordinal, - providerTurnOrdinal: ordinal, - attemptId: RunAttemptId.make(`attempt-antigravity-wake-${ordinal}`), - rootNodeId: NodeId.make(`node-antigravity-wake-${ordinal}`), - providerThread, - message: { - ...(continuation - ? { createdBy: "agent" as const, creationSource: "provider" as const } - : { createdBy: "user" as const, creationSource: "web" as const }), - messageId: MessageId.make(`message-antigravity-wake-${ordinal}`), - text: "chart the throughput", - attachments: [], + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-wake"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* session.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const throughTerminal = Effect.gen(function* () { + const seen: Array = []; + while (true) { + const event = yield* Queue.take(events); + seen.push(event); + if (event.type === "turn.terminal") return seen; + } + }); + const providerThread = yield* session.ensureThread({ + threadId, modelSelection, runtimePolicy, }); + const now = yield* DateTime.now; + const startTurn = (ordinal: number, continuation: boolean) => + session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-wake"), + title: "Antigravity wake", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make(`run-antigravity-wake-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt-antigravity-wake-${ordinal}`), + rootNodeId: NodeId.make(`node-antigravity-wake-${ordinal}`), + providerThread, + message: { + ...(continuation + ? { createdBy: "agent" as const, creationSource: "provider" as const } + : { createdBy: "user" as const, creationSource: "web" as const }), + messageId: MessageId.make(`message-antigravity-wake-${ordinal}`), + text: "chart the throughput", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); - yield* startTurn(1, false); - const promptTerminal = (yield* throughTerminal).at(-1); - assert.equal(promptTerminal?.type === "turn.terminal" && promptTerminal.status, "completed"); + yield* startTurn(1, false); + if (commandOutlivesPrompt) { + yield* Deferred.await(promptSettled); + const snapshot = yield* session.readThreadSnapshot({ providerThread }); + assert.equal(snapshot.providerTurns.at(-1)?.status, "running"); + } else { + const promptTerminal = (yield* throughTerminal).at(-1); + assert.equal( + promptTerminal?.type === "turn.terminal" && promptTerminal.status, + "completed", + ); + yield* send({ sessionUpdate: "tool_call", ...command, status: "in_progress" }); + } - yield* send({ - sessionUpdate: "tool_call_update", - ...command, - status: "completed", - rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, - }); - assert.lengthOf(offers, 1, "the finished command must wake the thread"); - // The agent can ask before the app has started the continuation run. - const followUp = { toolCallId: "call_analyze", kind: "execute", title: "node analyze.mjs" }; - const permission = yield* Effect.suspend(() => - requestPermission === undefined - ? Effect.die("the adapter must handle permission requests") - : requestPermission( - { - sessionId: "mock-session-1", - toolCall: { ...followUp, status: "pending" }, - options: [ - { optionId: "allow", name: "Allow", kind: "allow_once" }, - { optionId: "deny", name: "Deny", kind: "reject_once" }, - ], - }, - { requestId: "permission-1", method: "session/request_permission" }, - ), - ).pipe(Effect.forkScoped({ startImmediately: true })); - yield* offers[0]!.dispatchIfCurrent!(Effect.void); - yield* startTurn(2, true); - assert.deepEqual(yield* Fiber.join(permission), { - outcome: { outcome: "selected", optionId: "allow" }, - }); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + assert.lengthOf(offers, commandOutlivesPrompt ? 0 : 1); + // The agent can ask before the app has started the continuation run. + const followUp = { toolCallId: "call_analyze", kind: "execute", title: "node analyze.mjs" }; + const permission = yield* Effect.suspend(() => + requestPermission === undefined + ? Effect.die("the adapter must handle permission requests") + : requestPermission( + { + sessionId: "mock-session-1", + toolCall: { ...followUp, status: "pending" }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }, + { requestId: "permission-1", method: "session/request_permission" }, + ), + ).pipe(Effect.forkScoped({ startImmediately: true })); + if (!commandOutlivesPrompt) { + yield* offers[0]!.dispatchIfCurrent!(Effect.void); + yield* startTurn(2, true); + } + assert.deepEqual(yield* Fiber.join(permission), { + outcome: { outcome: "selected", optionId: "allow" }, + }); - // The model took 6.7 s to answer the finished command; the run must outlast that silence. - yield* TestClock.adjust("10 seconds"); - yield* send({ sessionUpdate: "tool_call", ...followUp, status: "completed" }); - yield* send({ - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Here is the chart." }, - }); - yield* TestClock.adjust("10 seconds"); - yield* send(usage); - yield* TestClock.adjust("3 seconds"); - const continued = yield* throughTerminal; - const continuedTerminal = continued.at(-1); - assert.equal( - continuedTerminal?.type === "turn.terminal" && continuedTerminal.status, - "completed", - ); - assert.isTrue( - continued.some( + // The model took 6.7 s to answer the finished command; the run must outlast that silence. + yield* TestClock.adjust("10 seconds"); + yield* send({ sessionUpdate: "tool_call", ...followUp, status: "completed" }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Here is the chart." }, + }); + yield* TestClock.adjust("10 seconds"); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const continued = yield* throughTerminal; + const continuedTerminal = continued.at(-1); + assert.equal( + continuedTerminal?.type === "turn.terminal" && continuedTerminal.status, + "completed", + ); + assert.isTrue( + continued.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.runId === + RunId.make(`run-antigravity-wake-${commandOutlivesPrompt ? 1 : 2}`), + ), + "the reply belongs to the active run", + ); + const finished = continued.findLast( (event) => event.type === "turn_item.updated" && - event.turnItem.type === "assistant_message" && - event.turnItem.runId === RunId.make("run-antigravity-wake-2"), + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.equal( + finished?.type === "turn_item.updated" && finished.turnItem.status, + "completed", + ); + assert.lengthOf(offers, commandOutlivesPrompt ? 0 : 1, "one reply stays in one run"); + }).pipe(Effect.provide(layerSession)), + ); +}); + +/** The agent reports one tool, answers end_turn, and the user optionally presses Stop after. */ +const endTurnAfterTool = ( + tool: Extract, + options: { + readonly stopAfterReply: boolean; + readonly detachedCommand?: boolean; + readonly terminateAfterReply?: "wire-settled" | "deferred"; + readonly negotiatedDeferral?: boolean; + }, +) => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const fs = yield* FileSystem.FileSystem; + const scratch = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-stop-" }); + const receiptPath = path.join(scratch, "processes.json"); + const controller = options.detachedCommand + ? AcpSessionRuntime.makePosixProcessTreeController("linux") + : undefined; + const decodeReceipt = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Struct({ + processes: Schema.NonEmptyArray( + Schema.Struct({ + pid: Schema.Int, + ppid: Schema.Int, + pgid: Schema.Int, + sid: Schema.Int, + startTime: Schema.String, + }), + ), + }), + ), + ); + const readReceipt = () => + fs.readFileString(receiptPath).pipe( + Effect.flatMap(decodeReceipt), + Effect.map((receipt) => receipt.processes), + ); + const executing = (owned: { readonly pid: number; readonly startTime: string }) => { + const current = controller?.identity(owned.pid); + return ( + current?.startTime === owned.startTime && current.state !== "Z" && current.state !== "X" + ); + }; + // Cleanup uses captured identities even if Stop loses the parent chain or setup fails. + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + if (controller === undefined || !(yield* fs.exists(receiptPath))) return; + const processes = yield* readReceipt(); + const owned = processes.map((entry) => ({ + ...entry, + executable: undefined, + parentExecutable: undefined, + parentStartTime: processes.find((parent) => parent.pid === entry.ppid)?.startTime ?? "", + })); + let signals = 0; + yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({ + controller: { + ...controller, + signalProcess: (pid, signal) => { + signals += 1; + controller.signalProcess(pid, signal); + }, + }, + rootPid: processes[0].pid, + root: { value: owned[0], captureAttempted: true }, + ledger: new Map(owned.map((entry) => [`${entry.pid}:${entry.startTime}`, entry])), + grace: 0, + }); + assert.isFalse(processes.some(executing), "Fixture cleanup retained a captured process"); + yield* Effect.logInfo("DETACHED_CLEANUP", { signals, survivors: [] }); + }).pipe(Effect.orDie), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + const promptSettled = yield* Deferred.make(); + const promptCallback = yield* Deferred.make(); + const runtimeInputs: AcpAdapterV2RuntimeInput[] = []; + const instanceId = ProviderInstanceId.make("antigravity-running-command-test"); + const threadId = ThreadId.make("thread-antigravity-running-command"); + const selfInvocation = yield* resolveSelfInvocation(); + const adapterFlavor = makeAntigravityAcpAdapterFlavor({ + random: crypto, + fileSystem: fs, + path, + host: yield* ProviderHost.ProviderHost, + instanceId, + selfInvocation, + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + // Keep the regression on the /proc path even on hosts with cgroup delegation. + ...(options.detachedCommand ? { linuxCgroupController: null } : {}), + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { + T3_ACP_ANTIGRAVITY: "1", + ...(options.detachedCommand ? { T3_ACP_DETACHED_COMMAND_RECEIPT: receiptPath } : {}), + }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: (payload, promptOptions) => + options.detachedCommand + ? runtime.prompt(payload, promptOptions) + : Effect.gen(function* () { + if (sessionUpdate === undefined) { + return yield* Effect.die("the adapter must handle session updates"); + } + yield* sessionUpdate( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update: tool, + }), + ); + return { stopReason: "end_turn" as const }; + }), + })), ), - "the reply belongs to the continuation run", + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + ...adapterFlavor, + ...(options.negotiatedDeferral ? { deferFinalizeForBackgroundWork: () => true } : {}), + makeRuntime: (input) => { + runtimeInputs.push(input); + return adapterFlavor.makeRuntime(input); + }, + }, + testHooks: { + afterPromptWireSettled: () => + options.terminateAfterReply === "wire-settled" + ? runtimeInputs[0]!.onTermination( + new EffectAcpErrors.AcpTransportError({ + detail: "Injected runtime death", + cause: "test", + }), + ) + : Effect.void, + afterPromptCallback: () => Deferred.succeed(promptCallback, undefined).pipe(Effect.asVoid), + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-running-command"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* session.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-running-command"), + title: "Antigravity running command", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make("run-antigravity-running-command"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-antigravity-running-command"), + rootNodeId: NodeId.make("node-antigravity-running-command"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-antigravity-running-command"), + text: "watch the log", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + + let providerTurnId: ProviderAdapter.ProviderAdapterV2InterruptInput["providerTurnId"] | null = + null; + let itemStatus: string | null = null; + while (providerTurnId === null || itemStatus === null) { + const event = yield* Queue.take(events); + if (event.type === "provider_turn.updated") providerTurnId = event.providerTurn.id; + if ( + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === tool.toolCallId + ) { + itemStatus = event.turnItem.status; + } + } + if (options.terminateAfterReply === "wire-settled") { + yield* Deferred.await(promptCallback); + } else if (options.stopAfterReply || options.terminateAfterReply) { + yield* Deferred.await(promptSettled); + } + const processes = options.detachedCommand ? yield* readReceipt() : []; + if (options.detachedCommand) { + assert.equal(processes.length, 3); + const [shell, command, sleep] = processes; + assert.equal(command!.ppid, shell!.pid); + assert.equal(sleep!.ppid, command!.pid); + assert.equal(shell!.pgid, shell!.pid); + assert.isTrue(processes.every(executing), "Readiness must include executing children"); + yield* Effect.logInfo("DETACHED_BEFORE_STOP", { processes }); + } + if (options.stopAfterReply) { + yield* session.interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }); + } + if (options.terminateAfterReply) { + if (options.terminateAfterReply === "deferred") { + yield* runtimeInputs[0]!.onTermination( + new EffectAcpErrors.AcpTransportError({ + detail: "Injected runtime death", + cause: "test", + }), + ); + } + const snapshot = yield* session.readThreadSnapshot({ providerThread }); + assert.equal( + snapshot.providerTurns.find((turn) => turn.id === providerTurnId)?.status, + "failed", ); - const finished = continued.findLast( - (event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + assert.lengthOf(runtimeInputs, 2, "runtime death must require a replacement runtime"); + yield* runtimeInputs[0]!.onTermination( + new EffectAcpErrors.AcpTransportError({ detail: "Stale runtime death", cause: "test" }), ); - assert.equal(finished?.type === "turn_item.updated" && finished.turnItem.status, "completed"); - assert.lengthOf(offers, 1, "one wake is one run"); - }).pipe(Effect.provide(layerSession)), + yield* session.readThreadSnapshot({ providerThread }); + assert.lengthOf(runtimeInputs, 2, "a stale death must not poison the replacement runtime"); + } + + let terminalStatus: string | null = null; + while (terminalStatus === null) { + const event = yield* Queue.take(events); + if ( + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === tool.toolCallId + ) { + itemStatus = event.turnItem.status; + } + if (event.type === "turn.terminal") { + terminalStatus = event.status; + if (options.terminateAfterReply) assert.equal(event.failure?.class, "transport_error"); + } + } + if (options.detachedCommand) { + const survivors = processes.filter(executing); + yield* Effect.logInfo("DETACHED_AFTER_STOP", { survivors, itemStatus, terminalStatus }); + assert.deepEqual(survivors, [], "Stop left a captured command process alive"); + assert.equal(terminalStatus, "interrupted"); + } + return { itemStatus, terminalStatus }; + }).pipe(Effect.provide(layerSession), Effect.scoped); + +describe("AntigravityAdapterV2 running commands", () => { + it.live("does not mark a command completed while it is still running at end_turn", () => + Effect.gen(function* () { + const result = yield* endTurnAfterTool( + { + sessionUpdate: "tool_call", + toolCallId: "watcher", + title: "Running run_command", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "tail -f app.log" }, + }, + { stopAfterReply: true, detachedCommand: (yield* HostProcess.Platform) === "linux" }, + ); + assert.equal(result.itemStatus, "interrupted"); + assert.equal(result.terminalStatus, "interrupted"); + }), + ); + + it.live.each([ + ["wire-settled", false], + ["deferred", false], + ["wire-settled", true], + ] as const)( + "fails a command and turn when its runtime dies after %s (negotiated: %s)", + ([terminateAfterReply, negotiatedDeferral]) => + Effect.gen(function* () { + const result = yield* endTurnAfterTool( + { + sessionUpdate: "tool_call", + toolCallId: "watcher", + title: "Running run_command", + kind: "execute", + status: "in_progress", + rawInput: { CommandLine: "tail -f app.log" }, + }, + { stopAfterReply: false, terminateAfterReply, negotiatedDeferral }, + ); + assert.equal(result.itemStatus, "failed"); + assert.equal(result.terminalStatus, "failed"); + }), + ); + + it.effect("completes the turn at end_turn while a launched subagent batch runs", () => + Effect.gen(function* () { + const result = yield* endTurnAfterTool( + { + sessionUpdate: "tool_call", + toolCallId: "batch", + title: "Running start_subagent", + kind: "other", + status: "completed", + rawOutput: "Started two agents.", + }, + { stopAfterReply: false }, + ); + assert.equal(result.terminalStatus, "completed"); + }), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index b91f1a452679..cb7423542d94 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -242,10 +242,15 @@ export function makeAntigravityAcpAdapterFlavor( ), // Loading history replays tool calls; resume avoids replay. subagentsIdleOnTurnCompletion: true, + // A command can outlive end_turn; session/cancel leaves it running, so Stop ends the process group. + extractBackgroundTaskId: (toolCall) => + toolCall.kind === "execute" ? toolCall.toolCallId : undefined, + deferFinalizeForBackgroundWork: true, + restartRuntimeAfterInterrupt: true, + terminateRuntimeProcessGroupOnInterrupt: true, // A finished background command or timer wakes the agent with no prompt open: it streams a // reply and asks for permissions, and no prompt response ever ends that reply. enablePostSettleContinuation: true, - deferFinalizeForBackgroundWork: true, wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true, ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }), diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts b/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts index 6b9afa7f30c5..bb3dd4d864cf 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts @@ -3,6 +3,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodeModule from "node:module"; import * as NodePath from "node:path"; +import * as NodeEvents from "node:events"; import { describe, expect, it, vi } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -814,6 +815,81 @@ describe("terminatePosixOwnedProcessTree", () => { }), ); + it.live.runIf(HostProcess.Platform.defaultValue() === "darwin")( + "terminates Darwin descendants in separate sessions before independent cleanup", + () => + Effect.gen(function* () { + const controller = AcpSessionRuntime.makePosixProcessTreeController("darwin"); + const captured = new Map(); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + for (const old of [...captured.values()].reverse()) { + const current = controller.identity(old.pid); + if (current?.startTime === old.startTime && current.state !== "Z") { + try { + process.kill(old.pid, "SIGKILL"); + } catch (error) { + if (!(error instanceof Error && "code" in error && error.code === "ESRCH")) { + throw error; + } + } + } + } + }), + ); + const root = NodeChildProcess.spawn( + process.execPath, + [ + "-e", + `const {spawn}=require("node:child_process"); + const child=spawn("/bin/sleep",["60"],{detached:true,stdio:"ignore"}); + child.on("spawn",()=>console.log(child.pid)); + process.stdin.on("end",()=>{ + if(child.exitCode!==null||child.signalCode!==null)process.exit(0); + child.once("exit",()=>process.exit(0)); + child.kill("SIGKILL"); + }); + process.stdin.resume();`, + ], + { detached: true, stdio: ["pipe", "pipe", "pipe"] }, + ); + const rootExit = NodeEvents.EventEmitter.once(root, "exit"); + yield* Effect.addFinalizer(() => + Effect.promise(async () => { + root.stdin.end(); + await rootExit; + }), + ); + const rootIdentity = controller.identity(root.pid!); + expect(rootIdentity).toBeDefined(); + captured.set(root.pid!, rootIdentity!); + const [chunk] = yield* Effect.promise(() => + NodeEvents.EventEmitter.once(root.stdout, "data"), + ); + const childPid = Number(String(chunk).trim()); + const child = controller.identity(childPid); + expect(child).toBeDefined(); + captured.set(childPid, child!); + expect(child!.ppid).toBe(root.pid); + expect(child!.pgid).toBe(childPid); + expect(child!.sid).toBe(childPid); + expect(controller.childPidsOf(root.pid!)).toContain(childPid); + expect(controller.snapshot()).toEqual(expect.arrayContaining([rootIdentity, child])); + yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({ + controller, + grace: 0, + rootPid: root.pid!, + }); + for (const old of captured.values()) { + const current = controller.identity(old.pid); + expect(current?.startTime !== old.startTime || current.state === "Z").toBe(true); + } + const [code, signal] = yield* Effect.promise(() => rootExit); + expect(code).toBeNull(); + expect(signal).toBe("SIGTERM"); + }).pipe(Effect.scoped), + ); + it.skipIf(HostProcess.Platform.defaultValue() !== "linux")( "snapshots /proc when a process exits while its entry is being typed", () => { @@ -843,11 +919,11 @@ describe("terminatePosixOwnedProcessTree", () => { it("fails closed where a stable POSIX identity provider is unavailable", () => { try { - AcpSessionRuntime.makePosixProcessTreeController("darwin"); - throw new Error("Expected Darwin process ownership to fail closed"); + AcpSessionRuntime.makePosixProcessTreeController("freebsd"); + throw new Error("Expected FreeBSD process ownership to fail closed"); } catch (error) { expect(error).toMatchObject({ - detail: "Detached ACP descendant ownership is unsupported on darwin", + detail: "Detached ACP descendant ownership is unsupported on freebsd", }); } }); diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 7fd64e2534fa..8e38233f896d 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -135,9 +135,15 @@ export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")( EffectAcpErrors.AcpError, SecureRandom.SecureRandom | Scope.Scope > { + const processGroupPlatform = yield* HostProcess.Platform; const context = yield* Layer.build( AcpSessionRuntime.layer({ ...input, + // Stop tears down the agent's process group to end commands session/cancel leaves running. + ownDetachedProcessGroup: true, + ownDescendantProcessGroups: + processGroupPlatform === "linux" || processGroupPlatform === "darwin", + processGroupPlatform, authMethodId: input.authMethod ?? "oauth-personal", authenticateEagerly: true, resumeMethod: "resume", diff --git a/knip.jsonc b/knip.jsonc index 748d6864e221..4dada04f1ac4 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -73,6 +73,7 @@ "@t3tools/web", "@napi-rs/keyring", "ffi-rs", + "koffi", "transcribe-cpp", ], }, diff --git a/packages/provider-acp/package.json b/packages/provider-acp/package.json index 83f556e4c44e..0e75ee8bebdf 100644 --- a/packages/provider-acp/package.json +++ b/packages/provider-acp/package.json @@ -49,7 +49,8 @@ "@t3tools/provider-core": "workspace:*", "@t3tools/shared": "workspace:*", "diff": "8.0.3", - "effect": "catalog:" + "effect": "catalog:", + "koffi": "3.3.6" }, "devDependencies": { "@effect/platform-node": "catalog:", diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index 21ae7f7fb199..8dbdd566a8e8 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -34,6 +34,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; import { appendAcpStderrTail, sanitizeAcpStderrExcerpt } from "./stderr.ts"; +import { makeDarwinProcessTreeController } from "./darwinProcessTree.ts"; import { collectSessionConfigOptionValues, decideToolCallUpdateEmission, @@ -751,6 +752,7 @@ export function makePosixProcessTreeController( platform: NodeJS.Platform, ): AcpPosixProcessTreeController { if (platform === "linux") return makeLinuxProcessTreeController(); + if (platform === "darwin") return makeDarwinProcessTreeController(); throw new AcpProcessGroupTerminationError({ detail: `Detached ACP descendant ownership is unsupported on ${platform}`, }); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 7402b5ec9b0e..0c14cb562dd8 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -1550,6 +1550,7 @@ interface ActiveAcpTurn { finalized: boolean; finalizedStatus: "completed" | "interrupted" | "failed" | "cancelled" | null; promptSettled: boolean; + runtimeTerminated: boolean; promptSettledStatus: "completed" | "interrupted" | "failed" | "cancelled" | null; workAccepted: boolean; readonly promptWireSettled: Deferred.Deferred; @@ -2570,12 +2571,38 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ? notePromptProgress() : Effect.void, ); + const failTurnOnRuntimeTermination = Effect.fn("AcpAdapterV2.failTurnOnRuntimeTermination")( + function* (context: ActiveAcpTurn, runtimeGeneration: number) { + yield* quarantineNativeTransportAtGeneration(runtimeGeneration); + yield* advanceRuntimeCallbackGeneration; + yield* cancelPendingRuntimeRequests(); + for (const tool of context.tools.values()) { + const status = toolStatus(tool.status); + if (status === "pending" || status === "running" || status === "waiting") { + yield* emitTool(context, tool, context.interrupted ? "interrupted" : "failed"); + } + } + yield* finalizeTurn( + context, + "failed", + makeProviderFailure({ class: "transport_error" }), + ); + }, + ); const handleRuntimeTerminationAtGeneration = (runtimeGeneration: number) => runRuntimeCallbackAtGeneration( runtimeGeneration, Effect.gen(function* () { yield* Ref.set(runtimeRestartRequired, true); - if (!followsAgentWorkState) return; + if (!followsAgentWorkState) { + const context = yield* Ref.get(activeTurn); + if (context === null || context.finalized) return; + context.runtimeTerminated = true; + if (context.promptSettled) { + yield* failTurnOnRuntimeTermination(context, runtimeGeneration); + } + return; + } agentWork = { sessionUpdate: "state_update", state: "idle", stopReason: "error" }; for (const child of nativeChildren.values()) { if (child.status !== "running") continue; @@ -8812,6 +8839,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( finalized: false, finalizedStatus: null, promptSettled: false, + runtimeTerminated: false, promptSettledStatus: null, workAccepted: false, promptWireSettled, @@ -9055,6 +9083,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); } if (context.finalized || followsAgentWorkState) return; + if (context.runtimeTerminated && defersFinalizeForBackgroundWork) { + yield* failTurnOnRuntimeTermination(context, promptGeneration); + return; + } // ACP v2 reports a failed prompt through its idle stop reason, not an RPC error. const hiddenFailure = checkPromptOutcome === undefined || diff --git a/packages/provider-acp/src/server/darwinProcessTree.ts b/packages/provider-acp/src/server/darwinProcessTree.ts new file mode 100644 index 000000000000..f28780dd4be7 --- /dev/null +++ b/packages/provider-acp/src/server/darwinProcessTree.ts @@ -0,0 +1,85 @@ +// @effect-diagnostics nodeBuiltinImport:off -- Node module loading anchors Koffi's Darwin FFI to the packaged runtime. +import * as NodeModule from "node:module"; + +import type { + AcpPosixProcessIdentity, + AcpPosixProcessTreeController, +} from "./AcpSessionRuntime.ts"; + +const requireForFfi = NodeModule.createRequire(import.meta.url); + +export function makeDarwinProcessTreeController(): AcpPosixProcessTreeController { + const koffi = requireForFfi("koffi") as typeof import("koffi"); + const libproc = koffi.load("/usr/lib/libproc.dylib"); + const libc = koffi.load("/usr/lib/libSystem.B.dylib"); + const pidInfo = libproc.func( + "int proc_pidinfo(int pid, int flavor, uint64_t arg, void *buffer, int size)", + ); + const pidPath = libproc.func("int proc_pidpath(int pid, void *buffer, uint32_t size)"); + const listPids = libproc.func( + "int proc_listpids(uint32_t type, uint32_t info, void *buffer, int size)", + ); + const getSid = libc.func("int getsid(int pid)"); + + const pids = (type: number, info: number): ReadonlyArray => { + const read = (buffer: Buffer | null, size: number): number => { + // libproc reports errors as zero bytes and errno, also allowing an empty child list. + koffi.errno(0); + const bytes: number = listPids(type, info, buffer, size); + if (bytes < 0 || (bytes === 0 && koffi.errno() !== 0) || bytes % 4 !== 0) { + throw new Error("Failed to read Darwin process list"); + } + return bytes; + }; + const needed = read(null, 0); + // proc_listpids returns bytes; spare entries absorb forks between sizing and reading. + let size = needed + 4096; + for (let attempt = 0; attempt < 3; attempt += 1) { + const buffer = Buffer.alloc(size); + const bytes = read(buffer, size); + if (bytes < size) { + const result: Array = []; + for (let offset = 0; offset < bytes; offset += 4) { + const pid = buffer.readInt32LE(offset); + if (pid > 0) result.push(pid); + } + return result; + } + size *= 2; + } + throw new Error("Darwin process list exceeded its buffer"); + }; + + const identity = (pid: number): AcpPosixProcessIdentity | undefined => { + // SDK proc_bsdinfo uses this 136-byte layout on both Darwin arm64 and x64. + const info = Buffer.alloc(136); + if (pidInfo(pid, 3, 0, info, info.length) !== info.length) return undefined; + const sid: number = getSid(pid); + if (sid < 0 || info.readUInt32LE(12) !== pid) return undefined; + const path = Buffer.alloc(4096); + const pathLength: number = pidPath(pid, path, path.length); + return { + pid, + ppid: info.readUInt32LE(16), + pgid: info.readUInt32LE(100), + sid, + startTime: `${info.readBigUInt64LE(120)}.${info.readBigUInt64LE(128).toString().padStart(6, "0")}`, + state: info.readUInt32LE(4) === 5 ? "Z" : "live", + executable: + pathLength > 0 ? path.toString("utf8", 0, pathLength).replace(/\0.*$/s, "") : undefined, + }; + }; + const identities = (pids: ReadonlyArray) => + pids.flatMap((pid) => { + const observed = identity(pid); + return observed === undefined ? [] : [observed]; + }); + + return { + identity, + childPidsOf: (pid) => pids(6, pid), + childrenOf: (pid) => identities(pids(6, pid)), + snapshot: () => identities(pids(1, 0)), + signalProcess: (pid, signal) => process.kill(pid, signal), + }; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e89935d15f27..27891764c2da 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -949,6 +949,9 @@ importers: ffi-rs: specifier: 1.3.2 version: 1.3.2 + koffi: + specifier: 3.3.6 + version: 3.3.6 node-pty: specifier: 1.2.0-beta.15 version: 1.2.0-beta.15(patch_hash=ff8117509663fe1d5a07ef2648c324e80a9349b7d90401a00a591702615b8b30) @@ -1701,6 +1704,9 @@ importers: effect: specifier: 4.1.3 version: 4.1.3 + koffi: + specifier: 3.3.6 + version: 3.3.6 devDependencies: '@effect/platform-node': specifier: 4.1.2