Skip to content

Commit a7f9a7f

Browse files
authored
refactor(gateway): interrupt at admission; sessions.steer delegates to chat.send (#126291)
* refactor(gateway): interrupt at admission; sessions.steer delegates to chat.send chat.send queueMode interrupt now aborts the captured current operation at the session-work admission owner (exact-instance abort, never a same-key successor) and dispatches the new turn after the abort settles; channel-originated interrupts share the same primitive. sessions.steer keeps its validation, sharing/access checks, and response shape but becomes a thin deprecated adapter over that path - its private inflight/retry and hard-abort machine is deleted. The Control UI /redirect command rides canonical chat.send. Compaction's use of the old hard-interrupt helper moves unchanged to session-run-interruption.ts. * fix(gateway): interrupt non-reply admissions
1 parent 1fa82e9 commit a7f9a7f

25 files changed

Lines changed: 650 additions & 726 deletions

‎docs/gateway/protocol.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -655,7 +655,7 @@ methods. Treat this as feature discovery, not a full enumeration of
655655
- `sessions.move` moves an authorized active session to the Gateway, a paired device, or a configured profile. Gateway and device targets require `operator.write`; profile targets require `operator.admin`; malformed targets use the write scope before schema validation. The caller supplies the exact observed generation, environment, and owner epoch; session authorization and those source facts are revalidated before the move commits.
656656
- `sessions.groups.list`, `sessions.groups.put`, `sessions.groups.rename`, and `sessions.groups.delete` manage the gateway-owned custom session group catalog (names + display order). The read-scoped list result is intentionally path-free. `sessions.groups.defaults` and `sessions.groups.update` require `operator.write` and read or replace one custom group's optional working-directory and worktree defaults. Non-admin callers can save only directories inside a configured agent workspace; other absolute Gateway paths require `operator.admin`. Membership stays on each session's `category` field; rename and delete update member sessions server-side.
657657
- `sessions.send` sends a message into an existing session.
658-
- `sessions.steer` is the interrupt-and-steer variant for an active session.
658+
- `sessions.steer` is a deprecated alias for `chat.send` with `queueMode: "interrupt"`; removal follows the protocol deprecation policy.
659659
- `sessions.abort` aborts active work for a session. Pass `key` plus optional `runId`, or `runId` alone for active runs the gateway can resolve to a session. Supplying `runId` keeps cancellation scoped to that run. Set `clearQueued: true` on a key-only non-global request to also discard followup and lane queues owned by that session. Existing callers that omit `clearQueued` preserve those queues. The literal `global` key keeps the existing agent-qualified `chat.abort` ownership rules and does not perform non-global followup or lane cleanup.
660660
- `sessions.patch` updates session metadata/overrides and reports the resolved canonical model plus effective `agentRuntime`. Session organization fields and the per-session `model` override require `operator.write`; thinking, fast, verbose, trace, reasoning, and other privileged overrides require `operator.admin`. Only an admin model selection can persist as the configured agent default. Archive and restore patches require the caller-observed `sessionId` from `sessions.list` or `sessions.describe` as `expectedSessionId`; missing or changed targets fail without materializing or mutating a replacement. With `archived: true`, the Gateway protects agent main sessions (including `global` when global scope is configured) and the `unknown` sentinel; for every other real session it first fences new admission, cancels exact-session active, pending, queued, reply, embedded, and worker work, and waits for admission and runtime terminal-persistence drains before committing `archivedAt`. A cancellation, drain, or persistence failure returns retryable `UNAVAILABLE` and leaves the session unarchived. `sessions.patchMany` carries `expectedSessionId` per target, prepares archive targets in input order inside the same batch lifecycle fence, and returns ordered per-target outcomes. Spawn lineage (`spawnedBy`, `spawnedWorkspaceDir`, `spawnedCwd`, `spawnDepth`, `subagentRole`, `subagentControlScope`) is no longer publicly patchable; those facts are written once by trusted creation paths, and requests that still send them are rejected.
661661
- `sessions.assignOwner` (`operator.write`) reassigns the session's mutable owner to a person or configured agent (`{ key, owner: { type, id } }`). It requires an identified caller (authenticated profile or trusted agent identity), authorizes by session visibility, and records `assignedBy`/`assignedAt` on the row's `owner` field. The write-once `createdActor` and creator-anchored sharing authority are unchanged; see [Multi-user mode](/concepts/multi-user#assigning-an-owner).
@@ -665,7 +665,7 @@ methods. Treat this as feature discovery, not a full enumeration of
665665
Tail responses can include an opaque `deltaCursor`. Pass it back as `cursor` to `chat.history` or `chat.startup` instead of `offset` or `messageId`. A successful catch-up returns `{ kind: "delta", messages, deltaCursor, sessionInfo }`; replay each `messages` entry through the same reducer as a live `session.message` payload. `{ kind: "reset" }` means the cursor is invalid, stale, belongs to another session, crossed a reset or compaction, or is too far behind; fetch a normal tail page. Catch-up never returns a partial page or continuation: more than 200 raw events or the 1 MB payload budget resets to a tail fetch.
666666
- `chat.message.get` is the additive bounded full-message reader for a single visible transcript entry. Pass `sessionKey`, optional `agentId` when session selection is agent-scoped, and a transcript `messageId` previously surfaced through `chat.history`; the gateway returns the same display-normalized projection without the lightweight history truncation cap when the stored entry is still available and not oversized.
667667
- `chat.toolTitles` returns short purpose titles for tool calls rendered in the Control UI (batched, max 24 items with bounded inputs). The feature is opt-in via `gateway.controlUi.toolTitles` (default off); disabled gateways answer `{ titles: {}, disabled: true }` with no model call so clients stop asking. When enabled, titles use standard utility-model routing: an explicitly configured `utilityModel` (an operator decision that, like all utility tasks, may send bounded task content to the chosen provider), else the session provider's declared small-model default so no new egress destination appears implicitly; an empty `utilityModel` disables them entirely. Titles never fall back to the primary model. Results cache in the per-agent state database keyed by tool name + input, so repeated views never re-bill the same calls.
668-
- `chat.send` accepts one-turn `fastMode: "auto"` to use fast mode for model calls started before the auto cutoff, then start later retry, fallback, tool-result, or continuation calls without fast mode. The cutoff defaults to 60 seconds (`DEFAULT_FAST_MODE_AUTO_ON_SECONDS`) and can be configured per model with `agents.defaults.models["<provider>/<model>"].params.fastAutoOnSeconds`. A `chat.send` caller can pass one-turn `fastAutoOnSeconds` to override the cutoff for that request. Pass `queueMode` (`steer`, `followup`, `collect`, or `interrupt`) to override the stored queue mode for this request only; explicit Control UI steer actions use `queueMode: "steer"`. A steer send targets the selected session's current state: the Gateway atomically injects the message into that session's direct active run, or starts a new turn when the session is idle. Activity in descendant subagent sessions never makes the selected session busy for this decision. `expectedLeafEntryId` is an independent transcript-branch compare-and-swap for non-steer interactive sends: pass the displayed branch leaf (or deliberate `null` for an authoritative empty transcript) and the send rejects with `details.reason: "active-leaf-changed"` if another client switched transcript branches first; steer sends ignore it.
668+
- `chat.send` accepts one-turn `fastMode: "auto"` to use fast mode for model calls started before the auto cutoff, then start later retry, fallback, tool-result, or continuation calls without fast mode. The cutoff defaults to 60 seconds (`DEFAULT_FAST_MODE_AUTO_ON_SECONDS`) and can be configured per model with `agents.defaults.models["<provider>/<model>"].params.fastAutoOnSeconds`. A `chat.send` caller can pass one-turn `fastAutoOnSeconds` to override the cutoff for that request. Pass `queueMode` (`steer`, `followup`, `collect`, or `interrupt`) to override the stored queue mode for this request only; explicit Control UI steer actions use `queueMode: "steer"`. Interrupt mode captures and aborts the session's current admitted turn, waits for that exact owner to settle, then starts the new turn; an idle session starts normally. A steer send targets the selected session's current state: the Gateway atomically injects the message into that session's direct active run, or starts a new turn when the session is idle. Activity in descendant subagent sessions never makes the selected session busy for this decision. `expectedLeafEntryId` is an independent transcript-branch compare-and-swap for non-steer interactive sends: pass the displayed branch leaf (or deliberate `null` for an authoritative empty transcript) and the send rejects with `details.reason: "active-leaf-changed"` if another client switched transcript branches first; steer sends ignore it.
669669

670670
</Accordion>
671671

‎src/auto-reply/reply/get-reply-run-admission.ts‎

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import type { SessionEntry } from "../../config/sessions/types.js";
1616
import { logVerbose } from "../../globals.js";
1717
import { isFastTestRuntimeEnv } from "../../infra/env.js";
1818
import { clearCommandLane, getQueueSize } from "../../process/command-queue.js";
19+
import { interruptSessionWorkAdmissions } from "../../sessions/session-lifecycle-admission.js";
1920
import { resolveCommandTurnTargetSessionKey } from "../command-turn-context.js";
2021
import {
2122
formatThinkingLevels,
@@ -40,8 +41,9 @@ import { resolveQueueSettings } from "./queue/settings-runtime.js";
4041
import { getExistingFollowupQueue } from "./queue/state.js";
4142
import {
4243
REPLY_RUN_IDLE_SETTLE_TIMEOUT_MS,
43-
abortReplyRunBySessionId,
44+
interruptReplyRunTarget,
4445
isReplyRunActiveForSessionId,
46+
replyRunRegistry,
4547
resolveActiveReplyRunThreadId,
4648
resolveActiveReplyRunSessionId,
4749
waitForReplyRunEndBySessionId,
@@ -392,10 +394,7 @@ export async function prepareReplyRunAdmission(context: PreparedReplyRunContext)
392394
(laneSize > 0 || activeSessionIdForInterrupt)
393395
) {
394396
const cleared = clearCommandLane(sessionLaneKey);
395-
const aborted = embeddedAgentRuntime?.abortEmbeddedAgentRun(
396-
activeSessionIdForInterrupt ?? preparedSessionState.sessionId,
397-
);
398-
logVerbose(`Interrupting ${sessionLaneKey} (cleared ${cleared}, aborted=${aborted})`);
397+
logVerbose(`Cleared ${cleared} queued command(s) before interrupting ${sessionLaneKey}`);
399398
}
400399
const agentHarnessPolicy = useFastReplyRuntime
401400
? undefined
@@ -520,6 +519,10 @@ export async function prepareReplyRunAdmission(context: PreparedReplyRunContext)
520519
}
521520
}
522521
const { activeSessionId, isActive } = resolveQueueBusyState();
522+
const activeRunInterruptTarget =
523+
activeRunQueueMode === "interrupt" && sessionKey
524+
? replyRunRegistry.resolveCurrentInterruptTarget(sessionKey)
525+
: undefined;
523526
const pendingQueue = getExistingFollowupQueue(queueKey);
524527
const queueAdmissionState = !pendingQueue
525528
? "empty"
@@ -559,11 +562,22 @@ export async function prepareReplyRunAdmission(context: PreparedReplyRunContext)
559562
queueMode: activeRunQueueMode,
560563
sessionKey,
561564
sessionId: sessionIdFinal,
562-
abortActiveRun: (activeRunSessionId) => {
563-
const embeddedAborted =
564-
embeddedAgentRuntime?.abortEmbeddedAgentRun(activeRunSessionId) ?? false;
565-
const replyOperationAborted = abortReplyRunBySessionId(activeRunSessionId);
566-
return embeddedAborted || replyOperationAborted;
565+
interruptActiveRun: async () => {
566+
if (activeRunInterruptTarget) {
567+
return (
568+
await interruptReplyRunTarget(
569+
activeRunInterruptTarget,
570+
REPLY_RUN_IDLE_SETTLE_TIMEOUT_MS,
571+
)
572+
).settled;
573+
}
574+
return storePath
575+
? await interruptSessionWorkAdmissions({
576+
scope: storePath,
577+
identities: [sessionKey, activeSessionId, preparedSessionState.sessionId],
578+
timeoutMs: REPLY_RUN_IDLE_SETTLE_TIMEOUT_MS,
579+
})
580+
: false;
567581
},
568582
waitForActiveRunEnd: (activeRunSessionId) =>
569583
isReplyRunActiveForSessionId(activeRunSessionId)

‎src/auto-reply/reply/get-reply-run-queue.test.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ describe("resolvePreparedReplyQueueState", () => {
1616
queueMode: "followup",
1717
sessionKey: "session-key",
1818
sessionId: "session-1",
19-
abortActiveRun: vi.fn(),
19+
interruptActiveRun: vi.fn(),
2020
waitForActiveRunEnd: vi.fn(),
2121
refreshPreparedState: vi.fn(),
2222
resolveBusyState,
@@ -30,8 +30,10 @@ describe("resolvePreparedReplyQueueState", () => {
3030
});
3131

3232
it("aborts and waits for interrupt mode before continuing", async () => {
33-
const abortActiveRun = vi.fn(() => true);
34-
const waitForActiveRunEnd = vi.fn(async () => undefined);
33+
const interruptActiveRun = vi.fn(async () => true);
34+
const waitForActiveRunEnd = vi.fn(async () => {
35+
throw new Error("interrupt mode must use session-work admission settling");
36+
});
3537
const refreshPreparedState = vi.fn(async () => undefined);
3638
const resolveBusyState = vi.fn(() => ({
3739
activeSessionId: undefined,
@@ -45,14 +47,14 @@ describe("resolvePreparedReplyQueueState", () => {
4547
queueMode: "interrupt",
4648
sessionKey: "session-key",
4749
sessionId: "session-1",
48-
abortActiveRun,
50+
interruptActiveRun,
4951
waitForActiveRunEnd,
5052
refreshPreparedState,
5153
resolveBusyState,
5254
});
5355

54-
expect(abortActiveRun).toHaveBeenCalledWith("session-active");
55-
expect(waitForActiveRunEnd).toHaveBeenCalledWith("session-active");
56+
expect(interruptActiveRun).toHaveBeenCalledOnce();
57+
expect(waitForActiveRunEnd).not.toHaveBeenCalled();
5658
expect(refreshPreparedState).toHaveBeenCalledOnce();
5759
expect(result).toEqual({
5860
kind: "continue",
@@ -67,7 +69,7 @@ describe("resolvePreparedReplyQueueState", () => {
6769
queueMode: "interrupt",
6870
sessionKey: "session-key",
6971
sessionId: "session-1",
70-
abortActiveRun: vi.fn(() => true),
72+
interruptActiveRun: vi.fn(async () => true),
7173
waitForActiveRunEnd: vi.fn(async () => undefined),
7274
refreshPreparedState: vi.fn(async () => undefined),
7375
resolveBusyState: () => ({

‎src/auto-reply/reply/get-reply-run-queue.ts‎

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
/** Active-run queue admission for prepared reply turns. */
2-
import { logVerbose } from "../../globals.js";
32
import type { ReplyPayload } from "../types.js";
43
import type { ActiveRunQueueAction } from "./queue-policy.js";
54
import type { QueueSettings } from "./queue.js";
@@ -20,7 +19,7 @@ export async function resolvePreparedReplyQueueState(params: {
2019
queueMode: QueueSettings["mode"];
2120
sessionKey: string | undefined;
2221
sessionId: string;
23-
abortActiveRun: (sessionId: string) => boolean;
22+
interruptActiveRun: () => Promise<boolean>;
2423
waitForActiveRunEnd: (sessionId: string) => Promise<unknown>;
2524
refreshPreparedState: () => Promise<void>;
2625
resolveBusyState: () => ReplyRunQueueBusyState;
@@ -32,14 +31,10 @@ export async function resolvePreparedReplyQueueState(params: {
3231
}
3332

3433
if (params.queueMode === "interrupt") {
35-
// Interrupt mode asks the active run to abort before waiting for teardown.
36-
const aborted = params.abortActiveRun(params.activeSessionId);
37-
logVerbose(
38-
`Interrupting active run for ${params.sessionKey ?? params.sessionId} (aborted=${aborted})`,
39-
);
34+
await params.interruptActiveRun();
35+
} else {
36+
await params.waitForActiveRunEnd(params.activeSessionId);
4037
}
41-
42-
await params.waitForActiveRunEnd(params.activeSessionId);
4338
await params.refreshPreparedState();
4439
const refreshedBusyState = params.resolveBusyState();
4540
if (refreshedBusyState.isActive) {

‎src/auto-reply/reply/get-reply-run.media-only.test.ts‎

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
resetSystemEventsForTest,
1010
} from "../../infra/system-events.js";
1111
import { MESSAGE_TOOL_ONLY_DELIVERY_HINT } from "../../plugin-sdk/message-tool-delivery-hints.js";
12+
import { beginSessionWorkAdmission } from "../../sessions/session-lifecycle-admission.js";
1213
import { normalizeSessionDeliveryState } from "../../utils/delivery-context.shared.js";
1314
import { hasControlCommand } from "../command-detection.js";
1415
import { runReplyAgent } from "./agent-runner.runtime.js";
@@ -2098,9 +2099,10 @@ describe("runPreparedReply media-only handling", () => {
20982099
expect(result).toEqual({ text: "ok" });
20992100
expect(vi.mocked(runReplyAgent)).toHaveBeenCalledOnce();
21002101
});
2101-
it("interrupts embedded-only active runs even without a reply operation", async () => {
2102+
it("routes a channel-configured interrupt through session-work admission", async () => {
21022103
const queueSettings = await import("./queue/settings-runtime.js");
21032104
const embeddedAgentRuntime = await import("../../agents/embedded-agent.runtime.js");
2105+
const storePath = "/tmp/channel-interrupt-sessions.json";
21042106
let embeddedRunActive = true;
21052107
vi.mocked(queueSettings.resolveQueueSettings).mockReturnValueOnce({ mode: "interrupt" });
21062108
vi.mocked(embeddedAgentRuntime.resolveActiveEmbeddedRunSessionId).mockImplementation(() =>
@@ -2109,39 +2111,36 @@ describe("runPreparedReply media-only handling", () => {
21092111
vi.mocked(embeddedAgentRuntime.isEmbeddedAgentRunActive).mockImplementation(
21102112
() => embeddedRunActive,
21112113
);
2112-
vi.mocked(embeddedAgentRuntime.abortEmbeddedAgentRun).mockReturnValue(true);
2113-
vi.mocked(embeddedAgentRuntime.waitForEmbeddedAgentRunEnd).mockImplementation(async () => {
2114-
embeddedRunActive = false;
2115-
return true;
2114+
let releaseActiveAdmission = () => {};
2115+
const activeAdmission = await beginSessionWorkAdmission({
2116+
scope: storePath,
2117+
identities: ["session-key", "session-embedded-only"],
2118+
assertAllowed: () => {},
2119+
onInterrupt: () => {
2120+
releaseActiveAdmission();
2121+
},
21162122
});
2123+
releaseActiveAdmission = () => {
2124+
embeddedRunActive = false;
2125+
activeAdmission.release();
2126+
};
21172127

21182128
try {
21192129
await expect(
21202130
runPrepared({
21212131
isNewSession: false,
21222132
sessionId: "session-embedded-only",
2133+
storePath,
21232134
}),
21242135
).resolves.toEqual({ text: "ok" });
21252136
} finally {
2137+
activeAdmission.release();
21262138
vi.mocked(embeddedAgentRuntime.resolveActiveEmbeddedRunSessionId).mockReturnValue(undefined);
21272139
vi.mocked(embeddedAgentRuntime.isEmbeddedAgentRunActive).mockReturnValue(false);
2128-
vi.mocked(embeddedAgentRuntime.abortEmbeddedAgentRun).mockReturnValue(false);
2129-
vi.mocked(embeddedAgentRuntime.waitForEmbeddedAgentRunEnd).mockResolvedValue(true);
21302140
}
21312141

2132-
expect(embeddedAgentRuntime.abortEmbeddedAgentRun).toHaveBeenCalledTimes(2);
2133-
expect(embeddedAgentRuntime.abortEmbeddedAgentRun).toHaveBeenNthCalledWith(
2134-
1,
2135-
"session-embedded-only",
2136-
);
2137-
expect(embeddedAgentRuntime.abortEmbeddedAgentRun).toHaveBeenNthCalledWith(
2138-
2,
2139-
"session-embedded-only",
2140-
);
2141-
expect(embeddedAgentRuntime.waitForEmbeddedAgentRunEnd).toHaveBeenCalledOnce();
2142-
expect(embeddedAgentRuntime.waitForEmbeddedAgentRunEnd).toHaveBeenCalledWith(
2143-
"session-embedded-only",
2144-
);
2142+
expect(embeddedAgentRuntime.abortEmbeddedAgentRun).not.toHaveBeenCalled();
2143+
expect(embeddedAgentRuntime.waitForEmbeddedAgentRunEnd).not.toHaveBeenCalled();
21452144
expect(vi.mocked(runReplyAgent)).toHaveBeenCalledOnce();
21462145
});
21472146
it("interrupts an embedded-only heartbeat before running a visible Telegram turn", async () => {
@@ -2365,12 +2364,15 @@ describe("runPreparedReply media-only handling", () => {
23652364
vi.mocked(embeddedAgentRuntime.resolveActiveEmbeddedRunSessionId).mockReturnValue(
23662365
"session-active",
23672366
);
2368-
vi.mocked(embeddedAgentRuntime.abortEmbeddedAgentRun).mockReturnValue(true);
23692367
const activeOperation = createReplyOperation({
23702368
sessionId: "session-active",
23712369
sessionKey: "session-key",
23722370
resetTriggered: false,
23732371
});
2372+
activeOperation.attachBackend({
2373+
kind: "embedded",
2374+
cancel: () => activeOperation.complete(),
2375+
});
23742376

23752377
try {
23762378
const result = await runPrepared({
@@ -2381,7 +2383,7 @@ describe("runPreparedReply media-only handling", () => {
23812383

23822384
expect(result).toEqual({ text: "ok" });
23832385
expect(commandQueue.clearCommandLane).toHaveBeenCalledWith("session:session-key");
2384-
expect(embeddedAgentRuntime.abortEmbeddedAgentRun).toHaveBeenCalledWith("session-active");
2386+
expect(embeddedAgentRuntime.abortEmbeddedAgentRun).not.toHaveBeenCalled();
23852387
expect(activeOperation.result).toEqual({
23862388
kind: "aborted",
23872389
code: "aborted_by_user",

0 commit comments

Comments
 (0)