fix(grok): align ACP extensions with open source runtime
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
664d82753f
commit
f14c150cf3
8 files changed
+219
-74
No files matched your search
@@ -120,8 +120,8 @@ export interface AcpAdapterV2ExtensionContext {
|
||||
readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"];
|
||||
/**
|
||||
* Session-scoped background-task lifecycle reported via extension
|
||||
* notifications (e.g. Grok `_x.ai/task_backgrounded` after a soft cancel
|
||||
* detaches foreground work). Mutations for non-root sessions are ignored.
|
||||
* notifications (e.g. Grok `x.ai/task_backgrounded`; older builds use the
|
||||
* underscore alias). Mutations for non-root sessions are ignored.
|
||||
*/
|
||||
readonly applyBackgroundTaskMutation: (mutation: {
|
||||
readonly sessionId: string;
|
||||
@@ -225,8 +225,9 @@ export interface AcpAdapterV2Flavor {
|
||||
/**
|
||||
* Optional parse of root-session synthetic text announcing a background
|
||||
* subagent's end ("Background subagent "<uuid>" ... completed successfully").
|
||||
* The agent may never hydrate via get_command_or_subagent_output, so this
|
||||
* notice can be the only terminal signal for the subagent row.
|
||||
* Older builds may never hydrate via get_command_or_subagent_output, so this
|
||||
* remains a terminal fallback. Current Grok additionally emits structured
|
||||
* `subagent_finished` session notifications.
|
||||
*/
|
||||
readonly extractSubagentEndNotice?: (text: string) =>
|
||||
| {
|
||||
|
||||
@@ -160,14 +160,14 @@ export function makeGrokAcpAdapterFlavor(options: GrokAdapterV2Options): AcpAdap
|
||||
// prompt while Grok continued, freezing T3 projection mid-turn.
|
||||
settleRootTurnWhenIdle: false,
|
||||
interruptPromptOnCancel: false,
|
||||
// User Stop (requestRuntimeRestart) still hard-kills the process group
|
||||
// and respawns: Grok `session/cancel` is detach-and-continue (the CLI
|
||||
// re-runs cancelled foreground work as a background task no client RPC
|
||||
// can kill, E3 harness 2026-07-18), so only a process kill truly stops
|
||||
// work. Non-Stop interrupts (mid-prompt steering, restart_active) omit
|
||||
// requestRuntimeRestart and stay soft: the session survives in the same
|
||||
// process, cancelled work backgrounds, and the model itself decides via
|
||||
// kill_command_or_subagent whether it keeps running.
|
||||
// User Stop (requestRuntimeRestart) still hard-kills the process group and
|
||||
// respawns so existing background tasks stop too. Older 0.2.x builds could
|
||||
// detach a cancelled foreground command (E3 harness 2026-07-18); current
|
||||
// source kills foreground work but intentionally preserves already-
|
||||
// backgrounded tasks. Non-Stop interrupts (mid-prompt steering,
|
||||
// restart_active) omit requestRuntimeRestart and stay soft: session/cancel
|
||||
// carries cancelTrigger=ctrl_c, the session survives, and background work
|
||||
// remains available to the replacement turn.
|
||||
restartRuntimeAfterInterrupt: true,
|
||||
terminateRuntimeProcessGroupOnInterrupt: true,
|
||||
// Steering restarts on a settled turn additionally skip session/cancel so
|
||||
|
||||
@@ -319,8 +319,9 @@ describe("AcpSessionRuntime", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("releases a fully silent prompt when session/cancel is requested", () =>
|
||||
Effect.gen(function* () {
|
||||
it.effect("releases a fully silent prompt and forwards configured cancel metadata", () => {
|
||||
const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
@@ -332,6 +333,19 @@ describe("AcpSessionRuntime", () => {
|
||||
|
||||
yield* TestClock.adjust("500 millis");
|
||||
yield* runtime.cancel;
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(
|
||||
protocolEvents.some(
|
||||
(event) =>
|
||||
event.direction === "outgoing" &&
|
||||
event.stage === "raw" &&
|
||||
typeof event.payload === "string" &&
|
||||
event.payload.includes('"method":"session/cancel"') &&
|
||||
event.payload.includes('"cancelTrigger":"ctrl_c"'),
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
const firstPromptResult = yield* Fiber.join(promptFiber);
|
||||
expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" });
|
||||
@@ -353,12 +367,20 @@ describe("AcpSessionRuntime", () => {
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
cancelMeta: { cancelTrigger: "ctrl_c" },
|
||||
protocolLogging: {
|
||||
logOutgoing: true,
|
||||
logger: (event) =>
|
||||
Effect.sync(() => {
|
||||
protocolEvents.push(event);
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("segments assistant text around ACP tool calls", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -73,6 +73,8 @@ export interface AcpSessionRuntimeOptions {
|
||||
readonly sessionLoadTimeout?: Duration.Input;
|
||||
readonly sessionLoadReplayIdleGap?: Duration.Input;
|
||||
readonly interruptPromptOnCancel?: boolean;
|
||||
/** Optional provider metadata forwarded on `session/cancel`. */
|
||||
readonly cancelMeta?: EffectAcpSchema.CancelNotification["_meta"];
|
||||
readonly ownDetachedProcessGroup?: boolean;
|
||||
readonly ownDescendantProcessGroups?: boolean;
|
||||
readonly processGroupPlatform?: NodeJS.Platform;
|
||||
@@ -2155,15 +2157,23 @@ export const make = (
|
||||
),
|
||||
cancel: getStartedState.pipe(
|
||||
Effect.flatMap((started) =>
|
||||
Effect.gen(function* () {
|
||||
const activePromptFiber = yield* Ref.get(activePromptFiberRef);
|
||||
if (Option.isSome(activePromptFiber)) {
|
||||
yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);
|
||||
}
|
||||
yield* acp.agent
|
||||
.cancel({ sessionId: started.sessionId })
|
||||
.pipe(Effect.ignore, Effect.forkIn(runtimeScope));
|
||||
}),
|
||||
options.interruptPromptOnCancel === false
|
||||
? acp.agent.cancel({
|
||||
sessionId: started.sessionId,
|
||||
...(options.cancelMeta === undefined ? {} : { _meta: options.cancelMeta }),
|
||||
})
|
||||
: Effect.gen(function* () {
|
||||
const activePromptFiber = yield* Ref.get(activePromptFiberRef);
|
||||
if (Option.isSome(activePromptFiber)) {
|
||||
yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);
|
||||
}
|
||||
yield* acp.agent
|
||||
.cancel({
|
||||
sessionId: started.sessionId,
|
||||
...(options.cancelMeta === undefined ? {} : { _meta: options.cancelMeta }),
|
||||
})
|
||||
.pipe(Effect.ignore, Effect.forkIn(runtimeScope));
|
||||
}),
|
||||
),
|
||||
),
|
||||
...(options.ownDetachedProcessGroup === true ? { terminateProcessGroup } : {}),
|
||||
|
||||
@@ -67,7 +67,7 @@ describe.runIf(process.env.T3_GROK_ACP_PROBE === "1")("Grok ACP CLI probe", () =
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("switches to another advertised model and completes a prompt", () =>
|
||||
it.effect("switches when another model is advertised and completes a prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeProbeRuntime;
|
||||
const started = yield* runtime.start();
|
||||
@@ -75,10 +75,13 @@ describe.runIf(process.env.T3_GROK_ACP_PROBE === "1")("Grok ACP CLI probe", () =
|
||||
const targetModel = models?.availableModels.find(
|
||||
({ modelId }) => modelId !== models.currentModelId,
|
||||
)?.modelId;
|
||||
expect(targetModel).toBeDefined();
|
||||
if (!targetModel) return;
|
||||
|
||||
yield* runtime.setSessionModel(targetModel).pipe(Effect.timeout("20 seconds"));
|
||||
// Model availability is account-dependent. Exercise a real switch when
|
||||
// possible, but a single-model catalog is valid and must still reach the
|
||||
// prompt check below.
|
||||
if (targetModel !== undefined) {
|
||||
yield* runtime.setSessionModel(targetModel).pipe(Effect.timeout("20 seconds"));
|
||||
}
|
||||
const result = yield* runtime
|
||||
.prompt({ prompt: [{ type: "text", text: "Respond with exactly: grok switch ok" }] })
|
||||
.pipe(Effect.timeout("60 seconds"));
|
||||
|
||||
@@ -81,6 +81,9 @@ export const makeGrokAcpRuntime = (
|
||||
...input,
|
||||
spawn: buildGrokAcpSpawnInput(input.grokSettings, input.cwd, input.environment),
|
||||
authMethodId: resolveGrokAuthMethodId(input.environment),
|
||||
// Current Grok treats Ctrl+C cancellation as a barrier against stale
|
||||
// background-task wake prompts until the next genuine user turn.
|
||||
cancelMeta: { ...input.cancelMeta, cancelTrigger: "ctrl_c" },
|
||||
...grokAcpRuntimeProcessOwnership(processGroupPlatform),
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
makeXAiAskUserQuestionResponse,
|
||||
makeXAiPromptCompletionRuntime,
|
||||
normalizeXAiAcpToolCallState,
|
||||
registerXAiBackgroundTaskTracking,
|
||||
resolveXAiAcpToolTitle,
|
||||
xAiBackgroundTaskLifecycleMutation,
|
||||
xAiPromptCompleteFromSessionUpdate,
|
||||
@@ -710,6 +711,57 @@ describe("XAiAcpExtension", () => {
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it.effect("tracks canonical Grok task lifecycle notifications", () =>
|
||||
Effect.gen(function* () {
|
||||
const handlers = new Map<string, (notification: unknown) => Effect.Effect<void>>();
|
||||
const mutations: Array<{
|
||||
readonly sessionId: string;
|
||||
readonly taskId: string;
|
||||
readonly status: "running" | "completed";
|
||||
}> = [];
|
||||
const runtime = {
|
||||
handleExtNotification: (
|
||||
method: string,
|
||||
_schema: unknown,
|
||||
handler: (notification: unknown) => Effect.Effect<void>,
|
||||
) => {
|
||||
handlers.set(method, handler);
|
||||
return Effect.void;
|
||||
},
|
||||
} as unknown as Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "handleExtNotification">;
|
||||
|
||||
yield* registerXAiBackgroundTaskTracking(runtime, (mutation) =>
|
||||
Effect.sync(() => mutations.push(mutation)),
|
||||
);
|
||||
|
||||
const backgrounded = handlers.get("x.ai/task_backgrounded");
|
||||
const completed = handlers.get("x.ai/task_completed");
|
||||
expect(backgrounded).toBeDefined();
|
||||
expect(completed).toBeDefined();
|
||||
yield* backgrounded!({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "task_backgrounded",
|
||||
tool_call_id: "call-bg-1",
|
||||
task_id: "task-bg-1",
|
||||
},
|
||||
});
|
||||
yield* completed!({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "task_completed",
|
||||
task_snapshot: { task_id: "task-bg-1" },
|
||||
},
|
||||
});
|
||||
expect(mutations).toEqual([
|
||||
{ sessionId: "session-1", taskId: "task-bg-1", status: "running" },
|
||||
{ sessionId: "session-1", taskId: "task-bg-1", status: "completed" },
|
||||
]);
|
||||
expect(handlers.has("_x.ai/task_backgrounded")).toBe(true);
|
||||
expect(handlers.has("_x.ai/task_completed")).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it("detects persistent Monitor start ACKs", () => {
|
||||
expect(
|
||||
isXAiPersistentMonitor({
|
||||
@@ -1187,7 +1239,7 @@ describe("XAiAcpExtension", () => {
|
||||
.prompt({ prompt: [{ type: "text", text: "hi" }] })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
const promptCompleteHandler = handlers.get("_x.ai/session/prompt_complete");
|
||||
const promptCompleteHandler = handlers.get("x.ai/session/prompt_complete");
|
||||
expect(promptCompleteHandler).toBeDefined();
|
||||
yield* promptCompleteHandler!({
|
||||
sessionId: "root-session",
|
||||
@@ -1195,6 +1247,7 @@ describe("XAiAcpExtension", () => {
|
||||
});
|
||||
const response = yield* Fiber.join(promptFiber);
|
||||
expect(response.stopReason).toBe("end_turn");
|
||||
expect(handlers.has("_x.ai/session/prompt_complete")).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1249,6 +1302,52 @@ describe("XAiAcpExtension", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles a hung prompt from released _x.ai/session_notification turns", () =>
|
||||
Effect.gen(function* () {
|
||||
const handlers = new Map<string, (notification: unknown) => Effect.Effect<void>>();
|
||||
const hungPrompt = yield* Deferred.make<never>();
|
||||
const baseRuntime = {
|
||||
start: () =>
|
||||
Effect.succeed({
|
||||
sessionId: "root-session",
|
||||
initializeResult: {},
|
||||
sessionSetupResult: {},
|
||||
modelConfigId: undefined,
|
||||
}),
|
||||
prompt: () => Deferred.await(hungPrompt),
|
||||
cancel: Effect.void,
|
||||
handleExtNotification: (
|
||||
method: string,
|
||||
_schema: unknown,
|
||||
handler: (notification: unknown) => Effect.Effect<void>,
|
||||
) => {
|
||||
handlers.set(method, handler);
|
||||
return Effect.void;
|
||||
},
|
||||
handleExtRequest: () => Effect.void,
|
||||
} as unknown as AcpSessionRuntime.AcpSessionRuntime["Service"];
|
||||
|
||||
const runtime = yield* makeXAiPromptCompletionRuntime(baseRuntime);
|
||||
const promptFiber = yield* runtime
|
||||
.prompt({ prompt: [{ type: "text", text: "hi" }] })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
const sessionNotificationHandler = handlers.get("_x.ai/session_notification");
|
||||
expect(sessionNotificationHandler).toBeDefined();
|
||||
yield* sessionNotificationHandler!({
|
||||
sessionId: "root-session",
|
||||
update: {
|
||||
sessionUpdate: "turn_completed",
|
||||
prompt_id: "t3-xai-prompt-1",
|
||||
stop_reason: "end_turn",
|
||||
},
|
||||
});
|
||||
const response = yield* Fiber.join(promptFiber);
|
||||
expect(response.stopReason).toBe("end_turn");
|
||||
expect(handlers.has("_x.ai/session/update")).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores turn_completed for non-pending prompt ids and task completions", () =>
|
||||
Effect.gen(function* () {
|
||||
const handlers = new Map<string, (notification: unknown) => Effect.Effect<void>>();
|
||||
|
||||
@@ -24,10 +24,14 @@ const XAiPromptCompleteNotification = Schema.Struct({
|
||||
type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type;
|
||||
|
||||
/**
|
||||
* Live Grok CLI (0.2.x) emits root turn completion as an extension session
|
||||
* update, not as top-level `_x.ai/session/prompt_complete`:
|
||||
* `{ method: "_x.ai/session/update", params: { sessionId, update: {
|
||||
* Grok persists root turn completion as an extension session update:
|
||||
* `{ params: { sessionId, update: {
|
||||
* sessionUpdate: "turn_completed", prompt_id, stop_reason } } }`.
|
||||
* The open-source runtime forwards it as `x.ai/session_notification` and
|
||||
* stores/replays it as `_x.ai/session/update`; released 0.2.106 forwards the
|
||||
* underscore alias `_x.ai/session_notification`. Current source also emits
|
||||
* the fire-and-forget canonical `x.ai/session/prompt_complete`, while released
|
||||
* builds use the underscore alias.
|
||||
*/
|
||||
const XAiSessionUpdateNotification = Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
@@ -324,7 +328,7 @@ export function extractXAiBackgroundTaskCompletion(toolCall: AcpToolCallState):
|
||||
|
||||
/**
|
||||
* A finished kill_command_or_subagent call is the genuine end signal for every
|
||||
* task id it names: the Grok CLI emits no `_x.ai/task_completed` for a killed
|
||||
* task id it names: the Grok CLI emits no `x.ai/task_completed` for a killed
|
||||
* task. A failed kill usually means the task was already gone, so it ends the
|
||||
* id too (failing open to a continuation beats pinning the running set).
|
||||
*/
|
||||
@@ -392,36 +396,32 @@ export function xAiBackgroundTaskLifecycleMutation(
|
||||
}
|
||||
|
||||
/**
|
||||
* Grok `session/cancel` is detach-and-continue: the CLI reaps the foreground
|
||||
* tool shell, then re-runs the command as a background task
|
||||
* (`_x.ai/task_backgrounded`) that executes to completion
|
||||
* (`_x.ai/task_completed`). Soft interrupts keep the process alive, so those
|
||||
* tasks must be tracked like monitors: residual frames buffer instead of
|
||||
* waking synthetic continuations, and pending-background-work stays truthful
|
||||
* until the task ends (or the model kills it via kill_command_or_subagent).
|
||||
* Grok task lifecycle notifications use canonical `x.ai/task_*` methods in
|
||||
* current builds; older 0.2.x builds used `_x.ai/task_*`. Interactive cancel
|
||||
* preserves tasks that were already backgrounded (and some older builds could
|
||||
* background the cancelled foreground command), so both spellings must be
|
||||
* tracked. Residual frames then buffer instead of waking synthetic
|
||||
* continuations, and pending-background-work stays truthful until the task
|
||||
* ends (or the model kills it via kill_command_or_subagent).
|
||||
*/
|
||||
export const registerXAiBackgroundTaskTracking = (
|
||||
runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "handleExtNotification">,
|
||||
apply: (mutation: XAiBackgroundTaskLifecycleMutation) => Effect.Effect<void>,
|
||||
): Effect.Effect<void, EffectAcpErrors.AcpError> =>
|
||||
Effect.gen(function* () {
|
||||
yield* runtime.handleExtNotification(
|
||||
"_x.ai/task_backgrounded",
|
||||
XAiTaskLifecycleNotification,
|
||||
(notification) => {
|
||||
const mutation = xAiBackgroundTaskLifecycleMutation(notification, "running");
|
||||
Effect.forEach(
|
||||
[
|
||||
["x.ai/task_backgrounded", "running"],
|
||||
["_x.ai/task_backgrounded", "running"],
|
||||
["x.ai/task_completed", "completed"],
|
||||
["_x.ai/task_completed", "completed"],
|
||||
] as const,
|
||||
([method, status]) =>
|
||||
runtime.handleExtNotification(method, XAiTaskLifecycleNotification, (notification) => {
|
||||
const mutation = xAiBackgroundTaskLifecycleMutation(notification, status);
|
||||
return mutation === null ? Effect.void : apply(mutation);
|
||||
},
|
||||
);
|
||||
yield* runtime.handleExtNotification(
|
||||
"_x.ai/task_completed",
|
||||
XAiTaskLifecycleNotification,
|
||||
(notification) => {
|
||||
const mutation = xAiBackgroundTaskLifecycleMutation(notification, "completed");
|
||||
return mutation === null ? Effect.void : apply(mutation);
|
||||
},
|
||||
);
|
||||
});
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
/**
|
||||
* Grok ACP often sends `title: "Tool"` even when rawInput has a useful
|
||||
@@ -1139,8 +1139,9 @@ const rememberCompletedXAiPromptId = (
|
||||
/**
|
||||
* Grok-specific ACP runtime wrapper. Races `session/prompt` against root-matched
|
||||
* terminal notifications:
|
||||
* - `_x.ai/session/update` + `turn_completed` + matching `prompt_id` (current CLI)
|
||||
* - `_x.ai/session/prompt_complete` (legacy / alternate builds)
|
||||
* - session notification/update + `turn_completed` + matching `prompt_id`
|
||||
* - `x.ai/session/prompt_complete` (open-source fire-and-forget signal)
|
||||
* - `_x.ai/session/prompt_complete` (released-build alias)
|
||||
*
|
||||
* Pending entries are keyed by root sessionId + T3-injected promptId, so
|
||||
* foreign/child sessions and `task-completed-*` ids do not settle the root turn.
|
||||
@@ -1164,22 +1165,28 @@ export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletion
|
||||
notification,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
yield* runtime.handleExtNotification(
|
||||
"_x.ai/session/prompt_complete",
|
||||
XAiPromptCompleteNotification,
|
||||
settleFromPromptComplete,
|
||||
yield* Effect.forEach(
|
||||
["x.ai/session/prompt_complete", "_x.ai/session/prompt_complete"] as const,
|
||||
(method) =>
|
||||
runtime.handleExtNotification(
|
||||
method,
|
||||
XAiPromptCompleteNotification,
|
||||
settleFromPromptComplete,
|
||||
),
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
yield* runtime.handleExtNotification(
|
||||
"_x.ai/session/update",
|
||||
XAiSessionUpdateNotification,
|
||||
(notification) => {
|
||||
const complete = xAiPromptCompleteFromSessionUpdate(notification);
|
||||
if (complete === null) {
|
||||
return Effect.void;
|
||||
}
|
||||
return settleFromPromptComplete(complete);
|
||||
},
|
||||
yield* Effect.forEach(
|
||||
["x.ai/session_notification", "_x.ai/session_notification", "_x.ai/session/update"] as const,
|
||||
(method) =>
|
||||
runtime.handleExtNotification(method, XAiSessionUpdateNotification, (notification) => {
|
||||
const complete = xAiPromptCompleteFromSessionUpdate(notification);
|
||||
if (complete === null) {
|
||||
return Effect.void;
|
||||
}
|
||||
return settleFromPromptComplete(complete);
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
Reference in new issue
Block a user