fix(orchestrator): harden Grok v2 lifecycle (#3578)
Integrate the current Grok settlement, monitor/subagent lifecycle, interrupt containment, steer visibility, and image support stack into the orchestration-v2 branch. Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
0282ab8608
commit
e16d4e514b
53 files changed
+15859
-985
No files matched your search
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -146,6 +146,46 @@ describe("CodexAdapterV2 assistant message streaming", () => {
|
||||
assert.equal((yield* Ref.get(updates)).length, 2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retains buffered text until completion updates are emitted", () =>
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* Ref.make<ReadonlyArray<CodexAgentMessageDeltaUpdate>>([]);
|
||||
const failNext = yield* Ref.make(true);
|
||||
const coalescer = yield* makeCodexAgentMessageDeltaCoalescer({
|
||||
flushIntervalMs: 50,
|
||||
emit: (update) =>
|
||||
Ref.getAndSet(failNext, false).pipe(
|
||||
Effect.flatMap((shouldFail) =>
|
||||
shouldFail
|
||||
? Effect.die("projection unavailable")
|
||||
: Ref.update(updates, (current) => [...current, update]),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "turn final" });
|
||||
const failedFlush = yield* coalescer.flushTurn("turn-1").pipe(Effect.exit);
|
||||
assert.equal(failedFlush._tag, "Failure");
|
||||
yield* coalescer.flushTurn("turn-1");
|
||||
|
||||
yield* coalescer.append({ turnId: "turn-1", itemId: "message-2", delta: "item final" });
|
||||
yield* Ref.set(failNext, true);
|
||||
const failedComplete = yield* coalescer
|
||||
.complete({ turnId: "turn-1", itemId: "message-2" })
|
||||
.pipe(Effect.exit);
|
||||
assert.equal(failedComplete._tag, "Failure");
|
||||
const completedText = yield* coalescer.complete({
|
||||
turnId: "turn-1",
|
||||
itemId: "message-2",
|
||||
});
|
||||
|
||||
assert.equal(completedText, "item final");
|
||||
assert.deepEqual(yield* Ref.get(updates), [
|
||||
{ turnId: "turn-1", itemId: "message-1", text: "turn final", completed: true },
|
||||
{ turnId: "turn-1", itemId: "message-2", text: "item final", completed: true },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("CodexAdapterV2 runtime policy", () => {
|
||||
|
||||
@@ -868,31 +868,37 @@ export const makeCodexAgentMessageDeltaCoalescer = Effect.fn(
|
||||
}) =>
|
||||
flushLock.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* Ref.modify(buffered, (current) => {
|
||||
const current = yield* Ref.get(buffered);
|
||||
const updates: Array<CodexAgentMessageDeltaUpdate> = [];
|
||||
for (const message of current.values()) {
|
||||
if (!options.predicate(message) || (options.onlyDirty && !message.dirty)) {
|
||||
continue;
|
||||
}
|
||||
updates.push({
|
||||
turnId: message.turnId,
|
||||
itemId: message.itemId,
|
||||
text: message.text,
|
||||
completed: options.completed,
|
||||
});
|
||||
}
|
||||
const emitUpdates = Effect.forEach(updates, input.emit, { discard: true });
|
||||
yield* options.releaseSchedule === true
|
||||
? emitUpdates.pipe(Effect.ensuring(Ref.set(flushScheduled, false)))
|
||||
: emitUpdates;
|
||||
yield* Ref.update(buffered, (current) => {
|
||||
const next = new Map(current);
|
||||
const pending: Array<CodexAgentMessageDeltaUpdate> = [];
|
||||
for (const [key, message] of current) {
|
||||
if (!options.predicate(message) || (options.onlyDirty && !message.dirty)) {
|
||||
continue;
|
||||
}
|
||||
pending.push({
|
||||
turnId: message.turnId,
|
||||
itemId: message.itemId,
|
||||
text: message.text,
|
||||
completed: options.completed,
|
||||
});
|
||||
if (options.completed) {
|
||||
next.delete(key);
|
||||
} else {
|
||||
next.set(key, { ...message, dirty: false });
|
||||
}
|
||||
}
|
||||
return [pending, next] as const;
|
||||
return next;
|
||||
});
|
||||
if (options.releaseSchedule === true) {
|
||||
yield* Ref.set(flushScheduled, false);
|
||||
}
|
||||
yield* Effect.forEach(updates, input.emit, { discard: true });
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -936,14 +942,15 @@ export const makeCodexAgentMessageDeltaCoalescer = Effect.fn(
|
||||
complete: ({ turnId, itemId, finalText }) =>
|
||||
flushLock.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const text = yield* Ref.modify(buffered, (current) => {
|
||||
const key = codexAgentMessageBufferKey(turnId, itemId);
|
||||
const existing = current.get(key);
|
||||
const key = codexAgentMessageBufferKey(turnId, itemId);
|
||||
const existing = (yield* Ref.get(buffered)).get(key);
|
||||
const text = finalText && finalText.length > 0 ? finalText : (existing?.text ?? "");
|
||||
yield* input.emit({ turnId, itemId, text, completed: true });
|
||||
yield* Ref.update(buffered, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(key);
|
||||
return [finalText && finalText.length > 0 ? finalText : (existing?.text ?? ""), next];
|
||||
return next;
|
||||
});
|
||||
yield* input.emit({ turnId, itemId, text, completed: true });
|
||||
return text;
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -1,9 +1,25 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts";
|
||||
import { AcpProviderCapabilitiesV2, acpPermissionDisposition } from "./AcpAdapterV2.ts";
|
||||
import { GrokProviderCapabilitiesV2 } from "./GrokAdapterV2.ts";
|
||||
import {
|
||||
AcpProviderCapabilitiesV2,
|
||||
acpCompletedTurnShouldTerminalizeTool,
|
||||
acpPermissionDisposition,
|
||||
acpRootSessionUpdateIngestsOutput,
|
||||
acpRootTurnCompletionDrainMs,
|
||||
acpRootTurnHasIngestedOutput,
|
||||
acpRootTurnIsIdle,
|
||||
acpRootTurnSettleDebounceMs,
|
||||
acpRootTurnShouldRearmRecoveryTimers,
|
||||
acpSupportsImagePrompts,
|
||||
} from "./AcpAdapterV2.ts";
|
||||
import {
|
||||
makeGrokAcpAdapterFlavor,
|
||||
GrokProviderCapabilitiesV2,
|
||||
type GrokAdapterV2Options,
|
||||
} from "./GrokAdapterV2.ts";
|
||||
|
||||
function permissionRequest(
|
||||
kind: EffectAcpSchema.ToolKind,
|
||||
@@ -37,7 +53,221 @@ function runtimePolicy(input: {
|
||||
});
|
||||
}
|
||||
|
||||
describe("acpRootTurnSettleDebounceMs", () => {
|
||||
it("keeps the historical debounce constant for re-enable experiments", () => {
|
||||
assert.equal(acpRootTurnSettleDebounceMs, 2_000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("acpRootTurnCompletionDrainMs", () => {
|
||||
it("gives trailing root chunks a short landing window", () => {
|
||||
assert.equal(acpRootTurnCompletionDrainMs, 100);
|
||||
});
|
||||
});
|
||||
|
||||
describe("acpRootSessionUpdateIngestsOutput", () => {
|
||||
const sessionId = "session-1";
|
||||
|
||||
it("ignores empty assistant chunks used as Grok keepalives", () => {
|
||||
assert.isFalse(
|
||||
acpRootSessionUpdateIngestsOutput({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts non-empty assistant and reasoning chunks", () => {
|
||||
assert.isTrue(
|
||||
acpRootSessionUpdateIngestsOutput({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
acpRootSessionUpdateIngestsOutput({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_thought_chunk",
|
||||
content: { type: "text", text: "thinking" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts tool and plan updates", () => {
|
||||
assert.isTrue(
|
||||
acpRootSessionUpdateIngestsOutput({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-1",
|
||||
title: "Read",
|
||||
kind: "read",
|
||||
status: "pending",
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
acpRootSessionUpdateIngestsOutput({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [{ content: "Step 1", status: "pending", priority: "medium" }],
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("acpRootTurnHasIngestedOutput", () => {
|
||||
const empty = {
|
||||
assistant: { current: null, nextSegment: 0 },
|
||||
reasoning: { current: null, nextSegment: 0 },
|
||||
tools: new Map(),
|
||||
plan: null,
|
||||
} as const;
|
||||
|
||||
it("is false before any root turn items land", () => {
|
||||
assert.isFalse(acpRootTurnHasIngestedOutput(empty));
|
||||
});
|
||||
|
||||
it("is true once assistant segments have streamed", () => {
|
||||
assert.isTrue(
|
||||
acpRootTurnHasIngestedOutput({
|
||||
...empty,
|
||||
assistant: { current: null, nextSegment: 1 },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("acpRootTurn recovery timer re-arm", () => {
|
||||
it("re-arms idle settle after pending clears on active turns", () => {
|
||||
assert.isTrue(acpRootTurnShouldRearmRecoveryTimers({ finalized: false, interrupted: false }));
|
||||
});
|
||||
|
||||
it("skips re-arm when the turn is already terminal", () => {
|
||||
assert.isFalse(acpRootTurnShouldRearmRecoveryTimers({ finalized: true, interrupted: false }));
|
||||
assert.isFalse(acpRootTurnShouldRearmRecoveryTimers({ finalized: false, interrupted: true }));
|
||||
});
|
||||
});
|
||||
|
||||
describe("acpRootTurnIsIdle", () => {
|
||||
const quiet = {
|
||||
finalized: false,
|
||||
interrupted: false,
|
||||
assistantStreamOpen: false,
|
||||
reasoningStreamOpen: false,
|
||||
hasRunningTool: false,
|
||||
hasPendingRuntimeRequest: false,
|
||||
hasToolHistory: false,
|
||||
hasRunningSubagent: false,
|
||||
hasOutput: true,
|
||||
} as const;
|
||||
|
||||
it("is false while assistant text is still streaming", () => {
|
||||
assert.isFalse(acpRootTurnIsIdle({ ...quiet, assistantStreamOpen: true }));
|
||||
});
|
||||
|
||||
it("is false while a tool is running", () => {
|
||||
assert.isFalse(acpRootTurnIsIdle({ ...quiet, hasRunningTool: true }));
|
||||
});
|
||||
|
||||
it("is false after tool history (prompt RPC owns terminalization)", () => {
|
||||
assert.isFalse(acpRootTurnIsIdle({ ...quiet, hasToolHistory: true }));
|
||||
});
|
||||
|
||||
it("is false while a native subagent task is still running", () => {
|
||||
assert.isFalse(acpRootTurnIsIdle({ ...quiet, hasRunningSubagent: true }));
|
||||
});
|
||||
|
||||
it("is false when only reasoning or tools have streamed", () => {
|
||||
assert.isFalse(acpRootTurnIsIdle({ ...quiet, hasOutput: false }));
|
||||
});
|
||||
|
||||
it("is false for assistant-only quiet (preamble-before-tools must not settle)", () => {
|
||||
assert.isFalse(acpRootTurnIsIdle(quiet));
|
||||
});
|
||||
|
||||
it("is false when tools finished and root is quiet (no speculative multi-wave settle)", () => {
|
||||
assert.isFalse(
|
||||
acpRootTurnIsIdle({
|
||||
...quiet,
|
||||
hasToolHistory: true,
|
||||
hasRunningTool: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GrokAdapterV2 capabilities", () => {
|
||||
it("wires hard Stop teardown but soft non-Stop interrupts in the constructor flavor", () => {
|
||||
const flavor = makeGrokAcpAdapterFlavor({
|
||||
makeRuntime: () => Effect.never,
|
||||
} as unknown as GrokAdapterV2Options);
|
||||
|
||||
assert.isFalse(flavor.interruptPromptOnCancel);
|
||||
// User Stop (requestRuntimeRestart) keeps the hard process-group kill and
|
||||
// respawn: Grok cancel is detach-and-continue, so only a process kill
|
||||
// stops the work.
|
||||
assert.isTrue(flavor.restartRuntimeAfterInterrupt);
|
||||
assert.isTrue(flavor.terminateRuntimeProcessGroupOnInterrupt);
|
||||
// Non-Stop interrupts (steering, restart_active) reuse the process and
|
||||
// session; the cancelled work backgrounds and the model decides its fate.
|
||||
assert.isUndefined(flavor.restartRuntimeOnEveryInterrupt);
|
||||
assert.isTrue(flavor.preserveRuntimeOnSettledInterrupt);
|
||||
});
|
||||
|
||||
it("terminalizes only foreground tools under the actual Grok flavor", () => {
|
||||
const flavor = makeGrokAcpAdapterFlavor({
|
||||
makeRuntime: () => Effect.never,
|
||||
} as unknown as GrokAdapterV2Options);
|
||||
const foreground = {
|
||||
toolCallId: "foreground-1",
|
||||
title: "Terminal",
|
||||
status: "inProgress" as const,
|
||||
data: {
|
||||
rawInput: { command: "true" },
|
||||
rawOutput: { type: "Bash", exit_code: 0 },
|
||||
},
|
||||
};
|
||||
const monitor = {
|
||||
toolCallId: "monitor-1",
|
||||
title: "Monitor",
|
||||
status: "inProgress" as const,
|
||||
data: {
|
||||
rawInput: { variant: "Monitor", command: "sleep 30" },
|
||||
rawOutput: {
|
||||
type: "Monitor",
|
||||
taskId: "019f44b8-8e98-7c80-a40e-df1e26a5f9e3",
|
||||
},
|
||||
},
|
||||
};
|
||||
const subagent = {
|
||||
toolCallId: "subagent-1",
|
||||
title: "Task",
|
||||
status: "inProgress" as const,
|
||||
data: {
|
||||
rawInput: {
|
||||
description: "Inspect interrupt handling",
|
||||
prompt: "Review the adapter.",
|
||||
subagent_type: "generalPurpose",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
assert.isTrue(acpCompletedTurnShouldTerminalizeTool(foreground, flavor));
|
||||
assert.isFalse(acpCompletedTurnShouldTerminalizeTool(monitor, flavor));
|
||||
assert.isFalse(acpCompletedTurnShouldTerminalizeTool(subagent, flavor));
|
||||
});
|
||||
|
||||
it("keeps optional protocol features conservative until a flavor or handshake confirms them", () => {
|
||||
assert.isFalse(AcpProviderCapabilitiesV2.sessions.supportsModelSwitchInSession);
|
||||
assert.isFalse(AcpProviderCapabilitiesV2.sessions.supportsRuntimeModeSwitchInSession);
|
||||
@@ -45,6 +275,27 @@ describe("GrokAdapterV2 capabilities", () => {
|
||||
assert.isFalse(AcpProviderCapabilitiesV2.tools.supportsMcpTools);
|
||||
});
|
||||
|
||||
it("overrides ACP image capability false so screenshot attachments can prompt", () => {
|
||||
// Handshake alone would refuse attachments (Grok advertises image:false).
|
||||
assert.isFalse(
|
||||
acpSupportsImagePrompts({
|
||||
negotiatedImage: false,
|
||||
}),
|
||||
);
|
||||
// Flavor override unblocks image content blocks for Grok.
|
||||
assert.isTrue(
|
||||
acpSupportsImagePrompts({
|
||||
flavorSupportsImagePrompts: true,
|
||||
negotiatedImage: false,
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
acpSupportsImagePrompts({
|
||||
negotiatedImage: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("declares Grok Task envelopes as native subagents", () => {
|
||||
assert.isFalse(GrokProviderCapabilitiesV2.threads.canForkThread);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.subagents.supportsSubagents);
|
||||
|
||||
@@ -21,17 +21,26 @@ import {
|
||||
resolveGrokAcpBaseModelId,
|
||||
} from "../../provider/acp/GrokAcpSupport.ts";
|
||||
import {
|
||||
extractXAiAcpBackgroundToolMutation,
|
||||
extractXAiAcpSubagentEndNotice,
|
||||
extractXAiAcpSubagentUpdate,
|
||||
extractXAiAskUserQuestionIdentity,
|
||||
extractXAiAskUserQuestions,
|
||||
extractXAiAcpSubagentUpdate,
|
||||
extractXAiBackgroundTaskCompletion,
|
||||
extractXAiKilledBackgroundTasks,
|
||||
extractXAiMonitorTaskId,
|
||||
isXAiPersistentMonitor,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
normalizeXAiAcpToolCallState,
|
||||
registerXAiBackgroundTaskTracking,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "../../provider/acp/XAiAcpExtension.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
|
||||
import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts";
|
||||
import { IdAllocatorV2 } from "../IdAllocator.ts";
|
||||
import { ProviderContinuationRequests } from "../ProviderContinuationRequests.ts";
|
||||
import { ProviderAdapterV2 } from "../ProviderAdapter.ts";
|
||||
import {
|
||||
ProviderAdapterDriverCreateError,
|
||||
@@ -41,6 +50,7 @@ import {
|
||||
import {
|
||||
AcpProviderCapabilitiesV2,
|
||||
makeAcpAdapterV2,
|
||||
type AcpAdapterV2ExtensionContext,
|
||||
type AcpAdapterV2Flavor,
|
||||
type AcpAdapterV2RuntimeInput,
|
||||
} from "./AcpAdapterV2.ts";
|
||||
@@ -88,6 +98,7 @@ export interface GrokAdapterV2Options {
|
||||
readonly idAllocator: IdAllocatorV2["Service"];
|
||||
readonly serverConfig: ServerConfig["Service"];
|
||||
readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
|
||||
readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];
|
||||
readonly makeRuntime?: (
|
||||
input: AcpAdapterV2RuntimeInput,
|
||||
) => Effect.Effect<
|
||||
@@ -101,7 +112,16 @@ export interface GrokAdapterV2Options {
|
||||
export const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["registerExtensions"]> = ({
|
||||
runtime,
|
||||
requestUserInput,
|
||||
applyBackgroundTaskMutation,
|
||||
}) =>
|
||||
registerXAiBackgroundTaskTracking(runtime, applyBackgroundTaskMutation).pipe(
|
||||
Effect.andThen(registerGrokAskUserQuestionExtensions({ runtime, requestUserInput })),
|
||||
);
|
||||
|
||||
const registerGrokAskUserQuestionExtensions = ({
|
||||
runtime,
|
||||
requestUserInput,
|
||||
}: Pick<AcpAdapterV2ExtensionContext, "runtime" | "requestUserInput">) =>
|
||||
Effect.forEach(
|
||||
["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,
|
||||
(method) =>
|
||||
@@ -115,37 +135,78 @@ export const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["register
|
||||
}));
|
||||
return requestUserInput({
|
||||
nativeItemId: `${identity.sessionId}:xai-question:${identity.toolCallId}`,
|
||||
nativeMethod: method,
|
||||
nativeRequestId: identity.toolCallId,
|
||||
nativeSessionId: identity.sessionId,
|
||||
questions,
|
||||
}).pipe(
|
||||
Effect.map((answers) =>
|
||||
answers === null
|
||||
? makeXAiAskUserQuestionCancelledResponse()
|
||||
: makeXAiAskUserQuestionResponse(params, answers),
|
||||
Effect.flatMap(({ acknowledgeNativeResponse, answers }) =>
|
||||
Effect.succeed(
|
||||
answers === null
|
||||
? makeXAiAskUserQuestionCancelledResponse()
|
||||
: makeXAiAskUserQuestionResponse(params, answers),
|
||||
).pipe(Effect.tap(() => acknowledgeNativeResponse)),
|
||||
),
|
||||
);
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
|
||||
const flavor: AcpAdapterV2Flavor = {
|
||||
export function makeGrokAcpAdapterFlavor(options: GrokAdapterV2Options): AcpAdapterV2Flavor {
|
||||
return {
|
||||
driver: GROK_PROVIDER,
|
||||
capabilities: GrokProviderCapabilitiesV2,
|
||||
// Idle settle over-settled preamble-before-tools turns and cancelled the
|
||||
// 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.
|
||||
restartRuntimeAfterInterrupt: true,
|
||||
terminateRuntimeProcessGroupOnInterrupt: true,
|
||||
// Steering restarts on a settled turn additionally skip session/cancel so
|
||||
// fire-and-forget subagents survive the steer (E1 harness confirmed the
|
||||
// Grok CLI accepts a concurrent session/prompt in that state).
|
||||
preserveRuntimeOnSettledInterrupt: true,
|
||||
// Grok ACP initialize reports promptCapabilities.image:false but the agent
|
||||
// still accepts image content blocks (verified with real screenshots).
|
||||
supportsImagePrompts: true,
|
||||
resolveModelId: (selection) => resolveGrokAcpBaseModelId(selection.model),
|
||||
makeRuntime:
|
||||
options.makeRuntime ??
|
||||
((input) =>
|
||||
makeGrokAcpRuntime({
|
||||
...input,
|
||||
interruptPromptOnCancel: input.interruptPromptOnCancel ?? false,
|
||||
grokSettings: options.settings,
|
||||
environment: options.environment,
|
||||
childProcessSpawner: options.childProcessSpawner,
|
||||
})),
|
||||
registerExtensions: registerGrokAcpExtensions,
|
||||
extractSubagentUpdate: extractXAiAcpSubagentUpdate,
|
||||
extractSubagentEndNotice: extractXAiAcpSubagentEndNotice,
|
||||
normalizeToolCall: normalizeXAiAcpToolCallState,
|
||||
extractBackgroundTaskId: extractXAiMonitorTaskId,
|
||||
extractBackgroundToolMutation: extractXAiAcpBackgroundToolMutation,
|
||||
extractBackgroundTaskCompletion: (toolCall) => [
|
||||
...extractXAiBackgroundTaskCompletion(toolCall),
|
||||
...extractXAiKilledBackgroundTasks(toolCall),
|
||||
],
|
||||
isPersistentBackgroundTool: isXAiPersistentMonitor,
|
||||
deferFinalizeForBackgroundWork: true,
|
||||
enablePostSettleContinuation: true,
|
||||
...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
|
||||
const flavor = makeGrokAcpAdapterFlavor(options);
|
||||
return makeAcpAdapterV2({
|
||||
instanceId: options.instanceId,
|
||||
flavor,
|
||||
@@ -153,6 +214,9 @@ export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
|
||||
idAllocator: options.idAllocator,
|
||||
serverConfig: options.serverConfig,
|
||||
...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
|
||||
...(options.continuationRequests === undefined
|
||||
? {}
|
||||
: { continuationRequests: options.continuationRequests }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -176,6 +240,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapte
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const providerEventLoggers = yield* ProviderEventLoggers;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const continuationRequests = yield* ProviderContinuationRequests;
|
||||
const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
return makeGrokAdapterV2({
|
||||
instanceId: input.instanceId,
|
||||
@@ -185,6 +250,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapte
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
continuationRequests,
|
||||
nativeLogging: (threadId) =>
|
||||
makeNativeLogger({
|
||||
nativeEventLogger: providerEventLoggers.native,
|
||||
@@ -226,6 +292,7 @@ export const layer: Layer.Layer<
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const providerEventLoggers = yield* ProviderEventLoggers;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const continuationRequests = yield* ProviderContinuationRequests;
|
||||
const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
return makeGrokAdapterV2({
|
||||
instanceId: GROK_DEFAULT_INSTANCE_ID,
|
||||
@@ -235,6 +302,7 @@ export const layer: Layer.Layer<
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
continuationRequests,
|
||||
nativeLogging: (threadId) =>
|
||||
makeNativeLogger({
|
||||
nativeEventLogger: providerEventLoggers.native,
|
||||
|
||||
@@ -17,7 +17,11 @@ import * as Ref from "effect/Ref";
|
||||
|
||||
import { CheckpointRollbackServiceV2 } from "./CheckpointRollbackService.ts";
|
||||
import type { OrchestrationEffectV2 } from "./EffectOutbox.ts";
|
||||
import { executorLayer, OrchestrationEffectExecutorV2 } from "./EffectWorker.ts";
|
||||
import {
|
||||
executorLayer,
|
||||
isNonRetryableProviderTurnControlFailure,
|
||||
OrchestrationEffectExecutorV2,
|
||||
} from "./EffectWorker.ts";
|
||||
import { RunFinalizationService } from "./RunFinalizationService.ts";
|
||||
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
|
||||
import { ProviderTurnControlServiceV2 } from "./ProviderTurnControlService.ts";
|
||||
@@ -133,6 +137,40 @@ function makeExecutorLayer(input: {
|
||||
return executorLayer.pipe(Layer.provide(dependencies));
|
||||
}
|
||||
|
||||
it("does not retry pure interrupt races where the turn is already gone", () => {
|
||||
assert.isTrue(
|
||||
isNonRetryableProviderTurnControlFailure(
|
||||
"provider-turn.interrupt",
|
||||
"ProviderAdapterInterruptError: ... ACP provider turn provider-turn:x is not active",
|
||||
),
|
||||
);
|
||||
assert.isTrue(
|
||||
isNonRetryableProviderTurnControlFailure(
|
||||
"provider-turn.interrupt",
|
||||
"Provider session provider-session:x is not active.",
|
||||
),
|
||||
);
|
||||
// Restart is compound (interrupt + detach + start). Do not swallow start failures.
|
||||
assert.isFalse(
|
||||
isNonRetryableProviderTurnControlFailure(
|
||||
"provider-turn.restart",
|
||||
"Provider session provider-session:x is not active.",
|
||||
),
|
||||
);
|
||||
assert.isFalse(
|
||||
isNonRetryableProviderTurnControlFailure(
|
||||
"provider-turn.start",
|
||||
"Provider session provider-session:x is not active.",
|
||||
),
|
||||
);
|
||||
assert.isFalse(
|
||||
isNonRetryableProviderTurnControlFailure(
|
||||
"provider-turn.interrupt",
|
||||
"ACP hard teardown failed unexpectedly; the session is poisoned",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("detaches a handed-off session only after the old turn terminalizes", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
|
||||
@@ -25,6 +25,30 @@ export class OrchestrationEffectExecutionError extends Schema.TaggedErrorClass<O
|
||||
},
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Pure interrupt races with hard process teardown or a dead session produce
|
||||
* "not active" protocol errors. Retrying those only delays recovery.
|
||||
*
|
||||
* Do not apply this to `provider-turn.restart`: that compound effect also runs
|
||||
* detach and start. Swallowing a start failure that happens to mention
|
||||
* "is not active" would drop the outbox item without ever starting the
|
||||
* replacement turn.
|
||||
*/
|
||||
export function isNonRetryableProviderTurnControlFailure(
|
||||
effectType: string,
|
||||
errorText: string,
|
||||
): boolean {
|
||||
if (effectType !== "provider-turn.interrupt") {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
/is not active/i.test(errorText) ||
|
||||
/hard teardown is already in progress/i.test(errorText) ||
|
||||
/treating as already interrupted/i.test(errorText) ||
|
||||
/treating as already stopped/i.test(errorText)
|
||||
);
|
||||
}
|
||||
|
||||
export interface OrchestrationEffectExecutorV2Shape {
|
||||
readonly execute: (
|
||||
effect: OrchestrationEffectV2,
|
||||
@@ -348,14 +372,19 @@ export const layerWithOptions = (
|
||||
}
|
||||
|
||||
const error = Cause.pretty(exit.cause);
|
||||
const nonRetryable = isNonRetryableProviderTurnControlFailure(effect.request.type, error);
|
||||
yield* Effect.logWarning("Orchestration effect execution failed", {
|
||||
effectId: effect.id,
|
||||
effectType: effect.request.type,
|
||||
attemptCount: effect.attemptCount,
|
||||
nonRetryable,
|
||||
error,
|
||||
});
|
||||
const updated =
|
||||
effect.attemptCount >= maxAttempts
|
||||
// Prefer succeed for terminal interrupt races so the outbox does not
|
||||
// keep a failed interrupt around; fail only when we must not retry.
|
||||
const updated = nonRetryable
|
||||
? yield* outbox.succeed({ effectId: effect.id, workerId })
|
||||
: effect.attemptCount >= maxAttempts
|
||||
? yield* outbox.fail({ effectId: effect.id, workerId, error })
|
||||
: yield* outbox.retry({
|
||||
effectId: effect.id,
|
||||
|
||||
@@ -573,6 +573,7 @@ function activeLocalTurnItems(
|
||||
item,
|
||||
runs: projection.runs,
|
||||
attempts: projection.attempts,
|
||||
items: projection.turnItems,
|
||||
}),
|
||||
)
|
||||
.map((item, position) => ({
|
||||
@@ -668,6 +669,7 @@ function visibleTurnItemsThroughRun(input: {
|
||||
isOrchestrationV2SupersededInterrupt({
|
||||
item,
|
||||
attempts: input.sourceProjection.attempts,
|
||||
items: input.sourceProjection.turnItems,
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
|
||||
@@ -407,6 +407,8 @@ export interface ProviderAdapterV2SteerInput {
|
||||
export interface ProviderAdapterV2InterruptInput {
|
||||
readonly providerThread: OrchestrationV2ProviderThread;
|
||||
readonly providerTurnId: ProviderTurnId;
|
||||
/** When true, the next `startTurn` may respawn the provider runtime (Grok Stop recovery). */
|
||||
readonly requestRuntimeRestart?: boolean;
|
||||
}
|
||||
|
||||
export interface ProviderAdapterV2RuntimeRequestResponseInput {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ProviderDriverKind, ProviderThreadId, ThreadId } from "@t3tools/contrac
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
|
||||
export interface ProviderContinuationRequest {
|
||||
@@ -9,6 +10,9 @@ export interface ProviderContinuationRequest {
|
||||
readonly providerThreadId: ProviderThreadId;
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly detail: string | null;
|
||||
readonly dispatchIfCurrent?: <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
) => Effect.Effect<Option.Option<A>, E, R>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
|
||||
import {
|
||||
type ProviderContinuationRequest,
|
||||
ProviderContinuationRequests,
|
||||
layer as continuationRequestsLayer,
|
||||
} from "./ProviderContinuationRequests.ts";
|
||||
import { workerLive } from "./ProviderContinuationService.ts";
|
||||
import { ThreadManagementService } from "./ThreadManagementService.ts";
|
||||
|
||||
const threadId = ThreadId.make("thread-provider-continuation");
|
||||
const providerThreadId = ProviderThreadId.make("provider-thread-continuation");
|
||||
const driver = ProviderDriverKind.make("continuation-test");
|
||||
const projection = {
|
||||
thread: { archivedAt: null },
|
||||
messages: [],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
|
||||
const request = (
|
||||
dispatchIfCurrent?: ProviderContinuationRequest["dispatchIfCurrent"],
|
||||
detail: string | null = null,
|
||||
): ProviderContinuationRequest => ({
|
||||
threadId,
|
||||
providerThreadId,
|
||||
driver,
|
||||
detail,
|
||||
...(dispatchIfCurrent === undefined ? {} : { dispatchIfCurrent }),
|
||||
});
|
||||
|
||||
const makeGuard = Effect.fnUntraced(function* (completed?: Deferred.Deferred<void>) {
|
||||
const generation = yield* Ref.make(0);
|
||||
const permit = yield* Semaphore.make(1);
|
||||
const capture = Effect.gen(function* () {
|
||||
const captured = yield* Ref.updateAndGet(generation, (value) => value + 1);
|
||||
return <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
permit
|
||||
.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if ((yield* Ref.get(generation)) !== captured) return Option.none();
|
||||
return Option.some(yield* effect);
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
completed === undefined
|
||||
? (effect) => effect
|
||||
: Effect.ensuring(Deferred.succeed(completed, undefined)),
|
||||
);
|
||||
});
|
||||
return {
|
||||
capture,
|
||||
invalidate: permit.withPermit(Ref.update(generation, (value) => value + 1)),
|
||||
};
|
||||
});
|
||||
|
||||
function testLayer(input: {
|
||||
readonly dispatched: Queue.Queue<unknown>;
|
||||
readonly getThreadProjection: () => Effect.Effect<OrchestrationV2ThreadProjection>;
|
||||
}) {
|
||||
const threads = Layer.mock(ThreadManagementService)({
|
||||
getThreadProjection: input.getThreadProjection,
|
||||
dispatch: (command) => Queue.offer(input.dispatched, command).pipe(Effect.as({} as never)),
|
||||
});
|
||||
const worker = workerLive.pipe(
|
||||
Layer.provide(Layer.mergeAll(idAllocatorLayer, continuationRequestsLayer, threads)),
|
||||
);
|
||||
return Layer.merge(continuationRequestsLayer, worker);
|
||||
}
|
||||
|
||||
describe("ProviderContinuationService", () => {
|
||||
it.effect("dispatches a current request exactly once", () => {
|
||||
return Effect.gen(function* () {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
yield* requests.offer(request());
|
||||
yield* Queue.take(dispatched);
|
||||
yield* Effect.yieldNow;
|
||||
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({ dispatched, getThreadProjection: () => Effect.succeed(projection) }),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("drops a request invalidated before dispatch", () => {
|
||||
return Effect.gen(function* () {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
const guard = yield* makeGuard();
|
||||
const dispatchIfCurrent = yield* guard.capture;
|
||||
yield* guard.invalidate;
|
||||
yield* requests.offer(request(dispatchIfCurrent));
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({ dispatched, getThreadProjection: () => Effect.succeed(projection) }),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("drops a request invalidated while projection is blocked", () => {
|
||||
return Effect.gen(function* () {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
const projectionEntered = yield* Deferred.make<void>();
|
||||
const releaseProjection = yield* Deferred.make<void>();
|
||||
const guardCompleted = yield* Deferred.make<void>();
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
const guard = yield* makeGuard(guardCompleted);
|
||||
const dispatchIfCurrent = yield* guard.capture;
|
||||
yield* requests.offer(request(dispatchIfCurrent));
|
||||
yield* Deferred.await(projectionEntered);
|
||||
yield* guard.invalidate;
|
||||
yield* Deferred.succeed(releaseProjection, undefined);
|
||||
yield* Deferred.await(guardCompleted);
|
||||
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
dispatched,
|
||||
getThreadProjection: () =>
|
||||
Deferred.succeed(projectionEntered, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseProjection)),
|
||||
Effect.as(projection),
|
||||
),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("does not revive an old request when a later generation is current", () => {
|
||||
return Effect.gen(function* () {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
const firstProjectionEntered = yield* Deferred.make<void>();
|
||||
const releaseFirstProjection = yield* Deferred.make<void>();
|
||||
let projectionCalls = 0;
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests;
|
||||
const guard = yield* makeGuard();
|
||||
const first = yield* guard.capture;
|
||||
yield* requests.offer(request(first, "A"));
|
||||
yield* Deferred.await(firstProjectionEntered);
|
||||
const second = yield* guard.capture;
|
||||
yield* requests.offer(request(second, "B"));
|
||||
yield* Deferred.succeed(releaseFirstProjection, undefined);
|
||||
const command = yield* Queue.take(dispatched);
|
||||
assert.equal((command as { readonly text?: unknown }).text, "B");
|
||||
yield* Effect.yieldNow;
|
||||
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
dispatched,
|
||||
getThreadProjection: () => {
|
||||
projectionCalls += 1;
|
||||
return projectionCalls === 1
|
||||
? Deferred.succeed(firstProjectionEntered, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseFirstProjection)),
|
||||
Effect.as(projection),
|
||||
)
|
||||
: Effect.succeed(projection);
|
||||
},
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -32,14 +32,20 @@ export const workerLive = Layer.effectDiscard(
|
||||
threadId: request.threadId,
|
||||
providerThreadId: request.providerThreadId,
|
||||
});
|
||||
// Still run the guard so adapters can clear sticky continuationRequested.
|
||||
if (request.dispatchIfCurrent !== undefined) {
|
||||
yield* request.dispatchIfCurrent(Effect.void);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The ordinal is display metadata only: allocate.message appends a
|
||||
// random UUID, so a stale projection read here cannot collide ids.
|
||||
const messageId = yield* ids.allocate.message({
|
||||
threadId: request.threadId,
|
||||
ordinal: projection.messages.length + 1,
|
||||
});
|
||||
const commandId = CommandId.make(`provider-continuation:${messageId}`);
|
||||
yield* threads.dispatch({
|
||||
const dispatch = threads.dispatch({
|
||||
type: "message.dispatch",
|
||||
commandId,
|
||||
threadId: request.threadId,
|
||||
@@ -50,6 +56,11 @@ export const workerLive = Layer.effectDiscard(
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
});
|
||||
if (request.dispatchIfCurrent === undefined) {
|
||||
yield* dispatch;
|
||||
return;
|
||||
}
|
||||
yield* request.dispatchIfCurrent(dispatch);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -1233,6 +1233,99 @@ it.effect(
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ProviderSessionManagerV2 does not apply a stale idle pin to a replacement session", () =>
|
||||
Effect.gen(function* () {
|
||||
const state = yield* Ref.make(emptyState);
|
||||
const firstCheck = yield* Ref.make(true);
|
||||
const checkEntered = yield* Deferred.make<void>();
|
||||
const checkGate = yield* Deferred.make<void>();
|
||||
const effect = Effect.gen(function* () {
|
||||
const eventSink = yield* EventSinkV2;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const manager = yield* ProviderSessionManagerV2;
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = yield* idAllocator.allocate.thread({
|
||||
fixtureName: "provider-session-manager-stale-pin",
|
||||
projectId: yield* idAllocator.allocate.project({
|
||||
fixtureName: "provider-session-manager-stale-pin",
|
||||
}),
|
||||
});
|
||||
const providerSessionId = yield* idAllocator.allocate.providerSession({
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
threadId,
|
||||
});
|
||||
|
||||
yield* eventSink.write({
|
||||
events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
|
||||
});
|
||||
yield* manager.open({
|
||||
threadId,
|
||||
providerSessionId,
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
|
||||
// Park the first idle fiber inside an uninterruptible pending-work probe.
|
||||
yield* TestClock.adjust("1 second");
|
||||
yield* Deferred.await(checkEntered);
|
||||
|
||||
// close removes the map entry first, then waits to interrupt the idle
|
||||
// fiber (still uninterruptible). That window lets a replacement open
|
||||
// under the same providerSessionId before the stale probe finishes.
|
||||
const closeFiber = yield* manager.close(providerSessionId).pipe(Effect.forkDetach);
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
yield* manager.open({
|
||||
threadId,
|
||||
providerSessionId,
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
assert.equal((yield* Ref.get(state)).openCount, 2);
|
||||
|
||||
// Stale probe reports pending work against the old runtime; the pin
|
||||
// stamp must no-op on the replacement (runtime / generation mismatch).
|
||||
yield* Deferred.succeed(checkGate, undefined);
|
||||
yield* Fiber.join(closeFiber);
|
||||
for (let i = 0; i < 10; i += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
assert.isTrue(Option.isSome(yield* manager.get(providerSessionId)));
|
||||
assert.equal((yield* Ref.get(state)).closeCount, 1);
|
||||
|
||||
// Replacement has no pending background work. After one idle window it
|
||||
// must release. A stale pin stamp would have deferred release until
|
||||
// maxIdlePinMs.
|
||||
yield* TestClock.adjust("1 second");
|
||||
yield* Effect.yieldNow;
|
||||
assert.isTrue(Option.isNone(yield* manager.get(providerSessionId)));
|
||||
assert.equal((yield* Ref.get(state)).closeCount, 2);
|
||||
});
|
||||
|
||||
yield* effect.pipe(
|
||||
Effect.provide(
|
||||
makeTestLayer({
|
||||
state,
|
||||
idleTimeoutMs: 1000,
|
||||
maxIdlePinMs: 60_000,
|
||||
hasPendingBackgroundWork: Effect.uninterruptible(
|
||||
Effect.gen(function* () {
|
||||
if (yield* Ref.getAndSet(firstCheck, false)) {
|
||||
yield* Deferred.succeed(checkEntered, undefined);
|
||||
yield* Deferred.await(checkGate);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"ProviderSessionManagerV2 keeps active sessions alive until the provider turn terminates",
|
||||
() =>
|
||||
|
||||
@@ -605,31 +605,47 @@ export const layerWithOptions = (
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// Capture runtime identity before yielding: a replacement session
|
||||
// can reuse the same providerSessionId while this fiber is parked.
|
||||
const probedRuntime = entry.runtime;
|
||||
const hasPendingWork =
|
||||
entry.runtime.hasPendingBackgroundWork === undefined
|
||||
probedRuntime.hasPendingBackgroundWork === undefined
|
||||
? false
|
||||
: yield* entry.runtime.hasPendingBackgroundWork.pipe(
|
||||
: yield* probedRuntime.hasPendingBackgroundWork.pipe(
|
||||
Effect.catchCause(() => Effect.succeed(false)),
|
||||
);
|
||||
if (hasPendingWork) {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const pinnedSinceMs = entry.pinnedSinceMs ?? now;
|
||||
if (now - pinnedSinceMs < maxIdlePinMs) {
|
||||
const shouldContinuePin = yield* Ref.modify(sessions, (latest) => {
|
||||
const latestEntry = latest.get(key);
|
||||
if (
|
||||
latestEntry === undefined ||
|
||||
latestEntry.busyCount > 0 ||
|
||||
latestEntry.idleGeneration !== input.generation ||
|
||||
latestEntry.runtime !== probedRuntime
|
||||
) {
|
||||
return [false, latest] as const;
|
||||
}
|
||||
const updated = new Map(latest);
|
||||
updated.set(key, { ...latestEntry, pinnedSinceMs });
|
||||
return [true, updated] as const;
|
||||
});
|
||||
if (!shouldContinuePin) {
|
||||
// Generation or runtime advanced while we probed pending work;
|
||||
// the current owner of the entry owns idle release.
|
||||
return;
|
||||
}
|
||||
yield* Effect.logInfo("orchestration-v2.driver-session.idle-release-deferred", {
|
||||
providerSessionId: input.providerSessionId,
|
||||
pinnedForMs: now - pinnedSinceMs,
|
||||
});
|
||||
yield* Ref.update(sessions, (latest) => {
|
||||
const latestEntry = latest.get(key);
|
||||
if (latestEntry === undefined || latestEntry.busyCount > 0) {
|
||||
return latest;
|
||||
}
|
||||
const updated = new Map(latest);
|
||||
updated.set(key, { ...latestEntry, pinnedSinceMs });
|
||||
return updated;
|
||||
});
|
||||
yield* scheduleIdleReleaseInternal(input.providerSessionId);
|
||||
return;
|
||||
// Re-check on this fiber after another idle window. Do not call
|
||||
// scheduleIdleReleaseInternal: that cancels entry.idleFiber, which
|
||||
// is this fiber, and can self-deadlock on Fiber.interrupt.
|
||||
yield* Effect.sleep(Duration.millis(idleTimeoutMs));
|
||||
return yield* releaseIfStillIdle(input);
|
||||
}
|
||||
yield* Effect.logWarning("orchestration-v2.driver-session.idle-release-pin-expired", {
|
||||
providerSessionId: input.providerSessionId,
|
||||
|
||||
@@ -129,6 +129,28 @@ export const layer: Layer.Layer<
|
||||
}
|
||||
const session = yield* sessions.get(input.providerSessionId);
|
||||
if (Option.isNone(session)) {
|
||||
// Interrupt/restart against a already-released session must not fail
|
||||
// the durable effect (and retry 5x). The turn may still look running
|
||||
// in projection until recovery/finalization; there is no live adapter
|
||||
// to interrupt.
|
||||
if (input.operation === "interrupt" || input.operation === "restart") {
|
||||
yield* Effect.logWarning(
|
||||
"Provider interrupt/restart found no live session; treating as already stopped",
|
||||
{
|
||||
threadId: input.threadId,
|
||||
operation: input.operation,
|
||||
providerSessionId: input.providerSessionId,
|
||||
providerTurnId: input.providerTurnId,
|
||||
providerTurnStatus: providerTurn.status,
|
||||
},
|
||||
);
|
||||
return {
|
||||
projection,
|
||||
providerThread: interruptProviderThread,
|
||||
providerTurn,
|
||||
session: Option.none(),
|
||||
};
|
||||
}
|
||||
return yield* new ProviderTurnControlError({
|
||||
threadId: input.threadId,
|
||||
operation: input.operation,
|
||||
@@ -147,6 +169,7 @@ export const layer: Layer.Layer<
|
||||
yield* loaded.session.value.interruptTurn({
|
||||
providerThread: loaded.providerThread,
|
||||
providerTurnId: loaded.providerTurn.id,
|
||||
requestRuntimeRestart: true,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
@@ -163,13 +186,28 @@ export const layer: Layer.Layer<
|
||||
interruptAndAwaitTerminal: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const loaded = yield* load({ ...input, operation: "restart" });
|
||||
if (Option.isSome(loaded.session)) {
|
||||
yield* loaded.session.value.interruptTurn({
|
||||
providerThread: loaded.providerThread,
|
||||
providerTurnId: loaded.providerTurn.id,
|
||||
});
|
||||
if (Option.isNone(loaded.session)) {
|
||||
// No live adapter: nothing can emit a terminal provider-turn update
|
||||
// from interrupt. Do not poll for projection terminalization or the
|
||||
// restart effect stalls; let detach/start proceed.
|
||||
if (loaded.providerTurn.status === "running") {
|
||||
yield* Effect.logWarning(
|
||||
"Provider restart interrupt skipped; no live session for a still-projected running turn",
|
||||
{
|
||||
threadId: input.threadId,
|
||||
providerSessionId: input.providerSessionId,
|
||||
providerTurnId: input.providerTurnId,
|
||||
},
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
yield* loaded.session.value.interruptTurn({
|
||||
providerThread: loaded.providerThread,
|
||||
providerTurnId: loaded.providerTurn.id,
|
||||
});
|
||||
|
||||
for (let remaining = 1_000; remaining > 0; remaining -= 1) {
|
||||
const projection = yield* projections.getThreadProjection(input.threadId);
|
||||
const providerTurn = projection.providerTurns.find(
|
||||
|
||||
@@ -439,6 +439,23 @@ export const layer: Layer.Layer<
|
||||
}),
|
||||
Effect.catchCause(() => Effect.succeed(false)),
|
||||
),
|
||||
hasUnpairedRunInterruptRequest: () =>
|
||||
projectionStore.getThreadProjection(projection.thread.id).pipe(
|
||||
Effect.map((current) => {
|
||||
const requestId = idAllocator.derive.runSignalTurnItem({
|
||||
runId: run.id,
|
||||
signal: "interrupt-request",
|
||||
});
|
||||
const resultId = idAllocator.derive.runSignalTurnItem({
|
||||
runId: run.id,
|
||||
signal: "interrupt-result",
|
||||
});
|
||||
const hasRequest = current.turnItems.some((item) => item.id === requestId);
|
||||
const hasResult = current.turnItems.some((item) => item.id === resultId);
|
||||
return hasRequest && !hasResult;
|
||||
}),
|
||||
Effect.catchCause(() => Effect.succeed(false)),
|
||||
),
|
||||
message: {
|
||||
messageId: message.id,
|
||||
text:
|
||||
|
||||
@@ -31,7 +31,7 @@ import * as Stream from "effect/Stream";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
|
||||
import { IdAllocatorV2, layer as idAllocatorLayer } from "./IdAllocator.ts";
|
||||
import type { ProviderAdapterV2Event, ProviderAdapterV2SessionRuntime } from "./ProviderAdapter.ts";
|
||||
import { ProviderEventIngestorV2 } from "./ProviderEventIngestor.ts";
|
||||
import {
|
||||
@@ -542,6 +542,194 @@ it.effect("does not pin ingestion on background items when the root turn is inte
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("omits run_interrupt_result when a superseding attempt already owns the run", () =>
|
||||
Effect.gen(function* () {
|
||||
const written = yield* captureInterruptTerminalTurnItems({
|
||||
key: "steer-supersede",
|
||||
shouldFinalizeRun: () => Effect.succeed(false),
|
||||
});
|
||||
assert.deepEqual(
|
||||
written.map((item) => item.type),
|
||||
[],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits run_interrupt_result when superseded attempt still has a hard-stop request", () =>
|
||||
Effect.gen(function* () {
|
||||
const written = yield* captureInterruptTerminalTurnItems({
|
||||
key: "stop-then-steer-supersede",
|
||||
shouldFinalizeRun: () => Effect.succeed(false),
|
||||
hasUnpairedRunInterruptRequest: () => Effect.succeed(true),
|
||||
});
|
||||
assert.deepEqual(
|
||||
written.map((item) => item.type),
|
||||
["run_interrupt_result"],
|
||||
);
|
||||
const ids = backgroundScenarioIds("stop-then-steer-supersede");
|
||||
const expectedRequestId = yield* Effect.gen(function* () {
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
return idAllocator.derive.runSignalTurnItem({
|
||||
runId: ids.runId,
|
||||
signal: "interrupt-request",
|
||||
});
|
||||
}).pipe(Effect.provide(idAllocatorLayer));
|
||||
assert.equal(written[0]?.parentItemId, expectedRequestId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("omits run_interrupt_result when superseded attempt request is already paired", () =>
|
||||
Effect.gen(function* () {
|
||||
const written = yield* captureInterruptTerminalTurnItems({
|
||||
key: "stop-then-steer-already-paired",
|
||||
shouldFinalizeRun: () => Effect.succeed(false),
|
||||
hasUnpairedRunInterruptRequest: () => Effect.succeed(false),
|
||||
});
|
||||
assert.deepEqual(
|
||||
written.map((item) => item.type),
|
||||
[],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits run_interrupt_result when hard-stop finalizes the active attempt", () =>
|
||||
Effect.gen(function* () {
|
||||
const written = yield* captureInterruptTerminalTurnItems({
|
||||
key: "hard-stop",
|
||||
shouldFinalizeRun: () => Effect.succeed(true),
|
||||
});
|
||||
assert.deepEqual(
|
||||
written.map((item) => item.type),
|
||||
["run_interrupt_result"],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
function captureInterruptTerminalTurnItems(input: {
|
||||
readonly key: string;
|
||||
readonly shouldFinalizeRun: () => Effect.Effect<boolean, never>;
|
||||
readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
|
||||
}) {
|
||||
return Effect.gen(function* () {
|
||||
const ids = backgroundScenarioIds(input.key);
|
||||
const providerInstanceId = ProviderInstanceId.make("codex");
|
||||
const writtenItems = yield* Ref.make<
|
||||
ReadonlyArray<{ readonly type: string; readonly parentItemId: string | null }>
|
||||
>([]);
|
||||
const ingestionDone = yield* Deferred.make<void>();
|
||||
const captureTurnItem = (payload: {
|
||||
readonly type: string;
|
||||
readonly parentItemId: string | null;
|
||||
}) =>
|
||||
Ref.update(writtenItems, (current) => [
|
||||
...current,
|
||||
{ type: payload.type, parentItemId: payload.parentItemId },
|
||||
]);
|
||||
const testLayer = runExecutionServiceLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
|
||||
Layer.mock(EventSinkV2)({
|
||||
write: (payload) =>
|
||||
Effect.gen(function* () {
|
||||
for (const event of payload.events) {
|
||||
if (event.type === "turn-item.updated") {
|
||||
yield* captureTurnItem(event.payload);
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
writeWithEffects: (payload) =>
|
||||
Effect.gen(function* () {
|
||||
for (const event of payload.events) {
|
||||
if (event.type === "turn-item.updated") {
|
||||
yield* captureTurnItem(event.payload);
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
writeIfRunCurrent: () => Effect.succeed({ committed: true, storedEvents: [] }),
|
||||
}),
|
||||
idAllocatorLayer,
|
||||
Layer.mock(ProviderEventIngestorV2)({
|
||||
ingestNormalized: () => Effect.succeed([]),
|
||||
}),
|
||||
ServerSettingsService.layerTest(),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const runExecution = yield* RunExecutionServiceV2;
|
||||
yield* runExecution.startRootRun({
|
||||
commandId: CommandId.make(`command:${input.key}`),
|
||||
appThread: { id: ids.threadId } as OrchestrationV2AppThread,
|
||||
providerSessionId: ProviderSessionId.make(`session:${input.key}`),
|
||||
session: {
|
||||
events: Stream.empty,
|
||||
subscribeEvents: Effect.succeed({
|
||||
events: Stream.fromIterable([rootTerminalEvent(ids, "interrupted")]),
|
||||
close: Deferred.succeed(ingestionDone, undefined),
|
||||
}),
|
||||
startTurn: () => Effect.void,
|
||||
} as unknown as ProviderAdapterV2SessionRuntime,
|
||||
run: {
|
||||
id: ids.runId,
|
||||
threadId: ids.threadId,
|
||||
ordinal: 1,
|
||||
providerInstanceId,
|
||||
} as OrchestrationV2Run,
|
||||
rootNode: {
|
||||
id: ids.rootNodeId,
|
||||
providerTurnId: ids.rootProviderTurnId,
|
||||
} as OrchestrationV2ExecutionNode,
|
||||
checkpointScope: {
|
||||
id: CheckpointScopeId.make(`checkpoint-scope:${input.key}`),
|
||||
} as OrchestrationV2CheckpointScope,
|
||||
providerThread: {
|
||||
id: ids.providerThreadId,
|
||||
driver,
|
||||
} as OrchestrationV2ProviderThread,
|
||||
attempt: {
|
||||
id: ids.attemptId,
|
||||
providerTurnId: ids.rootProviderTurnId,
|
||||
} as OrchestrationV2RunAttempt,
|
||||
attemptId: ids.attemptId,
|
||||
providerTurnOrdinal: 1,
|
||||
shouldFinalizeRun: input.shouldFinalizeRun,
|
||||
...(input.hasUnpairedRunInterruptRequest === undefined
|
||||
? {}
|
||||
: {
|
||||
hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
|
||||
}),
|
||||
message: {
|
||||
messageId: MessageId.make(`message:${input.key}`),
|
||||
text: "interrupt projection",
|
||||
attachments: [],
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
},
|
||||
modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
|
||||
runtimePolicy: {
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
cwd: process.cwd(),
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "readOnly",
|
||||
access: { type: "fullAccess" },
|
||||
networkAccess: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
|
||||
const closed = yield* Deferred.await(ingestionDone).pipe(Effect.timeoutOption("2 seconds"));
|
||||
assert.isTrue(Option.isSome(closed), "event ingestion fiber did not finish");
|
||||
return yield* Ref.get(writtenItems);
|
||||
});
|
||||
}
|
||||
|
||||
interface BackgroundScenarioIds {
|
||||
readonly threadId: ThreadId;
|
||||
readonly childThreadId: ThreadId;
|
||||
|
||||
@@ -260,6 +260,7 @@ export interface RunExecutionServiceV2StartRootRunInput {
|
||||
readonly relatedProviderThreadIds?: ReadonlyArray<ProviderThreadId>;
|
||||
readonly shouldStartProviderTurn?: () => Effect.Effect<boolean, never>;
|
||||
readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
|
||||
readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
|
||||
readonly message: ProviderAdapterV2TurnMessage;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
|
||||
@@ -323,6 +324,7 @@ export const layer: Layer.Layer<
|
||||
readonly providerThread: OrchestrationV2ProviderThread;
|
||||
readonly attempt: OrchestrationV2RunAttempt;
|
||||
readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
|
||||
readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
|
||||
readonly terminal: ProviderTerminalEvent;
|
||||
readonly failureItemPersisted: boolean;
|
||||
}) =>
|
||||
@@ -336,30 +338,37 @@ export const layer: Layer.Layer<
|
||||
const shouldFinalizeRun =
|
||||
input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun();
|
||||
if (!shouldFinalizeRun) {
|
||||
// A newer attempt already owns the run and the command that created
|
||||
// it terminalized this attempt as superseded. Preserve that domain
|
||||
// status while retaining the provider's interruption artifact.
|
||||
// Superseded attempt (steer / selection restart). Emit
|
||||
// run_interrupt_result only when hard Stop left an unpaired request
|
||||
// for this run; plain steers and already-paired stops emit nothing.
|
||||
if (input.terminal.status === "interrupted") {
|
||||
yield* eventSink.write({
|
||||
events: [
|
||||
{
|
||||
id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
|
||||
type: "turn-item.updated" as const,
|
||||
threadId: input.run.threadId,
|
||||
runId: input.run.id,
|
||||
nodeId: input.rootNode.id,
|
||||
providerInstanceId: input.run.providerInstanceId,
|
||||
occurredAt: completedAt,
|
||||
payload: makeInterruptResultTurnItem({
|
||||
idAllocator,
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
providerThread: input.providerThread,
|
||||
completedAt,
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
const hasUnpairedRequest =
|
||||
input.hasUnpairedRunInterruptRequest === undefined
|
||||
? false
|
||||
: yield* input.hasUnpairedRunInterruptRequest();
|
||||
if (hasUnpairedRequest) {
|
||||
yield* eventSink.writeWithEffects({
|
||||
effects: [],
|
||||
events: [
|
||||
{
|
||||
id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
|
||||
type: "turn-item.updated" as const,
|
||||
threadId: input.run.threadId,
|
||||
runId: input.run.id,
|
||||
nodeId: input.rootNode.id,
|
||||
providerInstanceId: input.run.providerInstanceId,
|
||||
occurredAt: completedAt,
|
||||
payload: makeInterruptResultTurnItem({
|
||||
idAllocator,
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
providerThread: input.providerThread,
|
||||
completedAt,
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -594,6 +603,11 @@ export const layer: Layer.Layer<
|
||||
...(input.shouldFinalizeRun === undefined
|
||||
? {}
|
||||
: { shouldFinalizeRun: input.shouldFinalizeRun }),
|
||||
...(input.hasUnpairedRunInterruptRequest === undefined
|
||||
? {}
|
||||
: {
|
||||
hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
|
||||
}),
|
||||
terminal,
|
||||
failureItemPersisted: terminal.status === "failed",
|
||||
}).pipe(
|
||||
@@ -776,6 +790,12 @@ export const layer: Layer.Layer<
|
||||
...(input.shouldFinalizeRun === undefined
|
||||
? {}
|
||||
: { shouldFinalizeRun: input.shouldFinalizeRun }),
|
||||
...(input.hasUnpairedRunInterruptRequest === undefined
|
||||
? {}
|
||||
: {
|
||||
hasUnpairedRunInterruptRequest:
|
||||
input.hasUnpairedRunInterruptRequest,
|
||||
}),
|
||||
terminal: makeFailedTerminalEvent(
|
||||
makeProviderFailure({
|
||||
cause: Cause.squash(cause),
|
||||
@@ -847,6 +867,12 @@ export const layer: Layer.Layer<
|
||||
...(input.shouldFinalizeRun === undefined
|
||||
? {}
|
||||
: { shouldFinalizeRun: input.shouldFinalizeRun }),
|
||||
...(input.hasUnpairedRunInterruptRequest === undefined
|
||||
? {}
|
||||
: {
|
||||
hasUnpairedRunInterruptRequest:
|
||||
input.hasUnpairedRunInterruptRequest,
|
||||
}),
|
||||
terminal: makeFailedTerminalEvent(
|
||||
makeProviderFailure({
|
||||
cause: Cause.squash(cause),
|
||||
|
||||
@@ -490,7 +490,12 @@ it.live("restarts selection as a new attempt and retries after old-session clean
|
||||
projection.providerTurns.map((turn) => turn.status),
|
||||
["interrupted", "completed"],
|
||||
);
|
||||
assert.isTrue(projection.turnItems.some((item) => item.type === "run_interrupt_result"));
|
||||
assert.isFalse(
|
||||
projection.turnItems.some(
|
||||
(item) => item.type === "run_interrupt_request" || item.type === "run_interrupt_result",
|
||||
),
|
||||
"selection restart supersede must not project hard-Stop interrupt items",
|
||||
);
|
||||
assert.equal(projection.runs[0]?.modelSelection.model, replacementSelection.model);
|
||||
assert.isTrue(captured.failedReplacementOpen);
|
||||
// The old pooled process remains available to its other threads; this
|
||||
|
||||
@@ -24,7 +24,7 @@ export function assertCursorMessageSteeringOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertTurnItemTypes(projection, ["user_message", "run_interrupt_result", "assistant_message"]);
|
||||
assertTurnItemTypes(projection, ["user_message", "assistant_message"]);
|
||||
assertRuntimeRequestCounts(projection, { total: 0 });
|
||||
assertUserMessagesInclude(projection, [
|
||||
MESSAGE_STEERING_INITIAL_PROMPT,
|
||||
@@ -47,9 +47,10 @@ export function assertCursorMessageSteeringOutput(
|
||||
);
|
||||
assert.equal(projection.runs[0]?.activeAttemptId, projection.attempts[1]?.id);
|
||||
assert.equal(projection.runs[0]?.rootNodeId, projection.attempts[1]?.rootNodeId);
|
||||
assert.notInclude(
|
||||
projection.visibleTurnItems.map((row) => row.item.type),
|
||||
"run_interrupt_result",
|
||||
"restart steering must keep its internal interruption out of visible chat history",
|
||||
assert.isFalse(
|
||||
projection.turnItems.some(
|
||||
(item) => item.type === "run_interrupt_request" || item.type === "run_interrupt_result",
|
||||
),
|
||||
"steer supersede must not project run_interrupt_* items (those are hard Stop only)",
|
||||
);
|
||||
}
|
||||
@@ -23,7 +23,7 @@ export function assertGrokMessageSteeringOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertTurnItemTypes(projection, ["user_message", "run_interrupt_result", "assistant_message"]);
|
||||
assertTurnItemTypes(projection, ["user_message", "assistant_message"]);
|
||||
assertRuntimeRequestCounts(projection, { total: 0 });
|
||||
assertUserMessagesInclude(projection, [
|
||||
MESSAGE_STEERING_INITIAL_PROMPT,
|
||||
@@ -46,9 +46,10 @@ export function assertGrokMessageSteeringOutput(
|
||||
);
|
||||
assert.equal(projection.runs[0]?.activeAttemptId, projection.attempts[1]?.id);
|
||||
assert.equal(projection.runs[0]?.rootNodeId, projection.attempts[1]?.rootNodeId);
|
||||
assert.notInclude(
|
||||
projection.visibleTurnItems.map((row) => row.item.type),
|
||||
"run_interrupt_result",
|
||||
"restart steering must keep its internal interruption out of visible chat history",
|
||||
assert.isFalse(
|
||||
projection.turnItems.some(
|
||||
(item) => item.type === "run_interrupt_request" || item.type === "run_interrupt_result",
|
||||
),
|
||||
"steer supersede must not project run_interrupt_* items (those are hard Stop only)",
|
||||
);
|
||||
}
|
||||
@@ -753,6 +753,40 @@ describe("AcpSessionRuntime", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("completes ad-hoc loadSession after replay becomes idle while RPC stays pending", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
const loaded = yield* runtime.loadSession("mock-session-1").pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
expect(loaded.sessionId).toBe("mock-session-1");
|
||||
expect(loaded.sessionSetupResult._meta).toMatchObject({
|
||||
t3SessionLoadReady: "replay_idle",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1",
|
||||
T3_ACP_LOAD_SESSION_DELAY_MS: "10000",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
sessionLoadReplayIdleGap: "50 millis",
|
||||
sessionLoadTimeout: "1 second",
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
TestClock.withLive,
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid config option values before sending session/set_config_option", () => {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-"));
|
||||
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
parsePermissionRequest,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
sessionUpdateCountsAsLoadReplayActivity,
|
||||
sessionUpdateIsReplay,
|
||||
syntheticLoadSessionResponseFromInitialize,
|
||||
} from "./AcpRuntimeModel.ts";
|
||||
@@ -83,6 +84,98 @@ describe("AcpRuntimeModel", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores Grok keepalive chunks when tracking session/load replay activity", () => {
|
||||
expect(
|
||||
sessionUpdateCountsAsLoadReplayActivity({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "" },
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(false);
|
||||
expect(
|
||||
sessionUpdateCountsAsLoadReplayActivity({
|
||||
_meta: { isReplay: true },
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "replay-tool",
|
||||
title: "Replay",
|
||||
kind: "search",
|
||||
status: "completed",
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores load-replay activity from other sessions while a load gate is active", () => {
|
||||
expect(
|
||||
sessionUpdateCountsAsLoadReplayActivity(
|
||||
{
|
||||
sessionId: "session-other",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "unrelated" },
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification,
|
||||
"session-loading",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
sessionUpdateCountsAsLoadReplayActivity(
|
||||
{
|
||||
sessionId: "session-loading",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification,
|
||||
"session-loading",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("counts mode/config/session/usage updates as load-replay activity", () => {
|
||||
expect(
|
||||
sessionUpdateCountsAsLoadReplayActivity({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId: "code",
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(true);
|
||||
expect(
|
||||
sessionUpdateCountsAsLoadReplayActivity({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "config_option_update",
|
||||
configOptions: [],
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(true);
|
||||
expect(
|
||||
sessionUpdateCountsAsLoadReplayActivity({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "session_info_update",
|
||||
title: "Restored",
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(true);
|
||||
expect(
|
||||
sessionUpdateCountsAsLoadReplayActivity({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "usage_update",
|
||||
used: 1,
|
||||
size: 10,
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("builds a synthetic load response from initialize model state", () => {
|
||||
const response = syntheticLoadSessionResponseFromInitialize({
|
||||
protocolVersion: 1,
|
||||
|
||||
@@ -459,8 +459,38 @@ export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotificatio
|
||||
return isRecord(meta) && meta.isReplay === true;
|
||||
}
|
||||
|
||||
/** Replay chunks and substantive updates during session/load; not Grok keepalives. */
|
||||
export function sessionUpdateCountsAsLoadReplayActivity(
|
||||
params: EffectAcpSchema.SessionNotification,
|
||||
gatedSessionId?: string,
|
||||
): boolean {
|
||||
if (gatedSessionId !== undefined && params.sessionId !== gatedSessionId) {
|
||||
return false;
|
||||
}
|
||||
if (sessionUpdateIsReplay(params)) return true;
|
||||
const update = params.update;
|
||||
switch (update.sessionUpdate) {
|
||||
case "agent_message_chunk":
|
||||
case "agent_thought_chunk":
|
||||
return update.content.type === "text" && update.content.text.length > 0;
|
||||
case "tool_call":
|
||||
case "tool_call_update":
|
||||
case "plan":
|
||||
case "available_commands_update":
|
||||
case "current_mode_update":
|
||||
case "config_option_update":
|
||||
case "session_info_update":
|
||||
case "usage_update":
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export interface SessionLoadGate {
|
||||
readonly active: boolean;
|
||||
/** Only notifications for this session refresh load-replay idle activity. */
|
||||
readonly sessionId: string;
|
||||
readonly lastActivityAtMillis: number | undefined;
|
||||
readonly idleGap: Duration.Duration;
|
||||
readonly initializeResult: EffectAcpSchema.InitializeResponse;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -5,9 +5,33 @@ import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import {
|
||||
applyGrokAcpModelSelection,
|
||||
buildGrokAcpSpawnInput,
|
||||
grokAcpRuntimeProcessOwnership,
|
||||
resolveGrokAcpBaseModelId,
|
||||
} from "./GrokAcpSupport.ts";
|
||||
|
||||
describe("grokAcpRuntimeProcessOwnership", () => {
|
||||
it("opts Grok into detached process-tree ownership on the injected host platform", () => {
|
||||
expect(grokAcpRuntimeProcessOwnership("linux")).toEqual({
|
||||
ownDescendantProcessGroups: true,
|
||||
ownDetachedProcessGroup: true,
|
||||
processGroupPlatform: "linux",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the prior provider-group path on Darwin and Windows", () => {
|
||||
expect(grokAcpRuntimeProcessOwnership("darwin")).toEqual({
|
||||
ownDescendantProcessGroups: false,
|
||||
ownDetachedProcessGroup: true,
|
||||
processGroupPlatform: "darwin",
|
||||
});
|
||||
expect(grokAcpRuntimeProcessOwnership("win32")).toEqual({
|
||||
ownDescendantProcessGroups: false,
|
||||
ownDetachedProcessGroup: true,
|
||||
processGroupPlatform: "win32",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveGrokAcpBaseModelId", () => {
|
||||
it("normalizes empty and custom Grok model ids", () => {
|
||||
expect(resolveGrokAcpBaseModelId(undefined)).toBe("grok-build");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { type GrokSettings, ProviderDriverKind } from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -6,6 +7,7 @@ import * as Scope from "effect/Scope";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
@@ -48,6 +50,21 @@ function resolveGrokAuthMethodId(environment: NodeJS.ProcessEnv | undefined): st
|
||||
: GROK_AUTH_METHOD_CACHED_TOKEN;
|
||||
}
|
||||
|
||||
export function grokAcpRuntimeProcessOwnership(
|
||||
processGroupPlatform: NodeJS.Platform,
|
||||
): Pick<
|
||||
AcpSessionRuntime.AcpSessionRuntimeOptions,
|
||||
"ownDescendantProcessGroups" | "ownDetachedProcessGroup" | "processGroupPlatform"
|
||||
> {
|
||||
return {
|
||||
// macOS keeps the prior provider-group teardown until a stable libproc
|
||||
// identity provider can cover Grok's nested detached tool groups.
|
||||
ownDescendantProcessGroups: processGroupPlatform === "linux",
|
||||
ownDetachedProcessGroup: true,
|
||||
processGroupPlatform,
|
||||
};
|
||||
}
|
||||
|
||||
export const makeGrokAcpRuntime = (
|
||||
input: GrokAcpRuntimeInput,
|
||||
): Effect.Effect<
|
||||
@@ -56,11 +73,15 @@ export const makeGrokAcpRuntime = (
|
||||
Crypto.Crypto | Scope.Scope
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const processGroupPlatform = yield* HostProcessPlatform.pipe(
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
const acpContext = yield* Layer.build(
|
||||
AcpSessionRuntime.layer({
|
||||
...input,
|
||||
spawn: buildGrokAcpSpawnInput(input.grokSettings, input.cwd, input.environment),
|
||||
authMethodId: resolveGrokAuthMethodId(input.environment),
|
||||
...grokAcpRuntimeProcessOwnership(processGroupPlatform),
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user