From aff1d65467c99fcfbb84b824570d29ff6e16c9dc Mon Sep 17 00:00:00 2001 From: Roy Sun Date: Wed, 25 Nov 2026 05:16:56 +0900 Subject: [PATCH] fix(server): accept T3 MCP calls while a wake continuation run is queued --- apps/server/src/mcp/McpToolAccess.test.ts | 82 ++++++- .../OrchestratorMcpService.activity.test.ts | 51 +++- apps/server/src/mcp/OrchestratorMcpService.ts | 21 +- apps/server/src/mcp/threadAccess.test.ts | 230 +++++++++++++++++- apps/server/src/mcp/threadAccess.ts | 91 ++++++- 5 files changed, 447 insertions(+), 28 deletions(-) diff --git a/apps/server/src/mcp/McpToolAccess.test.ts b/apps/server/src/mcp/McpToolAccess.test.ts index 6cfd86bd3d836..96b99eaec1d1e 100644 --- a/apps/server/src/mcp/McpToolAccess.test.ts +++ b/apps/server/src/mcp/McpToolAccess.test.ts @@ -1,10 +1,16 @@ import { expect, it } from "@effect/vitest"; import { EnvironmentId, + MessageId, + NodeId, + type OrchestrationV2Run, OrchestratorMcpEnvironmentTarget, OrchestratorMcpFailure, ProviderInstanceId, ProviderInteractionMode, + ProviderThreadId, + RunAttemptId, + RunId, RuntimeMode, ThreadId, } from "@t3tools/contracts"; @@ -23,7 +29,7 @@ import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.t import * as McpHttpServer from "./McpHttpServer.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; -import { liveThreadShell } from "./McpToolAccess.testkit.ts"; +import { idleThreadProjection, liveThreadShell } from "./McpToolAccess.testkit.ts"; const supervisedThreadId = ThreadId.make("thread:supervised"); const planThreadId = ThreadId.make("thread:plan"); @@ -33,6 +39,8 @@ const backgroundThreadId = ThreadId.make("thread:background"); const oldProviderThreadId = ThreadId.make("thread:old-provider-background"); const archivedThreadId = ThreadId.make("thread:archived-background"); const unknownOwnerThreadId = ThreadId.make("thread:unknown-background-owner"); +const queuedWakeThreadId = ThreadId.make("thread:queued-wake"); +const foreignQueuedThreadId = ThreadId.make("thread:foreign-queued"); const backgroundShell = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => ({ ...liveThreadShell(threadId, { activeRunId: null }), @@ -41,6 +49,63 @@ const backgroundShell = (threadId: ThreadId, providerInstanceId: ProviderInstanc ], }); +const queuedShell = (threadId: ThreadId, runId: RunId) => { + const base = liveThreadShell(threadId, { activeRunId: null }); + return { + ...base, + status: "queued" as const, + latestRunId: runId, + latestRunRequestedAt: base.updatedAt, + latestRunCompletedAt: null, + }; +}; + +const queuedRun = ( + threadId: ThreadId, + id: RunId, + providerInstanceId: ProviderInstanceId, +): OrchestrationV2Run => ({ + id, + threadId, + ordinal: 1, + providerInstanceId, + modelSelection: { instanceId: providerInstanceId, model: "gpt-5" }, + providerThreadId: ProviderThreadId.make("provider-thread:queued"), + userMessageId: MessageId.make("message:queued"), + rootNodeId: NodeId.make("node:queued"), + activeAttemptId: RunAttemptId.make("attempt:queued"), + status: "queued", + queuePosition: 1, + requestedAt: liveThreadShell(threadId).updatedAt, + startedAt: null, + completedAt: null, + checkpointId: null, + contextHandoffId: null, +}); + +const queuedRuns = new Map>([ + [ + queuedWakeThreadId, + [ + queuedRun( + queuedWakeThreadId, + RunId.make("run:queued-wake"), + ProviderInstanceId.make("codex"), + ), + ], + ], + [ + foreignQueuedThreadId, + [ + queuedRun( + foreignQueuedThreadId, + RunId.make("run:foreign-queued"), + ProviderInstanceId.make("claude"), + ), + ], + ], +]); + const shells = new Map([ [supervisedThreadId, liveThreadShell(supervisedThreadId, { runtimeMode: "approval-required" })], [ @@ -65,6 +130,8 @@ const shells = new Map([ pendingBackgroundTasks: [{ taskId: "task:unknown", kind: "subagent" as const }], }, ], + [queuedWakeThreadId, queuedShell(queuedWakeThreadId, RunId.make("run:queued-wake"))], + [foreignQueuedThreadId, queuedShell(foreignQueuedThreadId, RunId.make("run:foreign-queued"))], ]); const threadCaller = (threadId: ThreadId): McpInvocationContext.McpInvocationScope => ({ @@ -233,6 +300,8 @@ const background = threadCaller(backgroundThreadId); const oldProviderBackground = threadCaller(oldProviderThreadId); const archivedBackground = threadCaller(archivedThreadId); const unknownOwnerBackground = threadCaller(unknownOwnerThreadId); +const queuedWake = threadCaller(queuedWakeThreadId); +const foreignQueued = threadCaller(foreignQueuedThreadId); const mismatchedProvider = { ...background, thread: { ...background.thread!, providerInstanceId: ProviderInstanceId.make("claude") }, @@ -269,11 +338,15 @@ it.effect.each([ ["acts_as_caller", mismatchedProvider, {}, "parent_not_active"], ["acts_as_caller", archivedBackground, {}, "parent_not_active"], ["acts_as_caller", unknownOwnerBackground, {}, "parent_not_active"], + ["acts_as_caller", queuedWake, {}, "ran"], + ["acts_as_caller", foreignQueued, {}, "parent_not_active"], ["writes", supervised, {}, "ran"], ["writes", ended, {}, "parent_not_active"], ["writes", background, {}, "ran"], ["writes", oldProviderBackground, {}, "parent_not_active"], + ["writes", queuedWake, {}, "ran"], + ["writes", foreignQueued, {}, "parent_not_active"], ["writes", supervisedClient, {}, "ran"], ["writes", previewOnly, {}, "capability_denied"], ["writes_environment", previewOnly, {}, "capability_denied"], @@ -328,6 +401,13 @@ it.effect.each([ probeServer( Layer.mock(ThreadManagement.ThreadManagementService)({ getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null), + getProjectThreadRecords: ({ threadId }) => { + const shell = shells.get(threadId) ?? liveThreadShell(threadId, { activeRunId: null }); + return Effect.succeed({ + ...idleThreadProjection(shell), + runs: queuedRuns.get(threadId) ?? [], + }); + }, }), ), ), diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index 7c4a0f00eccfe..e66c93057eeda 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -1064,12 +1064,14 @@ it("readThread and sendToThread reach threads in other projects", async () => { getProjectThreadRecords: (input) => input.threadId === foreignThreadId && input.projectId === foreignProjectId ? Effect.succeed(foreignProjection(input.threadId)) - : Effect.fail( - new ThreadManagementService.ThreadManagementThreadNotFoundError({ - projectId: input.projectId, - threadId: input.threadId, - }), - ), + : input.threadId === parentThreadId && input.projectId === parentShell?.projectId + ? Effect.succeed(parentProjection) + : Effect.fail( + new ThreadManagementService.ThreadManagementThreadNotFoundError({ + projectId: input.projectId, + threadId: input.threadId, + }), + ), sendToThread: () => Effect.succeed({ run: { id: "run-foreign", status: "queued" }, @@ -1214,6 +1216,43 @@ it("readThread and sendToThread reach threads in other projects", async () => { .sendToThread(makeScope(), { threadId: foreignThreadId, message: "after stop" }) .pipe(Effect.flip); expect(stopped.code).toBe("parent_not_active"); + + const queuedRunId = RunId.make("run-parent-queued-wake"); + parentRuns = [ + { + ...makeRun({ id: queuedRunId, ordinal: 2, status: "queued" }), + rootNodeId: taskId, + }, + ]; + parentShell = { + ...liveThreadShell(parentThreadId, { activeRunId: null }), + status: "queued", + latestRunId: queuedRunId, + latestRunRequestedAt: now, + latestRunCompletedAt: null, + }; + const queuedSent = yield* service.sendToThread(makeScope(), { + threadId: foreignThreadId, + message: "queued wake", + }); + expect(queuedSent.threadId).toBe(foreignThreadId); + // Queued wakes do not satisfy backgroundSubagentRun when no background subagent is pending. + const queuedDelegate = yield* service + .delegateTask(makeScope(), { task: "requires an active run" }) + .pipe(Effect.flip); + expect(queuedDelegate.code).toBe("parent_not_active"); + + parentRuns = [ + { + ...makeRun({ id: queuedRunId, ordinal: 2, status: "queued" }), + providerInstanceId: customCodexInstanceId, + rootNodeId: taskId, + }, + ]; + const foreignQueuedSent = yield* service + .sendToThread(makeScope(), { threadId: foreignThreadId, message: "foreign queued" }) + .pipe(Effect.flip); + expect(foreignQueuedSent.code).toBe("parent_not_active"); }).pipe(Effect.provide(layer), Effect.runPromise); }); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index c0338d4dbc83a..722ddac61250c 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -68,7 +68,10 @@ import { SECRET_REQUEST_UNSAVED_NOTE, } from "@t3tools/contracts"; import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model"; -import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import { + backgroundWorkHoldsCompletion, + hasPendingBackgroundSubagent, +} from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; @@ -138,7 +141,7 @@ import { runtimeModeRank, taskPrompt, } from "./delegatedTaskModes.ts"; -import { assertTargetWithinLimits, isLiveCallerShell, threadNotFound } from "./threadAccess.ts"; +import { assertLiveCallerShell, assertTargetWithinLimits, threadNotFound } from "./threadAccess.ts"; import { WITHHELD, withoutWebhookUrlToken } from "../scheduledTasks/webhookUrlToken.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as PeerForwarding from "../peer/PeerForwarding.ts"; @@ -1529,9 +1532,7 @@ const make = Effect.gen(function* () { return threadManagement.getThreadShell(parent.thread.id).pipe( Effect.mapError(threadManagementFailure), Effect.flatMap((shell) => - isLiveCallerShell(shell, scope.thread?.providerInstanceId) - ? Effect.void - : Effect.fail(notActive), + assertLiveCallerShell(threadManagement, shell, scope.thread?.providerInstanceId), ), ); } @@ -1550,9 +1551,15 @@ const make = Effect.gen(function* () { .getThreadShell(threadId) .pipe(Effect.mapError(threadManagementFailure)); if ( - shell?.activeRunId !== null || + shell === null || + shell.archivedAt !== null || + shell.activeRunId !== null || shell.latestRunId === null || - !isLiveCallerShell(shell, scope.thread?.providerInstanceId) + shell.providerInstanceId !== scope.thread?.providerInstanceId || + !hasPendingBackgroundSubagent( + shell.pendingBackgroundTasks, + scope.thread?.providerInstanceId, + ) ) { return undefined; } diff --git a/apps/server/src/mcp/threadAccess.test.ts b/apps/server/src/mcp/threadAccess.test.ts index 914b42426540b..bf94892f3ac21 100644 --- a/apps/server/src/mcp/threadAccess.test.ts +++ b/apps/server/src/mcp/threadAccess.test.ts @@ -1,17 +1,30 @@ import { expect, it } from "@effect/vitest"; import { EnvironmentId, + MessageId, + NodeId, + type OrchestrationV2Run, type OrchestrationV2ThreadShell, ProviderInstanceId, + ProviderThreadId, + RunAttemptId, + RunId, ThreadId, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import { threadShellFromProjection } from "../orchestration-v2/ProjectionStore.ts"; import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; -import { liveThreadShell } from "./McpToolAccess.testkit.ts"; -import { assertTargetWithinLimits, readThread } from "./threadAccess.ts"; +import { idleThreadProjection, liveThreadShell } from "./McpToolAccess.testkit.ts"; +import { + assertLiveCaller, + assertTargetWithinLimits, + isLiveCallerShell, + readThread, +} from "./threadAccess.ts"; const bareId = ThreadId.make("5d0b4a3e-8c1f-4a52-9d37-2f6c7e1b9a04"); const claudeCode: McpInvocationContext.McpClientCaller = { @@ -138,3 +151,216 @@ it.effect("identifies the target and effective caller ceiling when a thread writ } }), ); + +const claudeInstanceId = ProviderInstanceId.make("claudeAgent"); +const codexInstanceId = ProviderInstanceId.make("codex"); +const requestedAt = DateTime.makeUnsafe("2026-11-08T12:32:48.852Z"); +const completedAt = DateTime.makeUnsafe("2026-11-08T12:32:31.797Z"); + +const makeRun = ( + threadId: ThreadId, + overrides: Partial = {}, +): OrchestrationV2Run => ({ + id: RunId.make("run:wake"), + threadId, + ordinal: 1, + providerInstanceId: claudeInstanceId, + modelSelection: { instanceId: claudeInstanceId, model: "claude-sonnet-4-6" }, + providerThreadId: ProviderThreadId.make("provider-thread:1"), + userMessageId: MessageId.make("message:1"), + rootNodeId: NodeId.make("node:1"), + activeAttemptId: RunAttemptId.make("attempt:1"), + status: "queued", + queuePosition: 1, + requestedAt, + startedAt: null, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + ...overrides, +}); + +it("isLiveCallerShell accepts an unheld queued continuation for the same provider and refuses settled, held, or foreign shells", () => { + const threadId = ThreadId.make("thread:wake-shell"); + const baseShell: OrchestrationV2ThreadShell = { + ...liveThreadShell(threadId, { activeRunId: null }), + providerInstanceId: claudeInstanceId, + modelSelection: { instanceId: claudeInstanceId, model: "claude-sonnet-4-6" }, + }; + const settledRun = makeRun(threadId, { + id: RunId.make("run:settled"), + ordinal: 1, + status: "completed", + queuePosition: null, + startedAt: completedAt, + completedAt, + }); + const queuedWake = makeRun(threadId, { + id: RunId.make("run:queued-wake"), + ordinal: 2, + status: "queued", + }); + const heldWake = makeRun(threadId, { + id: RunId.make("run:held-wake"), + ordinal: 2, + status: "queued", + queueHeld: true, + }); + + const queuedShell = threadShellFromProjection({ + ...idleThreadProjection(baseShell), + runs: [settledRun, queuedWake], + }); + const settledShell = threadShellFromProjection({ + ...idleThreadProjection(baseShell), + runs: [settledRun], + }); + const heldShell = threadShellFromProjection({ + ...idleThreadProjection(baseShell), + runs: [settledRun, heldWake], + }); + const idleShell = threadShellFromProjection(idleThreadProjection(baseShell)); + + expect(isLiveCallerShell(queuedShell, claudeInstanceId)).toBe(true); + expect(isLiveCallerShell(queuedShell, codexInstanceId)).toBe(false); + expect(isLiveCallerShell({ ...queuedShell, archivedAt: requestedAt }, claudeInstanceId)).toBe( + false, + ); + expect(isLiveCallerShell(settledShell, claudeInstanceId)).toBe(false); + expect(isLiveCallerShell(heldShell, claudeInstanceId)).toBe(false); + expect(isLiveCallerShell(idleShell, claudeInstanceId)).toBe(false); +}); + +it.effect( + "assertLiveCaller verifies queued run ownership so another provider's queued run cannot revive a stale caller", + () => + Effect.gen(function* () { + const threadId = ThreadId.make("thread:queued-owner"); + const baseShell: OrchestrationV2ThreadShell = { + ...liveThreadShell(threadId, { activeRunId: null }), + providerInstanceId: claudeInstanceId, + modelSelection: { instanceId: claudeInstanceId, model: "claude-sonnet-4-6" }, + }; + const queuedRunId = RunId.make("run:queued"); + const scope: McpInvocationContext.McpInvocationScope = { + ...client, + client: undefined, + thread: { + threadId, + providerSessionId: "provider:claude", + providerInstanceId: claudeInstanceId, + }, + }; + const checkWithRun = (run: OrchestrationV2Run) => { + const shell = threadShellFromProjection({ + ...idleThreadProjection(baseShell), + runs: [run], + }); + const threads = ThreadManagement.ThreadManagementService.of({ + getProjectThreadRecords: () => + Effect.succeed({ + ...idleThreadProjection(baseShell), + runs: [run], + }), + } as unknown as ThreadManagement.ThreadManagementService["Service"]); + return assertLiveCaller({ + caller: shell, + scope, + threads, + limits: { runtimeMode: shell.runtimeMode, interactionMode: shell.interactionMode }, + }); + }; + + // Unheld queued wake run for the same provider passes. + yield* checkWithRun(makeRun(threadId, { id: queuedRunId, status: "queued" })); + + // A run that transitioned from queued to running before the run check still passes. + const shellStillQueued: OrchestrationV2ThreadShell = { + ...baseShell, + status: "queued", + latestRunId: queuedRunId, + latestRunRequestedAt: requestedAt, + latestRunCompletedAt: null, + }; + yield* assertLiveCaller({ + caller: shellStillQueued, + scope, + threads: ThreadManagement.ThreadManagementService.of({ + getProjectThreadRecords: () => + Effect.succeed({ + ...idleThreadProjection(baseShell), + runs: [ + makeRun(threadId, { id: queuedRunId, status: "running", startedAt: requestedAt }), + ], + }), + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + limits: { + runtimeMode: shellStillQueued.runtimeMode, + interactionMode: shellStillQueued.interactionMode, + }, + }); + + // Another provider queued a run behind Claude's queued wake run: Claude still passes. + const claudeQueued = makeRun(threadId, { + id: RunId.make("run:claude-wake"), + ordinal: 2, + status: "queued", + }); + const codexQueuedBehind = makeRun(threadId, { + id: RunId.make("run:codex-followup"), + ordinal: 3, + status: "queued", + providerInstanceId: codexInstanceId, + modelSelection: { instanceId: codexInstanceId, model: "gpt-5" }, + }); + const multiQueuedShell = threadShellFromProjection({ + ...idleThreadProjection(baseShell), + runs: [claudeQueued, codexQueuedBehind], + }); + expect(multiQueuedShell.latestRunId).toBe(codexQueuedBehind.id); + yield* assertLiveCaller({ + caller: multiQueuedShell, + scope, + threads: ThreadManagement.ThreadManagementService.of({ + getProjectThreadRecords: () => + Effect.succeed({ + ...idleThreadProjection(baseShell), + runs: [claudeQueued, codexQueuedBehind], + }), + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + limits: { + runtimeMode: multiQueuedShell.runtimeMode, + interactionMode: multiQueuedShell.interactionMode, + }, + }); + + // Another provider queued a run while thread.providerInstanceId still names Claude. + const foreignQueuedError = yield* checkWithRun( + makeRun(threadId, { + id: queuedRunId, + status: "queued", + providerInstanceId: codexInstanceId, + modelSelection: { instanceId: codexInstanceId, model: "gpt-5" }, + }), + ).pipe(Effect.flip); + expect(foreignQueuedError.code).toBe("parent_not_active"); + + // A held queued run cannot revive a stale caller even if a stale shell reported status queued. + const heldError = yield* assertLiveCaller({ + caller: shellStillQueued, + scope, + threads: ThreadManagement.ThreadManagementService.of({ + getProjectThreadRecords: () => + Effect.succeed({ + ...idleThreadProjection(baseShell), + runs: [makeRun(threadId, { id: queuedRunId, status: "queued", queueHeld: true })], + }), + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + limits: { + runtimeMode: shellStillQueued.runtimeMode, + interactionMode: shellStillQueued.interactionMode, + }, + }).pipe(Effect.flip); + expect(heldError.code).toBe("parent_not_active"); + }), +); diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index d21495f0ff7c7..5fd86eabaa408 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -188,11 +188,33 @@ export const assertTargetWithinLimits = ( ), ); -/** Background subagents retain credentials until provider exit; archived threads and other instances cannot act. */ +const hasPendingQueuedRun = ( + shell: Pick< + OrchestrationV2ThreadShell, + "status" | "latestRunId" | "latestRunRequestedAt" | "latestRunCompletedAt" + >, +) => + shell.status === "queued" && + shell.latestRunId !== null && + shell.latestRunRequestedAt != null && + shell.latestRunCompletedAt === null; + +/** + * Shell-level liveness check for archived state, provider instance, active runs, background + * subagents, and unheld queued runs. A queued provider switch leaves `shell.providerInstanceId` + * on the previous owner until it starts, so callers enforcing access must use `assertLiveCallerShell`. + */ export const isLiveCallerShell = ( shell: Pick< OrchestrationV2ThreadShell, - "archivedAt" | "activeRunId" | "providerInstanceId" | "pendingBackgroundTasks" + | "archivedAt" + | "activeRunId" + | "providerInstanceId" + | "pendingBackgroundTasks" + | "status" + | "latestRunId" + | "latestRunRequestedAt" + | "latestRunCompletedAt" > | null, providerInstanceId: ProviderInstanceId | undefined, ) => @@ -200,19 +222,64 @@ export const isLiveCallerShell = ( shell.archivedAt === null && shell.providerInstanceId === providerInstanceId && (shell.activeRunId !== null || + hasPendingQueuedRun(shell) || hasPendingBackgroundSubagent(shell.pendingBackgroundTasks, providerInstanceId)); -/** Thread callers need a live run or its background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */ -export function assertLiveCaller({ caller, scope }: Caller) { +/** + * Verifies a thread shell owns a live run, a background subagent, or an unheld queued run + * for the calling provider. A queued provider switch leaves `shell.providerInstanceId` on + * the previous owner until the run starts, so the queued path checks the run records themselves. + */ +export const assertLiveCallerShell = ( + threads: Pick, + shell: OrchestrationV2ThreadShell | null, + providerInstanceId: ProviderInstanceId | undefined, +): Effect.Effect => { + const notActive = new OrchestratorMcpFailure({ + code: "parent_not_active", + message: "The calling provider no longer owns an active thread run.", + }); + if ( + shell === null || + shell.archivedAt !== null || + shell.providerInstanceId !== providerInstanceId + ) { + return Effect.fail(notActive); + } + if ( + shell.activeRunId !== null || + hasPendingBackgroundSubagent(shell.pendingBackgroundTasks, providerInstanceId) + ) { + return Effect.void; + } + if (!hasPendingQueuedRun(shell)) { + return Effect.fail(notActive); + } + return threads + .getProjectThreadRecords({ projectId: shell.projectId, threadId: shell.id }, ["runs"], { + runStatuses: ["queued", ...ThreadManagement.ACTIVE_RUN_STATUSES], + }) + .pipe( + Effect.mapError((error) => + error._tag === "ThreadManagementThreadNotFoundError" ? notActive : unavailable(), + ), + Effect.flatMap(({ runs }) => + runs.some( + (run) => + run.providerInstanceId === providerInstanceId && + (ThreadManagement.isActiveRun(run) || + (run.status === "queued" && run.queueHeld !== true)), + ) + ? Effect.void + : Effect.fail(notActive), + ), + ); +}; + +/** Thread callers need a live run, an unheld queued run, or a background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */ +export function assertLiveCaller({ caller, scope, threads }: Caller) { if (caller === undefined) return Effect.void; - return isLiveCallerShell(caller, scope.thread?.providerInstanceId) - ? Effect.void - : Effect.fail( - new OrchestratorMcpFailure({ - code: "parent_not_active", - message: "The calling provider no longer owns an active thread run.", - }), - ); + return assertLiveCallerShell(threads, caller, scope.thread?.providerInstanceId); } export const assertFullAccess = (context: Caller, message: string) =>