TypeScript
feat(server): delegate_task to a linked environment (#16719)
Julius Marminge594f1ce2eb3f
diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.tsindex 9a59367a954..ec0f6a14558 100644--- a/apps/mobile/src/features/home/useThreadListActions.test.ts+++ b/apps/mobile/src/features/home/useThreadListActions.test.ts@@ -114,7 +114,10 @@ vi.mock("../../state/thread-order", () => ({},}));vi.mock("../../state/threads", () => ({- environmentThreadShells: { threadShellsAtom: "thread-shells" },+ environmentThreadShells: {+ threadShellsAtom: "thread-shells",+ navigationThreadShellsAtom: "thread-shells",+ },threadEnvironment: Object.fromEntries(["archive",diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.tsindex ddbbf9ff343..3ba684bdff1 100644--- a/apps/mobile/src/features/home/useThreadListActions.ts+++ b/apps/mobile/src/features/home/useThreadListActions.ts@@ -611,7 +611,7 @@ export function useThreadListActions(): {const moveThread = async (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {if (!checkThreadOperationPermission(thread, "Could not move thread")) return false;if (getPendingThreadOrder() !== null || appAtomRegistry.get(threadDropBusyAtom)) return false;- const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);+ const shells = appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom);const current = shells.find((row) => row.id === thread.id && row.environmentId === thread.environmentId,);diff --git a/apps/mobile/src/features/threads/SubagentRow.tsx b/apps/mobile/src/features/threads/SubagentRow.tsxindex bd785f20e8c..a888adb8273 100644--- a/apps/mobile/src/features/threads/SubagentRow.tsx+++ b/apps/mobile/src/features/threads/SubagentRow.tsx@@ -26,14 +26,17 @@ type SubagentRowSubagent = Pick<| "status"| "progress"| "result"+ | "remoteChild">;export function SubagentRow(props: {readonly environmentId: EnvironmentId;readonly subagent: SubagentRowSubagent;readonly elapsed: ReactNode;+ /** The task runs in a linked environment this app is connected to. */+ readonly canOpenRemote?: boolean;}) {- const presentation = resolveSubagentRowPresentation(props.subagent);+ const presentation = resolveSubagentRowPresentation(props.subagent, props.canOpenRemote);const detail = subagentCardDetail(presentation.detail);return (<View className="flex-row gap-3">@@ -64,6 +67,11 @@ export function SubagentRow(props: {>{presentation.statusLabel}</Text>+ {presentation.runsOn !== null ? (+ <Text numberOfLines={1} className="shrink text-xs text-foreground-muted">+ on {presentation.runsOn}+ </Text>+ ) : null}</View>{props.elapsed}{presentation.canOpenThread ? (@@ -92,7 +100,8 @@ function SubagentMetadata(props: {readonly subagent: SubagentRowSubagent;}) {const { environmentId, subagent } = props;- const config = useEnvironmentServerConfig(environmentId);+ // A task in a linked environment runs a provider instance of that environment.+ const config = useEnvironmentServerConfig(subagent.remoteChild?.environmentId ?? environmentId);const provider = config?.providers.find((candidate) => candidate.instanceId === subagent.providerInstanceId,);diff --git a/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx b/apps/mobile/src/features/threads/ThreadAgentsSheet.tsxindex 4ebe077a3a6..5c0a4d53b6a 100644--- a/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx+++ b/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx@@ -20,10 +20,12 @@ import { AppText as Text } from "../../components/ui/AppText";import { environmentThreadDetails } from "../../state/threads";import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";import { NativeHeader, NativeScreen } from "../../native/ThemedScreenStack";+import { useEnvironments } from "../../state/environments";import { SubagentRow } from "./SubagentRow";import { useVisibleSecondClock } from "./use-visible-second-clock";import { ScreenContent } from "../../components/ui/ScreenContent";import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";+import { subagentThreadTarget } from "./threadAgentsPresentation";import { useOpenThreadInspector } from "./thread-inspector-navigation";@@ -53,21 +55,21 @@ export function ThreadAgentsSheet({ route }: StaticScreenProps<AgentsTarget>) {const subagents = turn?.subagents ?? [];const hasLiveAgent = (turn?.liveCount ?? 0) > 0;- const openChildThread = (childThreadId: ThreadId) => {+ const openChildThread = (child: { environmentId: EnvironmentId; threadId: ThreadId }) => {void Haptics.selectionAsync();if (openInspector(target, {type: "thread",- environmentId: target.environmentId,- threadId: childThreadId,+ environmentId: child.environmentId,+ threadId: child.threadId,}))return;// Replace this leaf sheet so the child enters the workspace stack expected by Home's Back button.navigation.dispatch(StackActions.replace("Thread", {- environmentId: target.environmentId,- threadId: childThreadId,+ environmentId: child.environmentId,+ threadId: child.threadId,}),);};@@ -143,26 +145,34 @@ function AgentRow(props: {readonly environmentId: EnvironmentId;readonly subagent: OrchestrationV2Subagent;readonly tickSeconds: boolean;- readonly onOpen: (childThreadId: ThreadId) => void;+ readonly onOpen: (child: { environmentId: EnvironmentId; threadId: ThreadId }) => void;}) {const { subagent } = props;- const childThreadId = subagent.childThreadId;+ const { presentationById } = useEnvironments();+ const target = subagentThreadTarget(subagent, props.environmentId, (id) =>+ presentationById.has(id),+ );const row = (<View className="border-b border-border py-3.5"><SubagentRowenvironmentId={props.environmentId}subagent={subagent}+ canOpenRemote={target !== null}elapsed={<AgentElapsed subagent={subagent} tickSeconds={props.tickSeconds} />}/></View>);- if (childThreadId === null) {+ if (target === null) {return (<Viewaccessible- accessibilityHint="Provider-managed agent. Its work appears in the transcript."+ accessibilityHint={+ subagent.remoteChild === undefined+ ? "Provider-managed agent. Its work appears in the transcript."+ : `Runs on ${subagent.remoteChild.label}. Connect to it to open its thread.`+ }>{row}</View>@@ -173,7 +183,7 @@ function AgentRow(props: {<PressableaccessibilityRole="link"accessibilityHint="Opens this agent's thread"- onPress={() => props.onOpen(childThreadId)}+ onPress={() => props.onOpen(target)}className="active:opacity-70">{row}diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsxindex 2233a30441a..1559adb60e1 100644--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx@@ -43,6 +43,8 @@ import { vcsEnvironment } from "../../state/vcs";import { EmptyState } from "../../components/ui/EmptyState";import { LoadingScreen } from "../../components/LoadingScreen";import { scopedThreadKey } from "../../lib/scopedEntities";+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import { useThreadShell } from "../../state/entities";import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";import { connectionTone } from "../connection/connectionTone";import {@@ -486,10 +488,22 @@ function ThreadRouteContent(: null;const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;+ const delegatedFrom = selectedThread?.delegatedFrom ?? null;+ const delegatedFromRef =+ delegatedFrom === null+ ? null+ : scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);+ // The title it had at delegation, until this client sees the parent itself.+ const delegatedFromThread = useThreadShell(delegatedFromRef);const headerSubtitle = [selectedThreadProject?.title ?? null,selectedEnvironmentConnection?.environmentLabel ?? null,- selectedThread?.linkOrigin ? `From ${selectedThread.linkOrigin.label}` : null,+ // A linked environment's delegated task names its parent; other linked work its origin.+ delegatedFrom !== null+ ? `Subagent of ${delegatedFromThread?.title ?? delegatedFrom.title}`+ : selectedThread?.linkOrigin+ ? `From ${selectedThread.linkOrigin.label}`+ : null,].filter(Boolean).join(" · ");diff --git a/apps/mobile/src/features/threads/thread-subagent-group.tsx b/apps/mobile/src/features/threads/thread-subagent-group.tsxindex aab3d3c7345..f83b85de0b8 100644--- a/apps/mobile/src/features/threads/thread-subagent-group.tsx+++ b/apps/mobile/src/features/threads/thread-subagent-group.tsx@@ -18,8 +18,11 @@ import type { ThreadFeedActivity } from "../../lib/threadActivity";import { serverEnvironment } from "../../state/server";import { environmentThreadDetails } from "../../state/threads";import { subagentCardElapsed } from "./subagent-card-presentation";+import { useEnvironments } from "../../state/environments";+import { useServerConfigs } from "../../state/entities";import { SubagentRow } from "./SubagentRow";import { useVisibleSecondClock } from "./use-visible-second-clock";+import { subagentThreadTarget } from "./threadAgentsPresentation";import { WorkLogBlock } from "./work-log-layout";import { useOpenThreadInspector } from "./thread-inspector-navigation";@@ -68,6 +71,7 @@ export function ThreadSubagentGroup(props: {environmentThreadDetails.threadAtom(scopeThreadRef(props.environmentId, members[0]!.threadId)),(thread) => thread?.projection.subagents,);+ const { presentationById } = useEnvironments();const agents = members.map((item) => {const live = liveAgents?.find((agent) => agent.id === item.subagentId);return {@@ -85,8 +89,13 @@ export function ThreadSubagentGroup(props: {const label = `${agents.length} subagents`;const summary = summarizeSubagentStatuses(agents.map((agent) => agent.status));const expanded = props.expandedRows[props.anchorKey] ?? false;+ const serverConfigs = useServerConfigs();+ // A task in a linked environment runs a provider instance of that environment.const iconUrl = (item: SubagentItem) =>- config?.providers.find((provider) => provider.instanceId === item.providerInstanceId)?.iconUrl;+ (item.remoteChild === undefined+ ? config+ : serverConfigs.get(item.remoteChild.environmentId)+ )?.providers.find((provider) => provider.instanceId === item.providerInstanceId)?.iconUrl;return (<WorkLogBlock>{grouped ? (@@ -137,29 +146,40 @@ export function ThreadSubagentGroup(props: {{!grouped || expanded ? (<View className="mb-1 gap-px rounded-xl border border-border bg-card/30 p-1">{agents.map((agent) => {- const threadId = agent.childThreadId;+ // A task in a linked environment opens there, if this app is connected to it.+ const target = subagentThreadTarget(agent, props.environmentId, (id) =>+ presentationById.has(id),+ );return (<Pressablekey={agent.item.id}accessible- accessibilityRole={threadId === null ? undefined : "link"}+ accessibilityRole={target === null ? undefined : "link"}accessibilityHint={- threadId === null ? "Provider-managed agent" : "Opens this agent's thread"+ target !== null+ ? "Opens this agent's thread"+ : agent.remoteChild !== undefined+ ? `Runs on ${agent.remoteChild.label}`+ : "Provider-managed agent"}- disabled={threadId === null}+ disabled={target === null}onPress={() => {- if (threadId === null) return;+ if (target === null) return;if (openInspector({ environmentId: props.environmentId, threadId: members[0]!.threadId },- { type: "thread", environmentId: props.environmentId, threadId },+ {+ type: "thread",+ environmentId: target.environmentId,+ threadId: target.threadId,+ },))return;navigation.dispatch(StackActions.push("Thread", {- environmentId: String(props.environmentId),- threadId: String(threadId),+ environmentId: String(target.environmentId),+ threadId: String(target.threadId),}),);}}@@ -168,6 +188,7 @@ export function ThreadSubagentGroup(props: {<SubagentRowenvironmentId={props.environmentId}subagent={agent}+ canOpenRemote={target !== null}elapsed={<SubagentElapsed agents={[agent]} />}/></Pressable>diff --git a/apps/mobile/src/features/threads/threadAgentsPresentation.ts b/apps/mobile/src/features/threads/threadAgentsPresentation.tsindex 96981ab3a38..3bf82e35c40 100644--- a/apps/mobile/src/features/threads/threadAgentsPresentation.ts+++ b/apps/mobile/src/features/threads/threadAgentsPresentation.ts@@ -3,7 +3,7 @@ import {subagentDetailPreview,} from "@t3tools/client-runtime/state/subagent-display";import { isActiveSubagentStatus } from "@t3tools/client-runtime/state/subagentRuntime";-import type { OrchestrationV2Subagent } from "@t3tools/contracts";+import type { EnvironmentId, OrchestrationV2Subagent, ThreadId } from "@t3tools/contracts";const PROMPT_TITLE_LIMIT = 80;@@ -16,6 +16,27 @@ export interface SubagentRowPresentation {readonly tone: SubagentRowTone;readonly live: boolean;readonly canOpenThread: boolean;+ /** The linked environment the task runs in, when it runs in one. */+ readonly runsOn: string | null;+}++/**+ * Where an agent's thread opens: here, or in the linked environment that runs+ * it. Null when there is no thread, or this app is not connected to that+ * environment.+ */+export function subagentThreadTarget(+ subagent: Pick<OrchestrationV2Subagent, "childThreadId" | "remoteChild">,+ environmentId: EnvironmentId,+ isKnownEnvironment: (environmentId: EnvironmentId) => boolean,+): { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } | null {+ if (subagent.childThreadId !== null) {+ return { environmentId, threadId: subagent.childThreadId };+ }+ const remote = subagent.remoteChild;+ return remote !== undefined && isKnownEnvironment(remote.environmentId)+ ? { environmentId: remote.environmentId, threadId: remote.threadId }+ : null;}function rowTitle(subagent: Pick<OrchestrationV2Subagent, "title" | "prompt">): string {@@ -58,8 +79,9 @@ function rowStatusLabel(status: OrchestrationV2Subagent["status"]): string {export function resolveSubagentRowPresentation(subagent: Pick<OrchestrationV2Subagent,- "title" | "prompt" | "status" | "progress" | "result" | "childThreadId"+ "title" | "prompt" | "status" | "progress" | "result" | "childThreadId" | "remoteChild">,+ canOpenRemote = false,): SubagentRowPresentation {const live = isActiveSubagentStatus(subagent.status);return {@@ -68,6 +90,8 @@ export function resolveSubagentRowPresentation(statusLabel: rowStatusLabel(subagent.status),tone: rowTone(subagent.status),live,- canOpenThread: subagent.childThreadId !== null,+ canOpenThread:+ subagent.childThreadId !== null || (subagent.remoteChild !== undefined && canOpenRemote),+ runsOn: subagent.remoteChild?.label ?? null,};}diff --git a/apps/mobile/src/state/thread-order.test.ts b/apps/mobile/src/state/thread-order.test.tsindex 6c8bec1454b..032744c75d6 100644--- a/apps/mobile/src/state/thread-order.test.ts+++ b/apps/mobile/src/state/thread-order.test.ts@@ -20,7 +20,9 @@ vi.mock("./atom-registry", async () => {});vi.mock("./threads", async () => {const { Atom } = await import("effect/reactivity");- return { environmentThreadShells: { threadShellsAtom: Atom.make([]).pipe(Atom.keepAlive) } };+ return {+ environmentThreadShells: { navigationThreadShellsAtom: Atom.make([]).pipe(Atom.keepAlive) },+ };});vi.mock("./server", async () => {const { Atom } = await import("effect/reactivity");@@ -34,7 +36,7 @@ vi.mock("./use-thread-outbox", async () => {type ServerConfigs = Atom.Type<typeof environmentServerConfigsAtom>;type ServerConfig = ServerConfigs extends ReadonlyMap<EnvironmentId, infer Config> ? Config : never;const configsAtom = environmentServerConfigsAtom as Atom.Writable<ServerConfigs, ServerConfigs>;-const shellsAtom = environmentThreadShells.threadShellsAtom as Atom.Writable<+const shellsAtom = environmentThreadShells.navigationThreadShellsAtom as Atom.Writable<readonly EnvironmentThreadShell[],readonly EnvironmentThreadShell[]>;diff --git a/apps/mobile/src/state/thread-order.ts b/apps/mobile/src/state/thread-order.tsindex 730797dac1b..a6505b61c8a 100644--- a/apps/mobile/src/state/thread-order.ts+++ b/apps/mobile/src/state/thread-order.ts@@ -64,7 +64,7 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) {const current = appAtomRegistry.get(pendingThreadOrderAtom);if (current === null) return;const configs = appAtomRegistry.get(environmentServerConfigsAtom);- const threads = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);+ const threads = appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom);const nowMs = Date.now();const ordered = getThreadListV2OrderedSection({threads,@@ -95,13 +95,16 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) {teardownPendingOrder = teardown;appAtomRegistry.set(pendingThreadOrderAtom, pending);unsubscribers.push(- appAtomRegistry.subscribe(environmentThreadShells.threadShellsAtom, refresh),+ appAtomRegistry.subscribe(environmentThreadShells.navigationThreadShellsAtom, refresh),appAtomRegistry.subscribe(environmentServerConfigsAtom, refresh),appAtomRegistry.subscribe(queuedThreadKeysAtom, refresh),minuteTick.subscribe(refresh),);armWake(- nextSnoozeWakeAfter(appAtomRegistry.get(environmentThreadShells.threadShellsAtom), Date.now()),+ nextSnoozeWakeAfter(+ appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom),+ Date.now(),+ ),);return {isPending: () => {diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.tsindex 7e6821e5139..a36b58a2b2d 100644--- a/apps/server/src/mcp/McpToolAccess.ts+++ b/apps/server/src/mcp/McpToolAccess.ts@@ -23,7 +23,7 @@ import {import * as PeerForwarding from "../peer/PeerForwarding.ts";import { assertNotLinked, assertSameLink, callerLinkOrigin } from "./linkOrigin.ts";import * as McpInvocationContext from "./McpInvocationContext.ts";-import { resolveInteractionMode, resolveRuntimeMode } from "./OrchestratorMcpService.ts";+import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts";import {assertFullAccess,assertLiveCaller,diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.tsindex d7f9746f76e..45561e76704 100644--- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts@@ -24,6 +24,7 @@ import * as ServerSettings from "../serverSettings.ts";import * as SecretRequests from "../secrets/SecretRequests.ts";import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";+import * as RemoteDelegation from "../peer/RemoteDelegation.ts";import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";import type * as McpInvocationContext from "./McpInvocationContext.ts";import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";@@ -161,6 +162,7 @@ it("readThread prefers activity-run status over a newer cancelled queued run", a} satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({list: () => Effect.succeed({ tasks: [] }),} satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),@@ -276,6 +278,7 @@ it("taskStatus returns task.providerInstanceId rather than the driver kind", asy} satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({list: () => Effect.succeed({ tasks: [] }),} satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),@@ -403,6 +406,7 @@ it("readThread and sendToThread reach threads in other projects", async () => {} satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({list: () =>Effect.succeed({diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.tsindex e3f3063d595..ead5229f865 100644--- a/apps/server/src/mcp/OrchestratorMcpService.test.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts@@ -57,9 +57,11 @@ import * as ProjectService from "../project/ProjectService.ts";import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";import * as ServerSettings from "../serverSettings.ts";import * as SecretRequests from "../secrets/SecretRequests.ts";+import * as RemoteDelegation from "../peer/RemoteDelegation.ts";import type { McpInvocationScope } from "./McpInvocationContext.ts";import { idleThreadProjection, liveThreadShell } from "./McpToolAccess.testkit.ts";import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";+import { resolveRuntimeMode } from "./delegatedTaskModes.ts";import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";const decodeTarget = Schema.decodeUnknownEffect(OrchestratorMcpTarget);@@ -165,6 +167,7 @@ describe("OrchestratorMcpService", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);const scope: McpInvocationScope = {@@ -265,6 +268,7 @@ describe("OrchestratorMcpService", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);const scope: McpInvocationScope = {@@ -365,6 +369,7 @@ describe("OrchestratorMcpService", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);const scope: McpInvocationScope = {@@ -457,6 +462,7 @@ describe("OrchestratorMcpService", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);const scope: McpInvocationScope = {@@ -553,6 +559,7 @@ describe("OrchestratorMcpService", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);const scope: McpInvocationScope = {@@ -644,6 +651,7 @@ describe("OrchestratorMcpService", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);const scope: McpInvocationScope = {@@ -729,6 +737,7 @@ describe("OrchestratorMcpService", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);const scope: McpInvocationScope = {@@ -815,6 +824,7 @@ describe("OrchestratorMcpService", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);const scope: McpInvocationScope = {@@ -948,6 +958,7 @@ describe("OrchestratorMcpService", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);const scope: McpInvocationScope = {@@ -1189,6 +1200,7 @@ describe("OrchestratorMcpService provider resolution", () => {]),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);@@ -1365,6 +1377,7 @@ describe("OrchestratorMcpService provider resolution", () => {adapterRegistryLayer([codexInstanceId, opencodeInstanceId]),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),),),@@ -1469,6 +1482,7 @@ describe("OrchestratorMcpService provider resolution", () => {adapterRegistryLayer([codexInstanceId]),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);@@ -1581,6 +1595,7 @@ describe("OrchestratorMcpService provider resolution", () => {adapterRegistryLayer([codexInstanceId, altInstanceId]),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),ServerSettings.layerTest(),);@@ -1689,6 +1704,7 @@ describe("OrchestratorMcpService provider resolution", () => {adapterRegistryLayer([codexInstanceId, altInstanceId]),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),ServerSettings.layerTest(),);@@ -1784,6 +1800,7 @@ describe("OrchestratorMcpService provider resolution", () => {]),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),),),@@ -2040,6 +2057,7 @@ describe("OrchestratorMcpService provider resolution", () => {),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);@@ -2204,6 +2222,7 @@ describe("OrchestratorMcpService provider resolution", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({list: () => Effect.succeed({ tasks }),upsert: () =>@@ -2274,6 +2293,7 @@ describe("OrchestratorMcpService provider resolution", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({list: () => Effect.succeed({ tasks: [task({})] }),}),@@ -2362,6 +2382,7 @@ describe("OrchestratorMcpService provider resolution", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({list: () => Effect.succeed({ tasks: [bound] }),upsert: () =>@@ -2438,6 +2459,7 @@ describe("OrchestratorMcpService provider resolution", () => {adapterRegistryLayer([]),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);yield* Effect.gen(function* () {@@ -2547,6 +2569,7 @@ describe("OrchestratorMcpService provider resolution", () => {adapterRegistryLayer([codexInstanceId, peerId]),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),);yield* Effect.gen(function* () {@@ -2577,11 +2600,9 @@ describe("OrchestratorMcpService provider resolution", () => {it.effect("refuses an explicit mode the target provider does not offer", () =>Effect.gen(function* () {- const error = yield* OrchestratorMcpService.resolveRuntimeMode(- "full-access",- "auto-accept-edits",- muse,- ).pipe(Effect.flip);+ const error = yield* resolveRuntimeMode("full-access", "auto-accept-edits", muse).pipe(+ Effect.flip,+ );assert.equal(error.code, "invalid_request");assert.include(error.message, "approval-required, full-access");}),@@ -2589,14 +2610,8 @@ describe("OrchestratorMcpService provider resolution", () => {it.effect("steps an inherited mode down to the broadest one the provider offers", () =>Effect.gen(function* () {- assert.equal(- yield* OrchestratorMcpService.resolveRuntimeMode("full-access", "inherit", muse),- "full-access",- );- assert.equal(- yield* OrchestratorMcpService.resolveRuntimeMode("auto", undefined, muse),- "approval-required",- );+ assert.equal(yield* resolveRuntimeMode("full-access", "inherit", muse), "full-access");+ assert.equal(yield* resolveRuntimeMode("auto", undefined, muse), "approval-required");}),);});@@ -2631,6 +2646,7 @@ describe("OrchestratorMcpService thread lookup", () => {}),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),),),@@ -2793,6 +2809,7 @@ describe("OrchestratorMcpService thread stop", () => {Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),),),diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.tsindex f2ce8c8bb1c..1721bc950cb 100644--- a/apps/server/src/mcp/OrchestratorMcpService.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.ts@@ -22,13 +22,11 @@ import {type OrchestratorMcpCreatedThread,type OrchestratorMcpDelegateTaskInput,type OrchestratorMcpDelegateTaskResult,- type OrchestratorMcpInteractionMode,type OrchestratorMcpDeleteScheduledTaskInput,type OrchestratorMcpRequestSecretInput,type OrchestratorMcpRequestSecretResult,type OrchestratorMcpDeleteScheduledTaskResult,type OrchestratorMcpListScheduledTasksResult,- type OrchestratorMcpRuntimeMode,type OrchestratorMcpScheduledTask,type OrchestratorMcpScheduleTaskInput,type OrchestratorMcpScheduleTaskResult,@@ -54,7 +52,6 @@ import {type OrchestratorMcpThreadWaitInput,type OrchestratorMcpThreadWaitResult,type ProviderInteractionMode,- type ProviderInstanceId,type ProviderOptionDescriptor,type ProviderOptionSelection,ProviderRequestKind,@@ -112,7 +109,17 @@ import {requireThreadScope,} from "./McpInvocationContext.ts";import * as Metrics from "../observability/Metrics.ts";+import {+ interactionModeRank,+ resolveInteractionMode,+ resolveRuntimeMode,+ runtimeModeRank,+ taskPrompt,+} from "./delegatedTaskModes.ts";+import { isLiveCallerShell, threadNotFound } from "./threadAccess.ts";import * as SecretRequests from "../secrets/SecretRequests.ts";+import * as PeerForwarding from "../peer/PeerForwarding.ts";+import * as RemoteDelegation from "../peer/RemoteDelegation.ts";const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000;@@ -214,43 +221,6 @@ function failure(code: OrchestratorMcpFailure["code"], message: string): Orchestreturn new OrchestratorMcpFailure({ code, message });}-/** Background subagents retain credentials until provider exit; archived threads and other instances cannot act. */-export const isLiveCallerShell = (- shell: Pick<- OrchestrationV2ThreadShell,- "archivedAt" | "activeRunId" | "providerInstanceId" | "pendingBackgroundTasks"- > | null,- providerInstanceId: ProviderInstanceId | undefined,-) =>- shell !== null &&- shell.archivedAt === null &&- shell.providerInstanceId === providerInstanceId &&- (shell.activeRunId !== null ||- (shell.pendingBackgroundTasks?.some(- (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId,- ) ??- false));--/**- * Threads an agent starts over MCP are `mcp:<uuid>`, and agents often paste the- * bare uuid. The id is never rewritten, so permission checks keyed on it still- * hold; the miss only names a live thread the caller could read by its full id.- */-export const threadNotFound = Effect.fn("OrchestratorMcpService.threadNotFound")(function* (- threads: Pick<ThreadManagementService.ThreadManagementService["Service"], "getThreadShell">,- threadId: ThreadId,- message: string,-) {- const prefixed = ThreadId.make(`mcp:${threadId}`);- const shell = yield* threads.getThreadShell(prefixed).pipe(Effect.orElseSucceed(() => null));- return yield* failure(- "thread_not_found",- shell === null || shell.deletedAt !== null- ? message- : `${message} Did you mean \`${prefixed}\`?`,- );-});-function threadManagementFailure(error: unknown): OrchestratorMcpFailure {if (!isThreadManagementError(error)) return failure("orchestration_error", errorMessage(error));switch (error._tag) {@@ -661,73 +631,6 @@ function canExposeTaskRunResult(run: OrchestrationV2Run | undefined): run is Orc);}-function runtimeModeRank(mode: RuntimeMode): number {- switch (mode) {- case "approval-required":- return 0;- case "auto-accept-edits":- return 1;- case "auto":- return 2;- case "full-access":- return 3;- }-}--function interactionModeRank(mode: ProviderInteractionMode): number {- return mode === "plan" ? 0 : 1;-}--export function resolveRuntimeMode(- parentMode: RuntimeMode,- requested: OrchestratorMcpRuntimeMode | undefined,- target?: Pick<ResolvedTarget, "modelSelection" | "supportedRuntimeModes">,-): Effect.Effect<RuntimeMode, OrchestratorMcpFailure> {- const inherited = requested === undefined || requested === "inherit";- const resolved = inherited ? parentMode : requested;- if (runtimeModeRank(resolved) > runtimeModeRank(parentMode)) {- return Effect.fail(- failure(- "runtime_mode_escalation_denied",- `Child runtime mode ${resolved} is broader than parent mode ${parentMode}.`,- ),- );- }- const supported = target?.supportedRuntimeModes;- if (supported === undefined || supported.length === 0 || supported.includes(resolved)) {- return Effect.succeed(resolved);- }- if (!inherited) {- return Effect.fail(- failure(- "invalid_request",- `Provider ${target?.modelSelection.instanceId} does not offer runtime mode ${resolved}, so it would run as approval-required. Use one of: ${supported.join(", ")}.`,- ),- );- }- return Effect.succeed(- supported- .filter((mode) => runtimeModeRank(mode) <= runtimeModeRank(resolved))- .toSorted((left, right) => runtimeModeRank(right) - runtimeModeRank(left))[0] ??- "approval-required",- );-}--export function resolveInteractionMode(- parentMode: ProviderInteractionMode,- requested: OrchestratorMcpInteractionMode | undefined,-): Effect.Effect<ProviderInteractionMode, OrchestratorMcpFailure> {- const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;- return interactionModeRank(resolved) > interactionModeRank(parentMode)- ? Effect.fail(- failure(- "interaction_mode_escalation_denied",- `Child interaction mode ${resolved} is broader than parent mode ${parentMode}.`,- ),- )- : Effect.succeed(resolved);-}-function stablePart(value: string): string {return encodeURIComponent(value);}@@ -809,12 +712,6 @@ function threadTitle(input: {return detail.length > 80 ? `${detail.slice(0, 77)}...` : detail;}-export function taskPrompt(input: OrchestratorMcpDelegateTaskInput): string {- return input.role === undefined || input.role === "general"- ? input.task- : `Act as the ${input.role} sub-agent for this task.\n\n${input.task}`;-}-function threadSettlement(thread: Pick<OrchestrationV2ThreadShell, "settledOverride" | "settledAt">,): Pick<OrchestratorMcpThreadListItem, "settled" | "settledAt"> {@@ -1062,6 +959,7 @@ const make = Effect.gen(function* () {const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;const gitDriver = yield* GitVcsDriver.GitVcsDriver;const serverSettings = yield* ServerSettings.ServerSettingsService;+ const remoteDelegation = yield* RemoteDelegation.RemoteDelegation;const requireProject = (projectId: ProjectId) =>projects.getById(projectId).pipe(@@ -1125,6 +1023,22 @@ const make = Effect.gen(function* () {),);+ // Task waits read on every wake of a parent that may hold thousands of+ // tasks, so they read only the task they watch and what its status needs.+ const loadTaskParent = (threadId: ThreadId, taskId: NodeId) =>+ threadManagement+ .getThreadRecords(threadId, ["runs", "subagents", "contextTransfers"], {+ subagentIds: [taskId],+ })+ .pipe(+ Effect.mapError((error) =>+ failure(+ "orchestration_error",+ `Unable to read thread ${threadId}: ${errorMessage(error)}`,+ ),+ ),+ );+const loadProjectThread = (projectId: OrchestrationV2ThreadProjection["thread"]["projectId"],threadId: ThreadId,@@ -1477,19 +1391,22 @@ const make = Effect.gen(function* () {acknowledgementOperation = "task-status-acknowledge",): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {yield* requireCapability(scope);- const parentProjection = yield* loadProjection(scope.thread.threadId);+ const parentProjection = yield* loadTaskParent(scope.thread.threadId, taskId);const task = parentProjection.subagents.find((candidate) =>candidate.id === taskId &&candidate.origin === "app_owned" &&candidate.threadId === scope.thread.threadId,);- if (task === undefined || task.childThreadId === null) {+ if (task === undefined || (task.childThreadId === null && task.remoteChild === undefined)) {return yield* failure("task_not_found",`Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`,);}+ if (task.childThreadId === null) {+ return yield* readRemoteTask(scope, task, waitTimedOut, acknowledgeTerminal);+ }const childControls = yield* threadManagement.getThreadRecords(task.childThreadId,@@ -1670,6 +1587,113 @@ const make = Effect.gen(function* () {return response;});+ /** `mode=wait` on a task already recorded, as `delegateTask` does for its own. */+ const awaitTask = Effect.fn("OrchestratorMcpService.awaitTask")(function* (+ scope: McpThreadInvocationScope,+ taskId: NodeId,+ requestedTimeoutMs: number | undefined,+ ): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {+ const timeoutMs = Math.min(+ MAX_WAIT_TIMEOUT_MS,+ Math.max(1, requestedTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),+ );+ const waited = yield* waitForTask(scope, taskId, timeoutMs);+ if (Option.isSome(waited)) return waited.value;+ // As for a local task: once the blocking wait ends, a later result wakes the parent.+ yield* threadManagement+ .dispatch({+ type: "delegated_task.wake-policy",+ commandId: stableCommandId({+ scope,+ requestKey: taskId,+ operation: "delegate-task-wake-policy",+ }),+ parentThreadId: scope.thread.threadId,+ taskId,+ completionWake: "always",+ })+ .pipe(Effect.ignoreCause({ log: true }));+ return yield* readTask(scope, taskId, true, true);+ });++ /**+ * A task that runs in a linked environment, answered from its row here:+ * the follower records its result once its thread there ends.+ */+ const readRemoteTask = Effect.fn("OrchestratorMcpService.readRemoteTask")(function* (+ scope: McpThreadInvocationScope,+ task: OrchestrationV2Subagent,+ waitTimedOut: boolean,+ acknowledgeTerminal: boolean,+ ): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {+ const status: OrchestratorMcpDelegateTaskResult["status"] =+ task.result === null+ ? "running"+ : task.status === "completed" ||+ task.status === "failed" ||+ task.status === "cancelled" ||+ task.status === "interrupted"+ ? task.status+ : "completed";+ const terminal = isTerminalTaskStatus(status);+ if (+ acknowledgeTerminal &&+ terminal &&+ task.completionDelivery?.state !== "acknowledged" &&+ task.completionDelivery?.state !== "disposed"+ ) {+ const parentProjection = yield* loadProjection(scope.thread.threadId);+ const observingRun = ThreadManagementService.latestActiveRun(parentProjection);+ yield* threadManagement+ .dispatch({+ type: "delegated_task.completion-delivery.acknowledge",+ commandId: stableCommandId({+ scope,+ requestKey: yield* requestKey(undefined),+ operation: "task-status-acknowledge",+ }),+ parentThreadId: scope.thread.threadId,+ taskId: task.id,+ observedByRunId:+ observingRun?.providerInstanceId === scope.thread.providerInstanceId+ ? observingRun.id+ : null,+ })+ .pipe(+ Effect.mapError((error) =>+ failure(+ "orchestration_error",+ `Unable to acknowledge delegated task ${task.id}: ${errorMessage(error)}`,+ ),+ ),+ );+ }+ return {+ taskId: task.id,+ childThreadId: null,+ ...(task.remoteChild === undefined ? {} : { remoteChild: task.remoteChild }),+ childRunId: null,+ childNodeId: task.id,+ status,+ workState: terminal ? "result_available" : "working",+ hasPendingChildRuns: false,+ providerInstanceId: task.providerInstanceId,+ model: task.model,+ summary: task.result,+ resultContextTransferId: null,+ latestTerminalRunId: null,+ latestTerminalStatus: terminal+ ? (status as OrchestratorMcpDelegateTaskResult["latestTerminalStatus"])+ : null,+ latestTerminalSummary: terminal ? task.result : null,+ latestTerminalResultContextTransferId: null,+ // Its questions and approvals are answered in the environment it runs in.+ hasPendingQuestion: false,+ pendingApproval: null,+ waitTimedOut,+ } satisfies OrchestratorMcpDelegateTaskResult;+ });+const waitForTask = Effect.fn("OrchestratorMcpService.waitForTask")(function* (scope: McpThreadInvocationScope, taskId: NodeId, _timeoutMs: number) {const streamError = (error: unknown) =>@@ -1686,10 +1710,17 @@ const make = Effect.gen(function* () {return Option.some(initial);}// One stream per event type, so transcript events never fill a buffer.+ // A remote task has no child here; its completion lands on the parent.+ const childThreadId = initial.childThreadId;+ const wakeEvents =+ childThreadId === null+ ? TASK_WAKE_EVENTS.filter(({ thread }) => thread === "parent")+ : TASK_WAKE_EVENTS;return yield* Stream.mergeAll(- TASK_WAKE_EVENTS.map(({ thread, eventType }) =>+ wakeEvents.map(({ thread, eventType }) =>threadManagement.streamStoredEventsFrom({- threadId: thread === "parent" ? scope.thread.threadId : initial.childThreadId,+ threadId:+ thread === "parent" || childThreadId === null ? scope.thread.threadId : childThreadId,afterSequence,eventType,}),@@ -2131,7 +2162,32 @@ const make = Effect.gen(function* () {};}),delegateTask: Effect.fn("OrchestratorMcpService.delegateTask")(function* (callerScope, input) {+ const environmentId =+ input.target === undefined+ ? undefined+ : PeerForwarding.remoteTarget(callerScope, input.target.environmentId);+ if (input.target !== undefined && environmentId !== undefined) {+ yield* requireCapability(callerScope);+ const scope = yield* requireThreadScope(callerScope, "delegate_task");+ // The task's child runs as an ordinary thread there; this thread keeps the task.+ const { taskId } = yield* remoteDelegation.delegate(scope, {+ ...input,+ target: { ...input.target, environmentId },+ });+ return yield* input.mode === "wait"+ ? awaitTask(scope, taskId, input.timeoutMs)+ : readTask(scope, taskId, false, true);+ }const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task");+ if (+ input.target?.projectId !== undefined &&+ input.target.projectId !== parent.thread.projectId+ ) {+ return yield* failure(+ "invalid_request",+ "A local task runs in this thread's project. Omit target.projectId, or pass target.environmentId to run it in that environment's project.",+ );+ }const parentRun = parent.runs.filter(ThreadManagementService.isActiveRun).toSorted((left, right) => right.ordinal - left.ordinal)[0];@@ -2311,6 +2367,24 @@ const make = Effect.gen(function* () {cancelTask: Effect.fn("OrchestratorMcpService.cancelTask")(function* (callerScope, input) {const scope = yield* requireThreadScope(callerScope, "task_cancel");const current = yield* readTask(scope, input.taskId);+ const childThreadId = current.childThreadId;+ if (childThreadId === null) {+ // The task runs in a linked environment: its thread there is stopped through the link.+ const { subagents } = yield* loadProjection(scope.thread.threadId);+ const remoteTask = subagents.find(+ (task) =>+ task.id === input.taskId &&+ task.origin === "app_owned" &&+ task.remoteChild !== undefined,+ );+ if (remoteTask === undefined) {+ return yield* failure(+ "task_not_found",+ `Delegated task ${input.taskId} does not belong to thread ${scope.thread.threadId}.`,+ );+ }+ return yield* remoteDelegation.cancel(scope, remoteTask, input);+ }const key = yield* requestKey(input.clientRequestId);const parentProjection = yield* loadProjection(scope.thread.threadId);// Cancelling stops the child and every task under it, each a write to a@@ -2338,7 +2412,7 @@ const make = Effect.gen(function* () {}}});- yield* assertStoppable(current.childThreadId);+ yield* assertStoppable(childThreadId);const parentTask = parentProjection.subagents.find((task) => task.id === input.taskId && task.origin === "app_owned",);@@ -2372,7 +2446,7 @@ const make = Effect.gen(function* () {.dispatch({type: "thread.stop",commandId,- threadId: current.childThreadId,+ threadId: childThreadId,stopDelegatedTasks: false,reason,})@@ -2385,7 +2459,7 @@ const make = Effect.gen(function* () {),);yield* threadManagement- .stopDelegatedTasks({ threadId: current.childThreadId, commandId, reason })+ .stopDelegatedTasks({ threadId: childThreadId, commandId, reason }).pipe(Effect.mapError((error) =>failure(@@ -2395,7 +2469,7 @@ const make = Effect.gen(function* () {),);const stopped = yield* threadManagement- .getThreadRecords(current.childThreadId, ["runs"])+ .getThreadRecords(childThreadId, ["runs"]).pipe(Effect.mapError(threadManagementFailure));for (const run of stopped.runs) {if (@@ -2413,7 +2487,7 @@ const make = Effect.gen(function* () {requestKey: key,operation: `cancel-task-queued-run:${run.id}`,}),- threadId: current.childThreadId,+ threadId: childThreadId,runId: run.id,}).pipe(Effect.mapError(threadManagementFailure));@@ -2474,7 +2548,7 @@ const make = Effect.gen(function* () {status: cancelled ? "cancelled" : current.status,} satisfies OrchestratorMcpTaskCancelResult;}- const child = yield* loadProjection(current.childThreadId);+ const child = yield* loadProjection(childThreadId);if (current.workState !== "waiting_for_children" &&ThreadManagementService.latestActiveRun(child) === undefined &&@@ -2873,6 +2947,7 @@ const make = Effect.gen(function* () {MAX_WAIT_TIMEOUT_MS,Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),),+ ...(input.untilDelegatedWorkSettled === true ? { untilDelegatedWorkSettled: true } : {}),}).pipe(Effect.mapError(threadManagementFailure));const status = result.run === null ? "idle" : runOutcome(result.run);@@ -2902,6 +2977,11 @@ const make = Effect.gen(function* () {status,timedOut: result.timedOut,...(wakesCaller ? { next: ORCHESTRATOR_MCP_RUNNING_TASK_NEXT } : {}),+ ...(result.resultRun === undefined+ ? {}+ : {+ resultRun: { runId: result.resultRun.id, status: runOutcome(result.resultRun) },+ }),} satisfies OrchestratorMcpThreadWaitResult;}),interruptThread: Effect.fn("OrchestratorMcpService.interruptThread")(function* (scope, input) {@@ -3006,4 +3086,5 @@ export const layer: Layer.Layer<| ProjectService.ProjectService| SecretRequests.SecretRequests| ServerSettings.ServerSettingsService+ | RemoteDelegation.RemoteDelegation> = Layer.effect(OrchestratorMcpService, make);diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.tsindex 6f89e37d4cd..c73ee930425 100644--- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts+++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts@@ -43,6 +43,7 @@ import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMocimport * as ProjectService from "../project/ProjectService.ts";import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";import * as SecretRequests from "../secrets/SecretRequests.ts";+import * as RemoteDelegation from "../peer/RemoteDelegation.ts";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import * as McpHttpServer from "./McpHttpServer.ts";import * as McpInvocationContext from "./McpInvocationContext.ts";@@ -53,6 +54,12 @@ const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe(Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),);+/** A task delegated here always has a local child thread. */+const localChild = (childThreadId: ThreadId | null): ThreadId => {+ if (childThreadId === null) throw new Error("expected a local delegated child");+ return childThreadId;+};+// Effect returns a declared tool failure as `isError` with its encoded payload// as JSON text, never as `structuredContent`.@@ -229,6 +236,7 @@ describe("orchestrator MCP toolkit", () => {Layer.provide(layerOrchestration),),),+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),Layer.provide(NodeServices.layer),);@@ -355,14 +363,16 @@ describe("orchestrator MCP toolkit", () => {});expect(delegated.resultContextTransferId).not.toBeNull();- const delegatedChild = yield* orchestrator.getThreadProjection(delegated.childThreadId);+ const delegatedChild = yield* orchestrator.getThreadProjection(+ localChild(delegated.childThreadId),+ );expect(delegatedChild.thread.lineage.relationshipToParent).toBe("subagent");expect(isProviderNativeSubagentThread(delegatedChild.thread)).toBe(false);const followupStartSequence = yield* orchestrator.getThreadEventSequence(- delegated.childThreadId,+ localChild(delegated.childThreadId),);const runningFollowupCall = yield* invoke("t3_thread_send", {- threadId: delegated.childThreadId,+ threadId: localChild(delegated.childThreadId),message: cancellationPrompt,clientRequestId: "delegated-child-replay-running-1",});@@ -371,7 +381,7 @@ describe("orchestrator MCP toolkit", () => {).pipe(Effect.orDie);yield* orchestrator.streamStoredEventsFrom({- threadId: delegated.childThreadId,+ threadId: localChild(delegated.childThreadId),afterSequence: followupStartSequence,}).pipe(@@ -390,7 +400,7 @@ describe("orchestrator MCP toolkit", () => {);const queuedFollowupCall = yield* invoke("t3_thread_send", {- threadId: delegated.childThreadId,+ threadId: localChild(delegated.childThreadId),message: queuedFollowupPrompt,mode: "queue",clientRequestId: "delegated-child-replay-queued-1",@@ -404,7 +414,7 @@ describe("orchestrator MCP toolkit", () => {});const pendingProjection = yield* orchestrator.getThreadProjection(- delegated.childThreadId,+ localChild(delegated.childThreadId),);const followupTasks = (yield* orchestrator.getThreadProjection(parentThreadId,@@ -451,9 +461,11 @@ describe("orchestrator MCP toolkit", () => {latestTerminalResultContextTransferId: null,});- const finalSequence = yield* orchestrator.getThreadEventSequence(delegated.childThreadId);+ const finalSequence = yield* orchestrator.getThreadEventSequence(+ localChild(delegated.childThreadId),+ );const interruptCall = yield* invoke("t3_thread_interrupt", {- threadId: delegated.childThreadId,+ threadId: localChild(delegated.childThreadId),runId: runningFollowup.runId,reason: "Allow the queued replay follow-up to run.",clientRequestId: "interrupt-delegated-child-replay-1",@@ -467,7 +479,7 @@ describe("orchestrator MCP toolkit", () => {});yield* orchestrator.streamStoredEventsFrom({- threadId: delegated.childThreadId,+ threadId: localChild(delegated.childThreadId),afterSequence: finalSequence,}).pipe(@@ -486,7 +498,9 @@ describe("orchestrator MCP toolkit", () => {),);- const finalProjection = yield* orchestrator.getThreadProjection(delegated.childThreadId);+ const finalProjection = yield* orchestrator.getThreadProjection(+ localChild(delegated.childThreadId),+ );expect(finalProjection.runs.find((run) => run.id === runningFollowup.runId)?.status).toBe("interrupted",);diff --git a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.tsindex 504ae749a78..5e6cc151fc2 100644--- a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts+++ b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts@@ -40,6 +40,7 @@ import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.tsimport * as SecretRequests from "../secrets/SecretRequests.ts";import type { McpInvocationScope } from "./McpInvocationContext.ts";import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";+import * as RemoteDelegation from "../peer/RemoteDelegation.ts";const layerOrchestratorService = OrchestratorMcpService.layer.pipe(Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),@@ -155,6 +156,7 @@ it.effect("task_cancel ends a delegated child's background native subagent", ()Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),Layer.mock(ProjectService.ProjectService)({}),Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),ServerSettings.layerTest(),Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),NodeServices.layer,diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.ts b/apps/server/src/mcp/ThreadMetadataMcpService.tsindex d5a77f326f9..cc2ce2b9a86 100644--- a/apps/server/src/mcp/ThreadMetadataMcpService.ts+++ b/apps/server/src/mcp/ThreadMetadataMcpService.ts@@ -16,7 +16,7 @@ import * as Layer from "effect/Layer";import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";import type { McpInvocationScope } from "./McpInvocationContext.ts";-import { threadNotFound } from "./OrchestratorMcpService.ts";+import { threadNotFound } from "./threadAccess.ts";export class ThreadMetadataMcpService extends Context.Service<ThreadMetadataMcpService,diff --git a/apps/server/src/mcp/delegatedTaskModes.ts b/apps/server/src/mcp/delegatedTaskModes.tsnew file mode 100644index 00000000000..54d25bbb36e--- /dev/null+++ b/apps/server/src/mcp/delegatedTaskModes.ts@@ -0,0 +1,95 @@+import {+ type ModelSelection,+ OrchestratorMcpFailure,+ type OrchestratorMcpDelegateTaskInput,+ type OrchestratorMcpInteractionMode,+ type OrchestratorMcpRuntimeMode,+ type ProviderInteractionMode,+ type RuntimeMode,+} from "@t3tools/contracts";+import * as Effect from "effect/Effect";++/** How much a runtime mode allows, narrowest first. */+export function runtimeModeRank(mode: RuntimeMode): number {+ switch (mode) {+ case "approval-required":+ return 0;+ case "auto-accept-edits":+ return 1;+ case "auto":+ return 2;+ case "full-access":+ return 3;+ }+}++/** How much an interaction mode allows: plan, then default. */+export function interactionModeRank(mode: ProviderInteractionMode): number {+ return mode === "plan" ? 0 : 1;+}++/**+ * The mode a child runs at: the one asked for, never broader than its parent's.+ * An inherited mode the target provider does not offer steps down to the+ * broadest one it does; an explicitly requested one is refused instead.+ */+export function resolveRuntimeMode(+ parentMode: RuntimeMode,+ requested: OrchestratorMcpRuntimeMode | undefined,+ target?: {+ readonly modelSelection: ModelSelection;+ readonly supportedRuntimeModes: ReadonlyArray<RuntimeMode> | undefined;+ },+): Effect.Effect<RuntimeMode, OrchestratorMcpFailure> {+ const inherited = requested === undefined || requested === "inherit";+ const resolved = inherited ? parentMode : requested;+ if (runtimeModeRank(resolved) > runtimeModeRank(parentMode)) {+ return Effect.fail(+ new OrchestratorMcpFailure({+ code: "runtime_mode_escalation_denied",+ message: `Child runtime mode ${resolved} is broader than parent mode ${parentMode}.`,+ }),+ );+ }+ const supported = target?.supportedRuntimeModes;+ if (supported === undefined || supported.length === 0 || supported.includes(resolved)) {+ return Effect.succeed(resolved);+ }+ if (!inherited) {+ return Effect.fail(+ new OrchestratorMcpFailure({+ code: "invalid_request",+ message: `Provider ${target?.modelSelection.instanceId} does not offer runtime mode ${resolved}, so it would run as approval-required. Use one of: ${supported.join(", ")}.`,+ }),+ );+ }+ return Effect.succeed(+ supported+ .filter((mode) => runtimeModeRank(mode) <= runtimeModeRank(resolved))+ .toSorted((left, right) => runtimeModeRank(right) - runtimeModeRank(left))[0] ??+ "approval-required",+ );+}++/** The same, for interaction modes. */+export function resolveInteractionMode(+ parentMode: ProviderInteractionMode,+ requested: OrchestratorMcpInteractionMode | undefined,+): Effect.Effect<ProviderInteractionMode, OrchestratorMcpFailure> {+ const resolved = requested === undefined || requested === "inherit" ? parentMode : requested;+ return interactionModeRank(resolved) > interactionModeRank(parentMode)+ ? Effect.fail(+ new OrchestratorMcpFailure({+ code: "interaction_mode_escalation_denied",+ message: `Child interaction mode ${resolved} is broader than parent mode ${parentMode}.`,+ }),+ )+ : Effect.succeed(resolved);+}++/** The task as its child receives it, with the role the caller asked for. */+export function taskPrompt(input: OrchestratorMcpDelegateTaskInput): string {+ return input.role === undefined || input.role === "general"+ ? input.task+ : `Act as the ${input.role} sub-agent for this task.\n\n${input.task}`;+}diff --git a/apps/server/src/mcp/linkOrigin.test.ts b/apps/server/src/mcp/linkOrigin.test.tsindex c990fbf68e8..59e7ba59921 100644--- a/apps/server/src/mcp/linkOrigin.test.ts+++ b/apps/server/src/mcp/linkOrigin.test.ts@@ -37,6 +37,7 @@ import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.tsimport * as ServerSettings from "../serverSettings.ts";import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";import * as SecretRequests from "../secrets/SecretRequests.ts";+import * as RemoteDelegation from "../peer/RemoteDelegation.ts";import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as McpHttpServer from "./McpHttpServer.ts";@@ -92,6 +93,7 @@ const layerLaunches = Layer.effect(branch: null,worktreePath: null,...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),+ ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }),createdBy: input.createdBy,creationSource: input.creationSource,})@@ -156,6 +158,7 @@ const layerTools = Layer.mergeAll(Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),Layer.provide(Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/p" }),),@@ -226,11 +229,16 @@ const failureCode = (result: McpSchema.CallToolResult) => {: undefined;};-const launch = (scope: McpInvocationContext.McpInvocationScope, title: string) =>+const launch = (+ scope: McpInvocationContext.McpInvocationScope,+ title: string,+ extra: Record<string, unknown> = {},+) =>call(scope, "t3_thread_launch", {projectId,title,modelSelection: { instanceId, model: "gpt-5" },+ ...extra,}).pipe(Effect.map((result) => {assert.equal(result.isError, false, JSON.stringify(result.content));@@ -309,6 +317,17 @@ it.layer(Layer.provideMerge(layerTools, layerOrchestration))("work a link starts// An ordinary outside agent's launch is not a link's.const plain = yield* launch(claudeCode, "Started by Claude Code");assert.equal((yield* projections.getThreadShell(plain))?.linkOrigin, undefined);++ // A link's delegated task names its parent there; only a link's launch may.+ const delegatedFrom = {+ environmentId: "environment-laptop",+ threadId: "thread:laptop-parent",+ title: "Laptop parent",+ };+ const task = yield* launch(laptop, "Delegated from the laptop", { delegatedFrom });+ assert.deepEqual((yield* projections.getThreadShell(task))?.delegatedFrom, delegatedFrom);+ const claimed = yield* launch(claudeCode, "Claims a parent", { delegatedFrom });+ assert.equal((yield* projections.getThreadShell(claimed))?.delegatedFrom, undefined);}),);diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.tsindex 1c0e3e543e5..ca8b373ba92 100644--- a/apps/server/src/mcp/threadAccess.ts+++ b/apps/server/src/mcp/threadAccess.ts@@ -3,9 +3,10 @@ import {CommandId,OrchestratorMcpFailure,type ProjectId,+ type ProviderInstanceId,type ProviderInteractionMode,type RuntimeMode,- type ThreadId,+ ThreadId,type OrchestrationV2ThreadShell,} from "@t3tools/contracts";import * as Crypto from "effect/Crypto";@@ -13,9 +14,30 @@ import * as Effect from "effect/Effect";import type { OrchestratorV2Error } from "../orchestration-v2/Orchestrator.ts";import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";-import * as OrchestrationMcp from "./OrchestratorMcpService.ts";+import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts";import * as McpInvocationContext from "./McpInvocationContext.ts";+/**+ * Threads an agent starts over MCP are `mcp:<uuid>`, and agents often paste the+ * bare uuid. The id is never rewritten, so permission checks keyed on it still+ * hold; the miss only names a live thread the caller could read by its full id.+ */+export const threadNotFound = Effect.fn("OrchestratorMcpService.threadNotFound")(function* (+ threads: Pick<ThreadManagement.ThreadManagementService["Service"], "getThreadShell">,+ threadId: ThreadId,+ message: string,+) {+ const prefixed = ThreadId.make(`mcp:${threadId}`);+ const shell = yield* threads.getThreadShell(prefixed).pipe(Effect.orElseSucceed(() => null));+ return yield* new OrchestratorMcpFailure({+ code: "thread_not_found",+ message:+ shell === null || shell.deletedAt !== null+ ? message+ : `${message} Did you mean \`${prefixed}\`?`,+ });+});+export const unavailable = () =>new OrchestratorMcpFailure({code: "orchestration_error",@@ -92,17 +114,32 @@ export const assertTargetWithinLimits = (limits: CallerLimits,target: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode },) =>- OrchestrationMcp.resolveRuntimeMode(limits.runtimeMode, target.runtimeMode).pipe(- Effect.andThen(- OrchestrationMcp.resolveInteractionMode(limits.interactionMode, target.interactionMode),- ),+ resolveRuntimeMode(limits.runtimeMode, target.runtimeMode).pipe(+ Effect.andThen(resolveInteractionMode(limits.interactionMode, target.interactionMode)),Effect.asVoid,);+/** Background subagents retain credentials until provider exit; archived threads and other instances cannot act. */+export const isLiveCallerShell = (+ shell: Pick<+ OrchestrationV2ThreadShell,+ "archivedAt" | "activeRunId" | "providerInstanceId" | "pendingBackgroundTasks"+ > | null,+ providerInstanceId: ProviderInstanceId | undefined,+) =>+ shell !== null &&+ shell.archivedAt === null &&+ shell.providerInstanceId === providerInstanceId &&+ (shell.activeRunId !== null ||+ (shell.pendingBackgroundTasks?.some(+ (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId,+ ) ??+ false));+/** 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) {if (caller === undefined) return Effect.void;- return OrchestrationMcp.isLiveCallerShell(caller, scope.thread?.providerInstanceId)+ return isLiveCallerShell(caller, scope.thread?.providerInstanceId)? Effect.void: Effect.fail(new OrchestratorMcpFailure({@@ -148,11 +185,7 @@ export const readThread = Effect.fn("mcp.readThread")(function* <const targetId = yield* resolveThreadId(context, threadId);const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable));if (shell === null || shell.deletedAt !== null) {- return yield* OrchestrationMcp.threadNotFound(- context.threads,- targetId,- "The thread was not found.",- );+ return yield* threadNotFound(context.threads, targetId, "The thread was not found.");}const projection = yield* context.threads.getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.tsindex 96a4a3345ce..e0eb6f6c811 100644--- a/apps/server/src/mcp/toolkits/core.test.ts+++ b/apps/server/src/mcp/toolkits/core.test.ts@@ -45,6 +45,7 @@ import * as PreviewBrowser from "../../preview/PreviewBrowser.ts";import * as ProjectService from "../../project/ProjectService.ts";import * as ProviderRegistry from "../../provider/ProviderRegistry.ts";import * as SecretRequests from "../../secrets/SecretRequests.ts";+import * as RemoteDelegation from "../../peer/RemoteDelegation.ts";import * as ScheduledTaskService from "../../scheduledTasks/ScheduledTaskService.ts";import * as ServerSettings from "../../serverSettings.ts";import * as McpHttpServer from "../McpHttpServer.ts";@@ -603,6 +604,7 @@ it.effect("refuses act-as-caller tools to a client caller", () =>Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),Layer.provide(Layer.mock(ProjectService.ProjectService)({})),Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),),),),@@ -659,6 +661,7 @@ it.effect("a caller cannot rewrite a scheduled task that runs above its own modeLayer.provide(Layer.mock(ProjectService.ProjectService)({})),Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),),),),@@ -743,6 +746,7 @@ it.effect.each(["t3_thread_interrupt", "t3_workflow_stop"])(Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),Layer.provide(Layer.mock(ProjectService.ProjectService)({})),Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),),),@@ -837,6 +841,7 @@ it.effect("discovers workflow stop targets and requires orchestration capabilityLayer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),Layer.provide(Layer.mock(ProjectService.ProjectService)({})),Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),),),);diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.tsindex 55034630b2c..f5a67ae025a 100644--- a/apps/server/src/mcp/toolkits/project/handlers.ts+++ b/apps/server/src/mcp/toolkits/project/handlers.ts@@ -20,7 +20,7 @@ import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";import * as ServerSettings from "../../../serverSettings.ts";import { resolveProjectSettings } from "@t3tools/shared/projectSettings";import { formatThreadLink } from "@t3tools/shared/threadLinks";-import { resolveRuntimeMode } from "../../OrchestratorMcpService.ts";+import { resolveRuntimeMode } from "../../delegatedTaskModes.ts";import * as McpInvocationContext from "../../McpInvocationContext.ts";import * as McpToolAccess from "../../McpToolAccess.ts";import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts";@@ -217,6 +217,8 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {createdBy: "agent",creationSource: "mcp",...(linkOrigin === undefined ? {} : { linkOrigin }),+ // Kept only alongside linkOrigin: thread.create drops it otherwise.+ ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }),}).pipe(Effect.mapError((error) => {if (error._tag === "AttachmentClaimError") {@@ -251,11 +253,10 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {t3_project_list: McpToolAccess.reads((input) =>Effect.gen(function* () {const projects = yield* access;- const snapshot = yield* projects.snapshot.pipe(Effect.mapError(unavailable));- const rows = snapshot.projects.filter((project) => project.deletedAt === null);- const start = input.cursor ?? 0,- end = start + (input.limit ?? 20);- return { projects: rows.slice(start, end), nextCursor: end < rows.length ? end : null };+ // Identities are resolved: linked environments find this side's project by repository.+ return yield* projects+ .listPage({ cursor: input.cursor ?? 0, limit: input.limit ?? 20 })+ .pipe(Effect.mapError(unavailable));}),),t3_project_read: McpToolAccess.reads((input) =>diff --git a/apps/server/src/mcp/toolkits/project/tools.ts b/apps/server/src/mcp/toolkits/project/tools.tsindex b4bddfcd0b5..38931596868 100644--- a/apps/server/src/mcp/toolkits/project/tools.ts+++ b/apps/server/src/mcp/toolkits/project/tools.ts@@ -5,6 +5,7 @@ import {TrimmedNonEmptyString,ThreadId,RunId,+ OrchestrationV2DelegatedFrom,OrchestrationV2RunStatus,OrchestrationV2ThreadLaunchWorkspaceStrategy,RuntimeMode,@@ -146,6 +147,8 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {),attachments: Schema.optional(Schema.Array(McpAttachmentInput).check(Schema.isMaxLength(8))),clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),+ /** Set by a linked environment launching its agent's delegated task here; ignored otherwise. */+ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),}),success: Schema.Struct({threadId: ThreadId,diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.tsindex 78bf5dcce18..6293d25025a 100644--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts@@ -121,6 +121,7 @@ const layerTest = Layer.mergeAll(RuntimeLayer.layer, RuntimeLayer.layerEventSinkrepositoryIdentityResolved: false,}),request: () => Effect.void,+ readRepositoryIdentity: () => Effect.succeed(null),getAvailable: () =>Effect.succeed({repositoryIdentity: null,diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex e627b466360..c4f3fe5ebd8 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -47,6 +47,7 @@ import {type OrchestrationV2ExecutionNode,type OrchestrationV2ProviderThread,type OrchestrationV2ProviderTurn,+ type OrchestrationV2RemoteTaskChild,type OrchestrationV2Run,type OrchestrationV2RunAttempt,type OrchestrationV2ThreadShell,@@ -516,6 +517,9 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {case "provider.switch":return command.threadId;case "delegated_task.request":+ case "delegated_task.remote.request":+ case "delegated_task.remote.complete":+ case "delegated_task.remote.stop":case "delegated_task.wake-policy":case "delegated_task.completion-delivery.acknowledge":case "delegated_task.completion-delivery.dispose":@@ -2540,6 +2544,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioactiveProviderThreadId: null,pullRequests: [],...(command.linkOrigin === undefined ? {} : { linkOrigin: command.linkOrigin }),+ // Only stamped work names a remote parent, so a client cannot claim one.+ ...(command.linkOrigin === undefined || command.delegatedFrom === undefined+ ? {}+ : { delegatedFrom: command.delegatedFrom }),lineage: {parentThreadId: null,relationshipToParent: null,@@ -7561,6 +7569,386 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio});});+ /**+ * Records a task that runs in a linked environment on its parent: the+ * task, its node and its turn item, as a local delegation does, but no child+ * thread here. The parent's own checks are the local request's.+ */+ const dispatchRemoteDelegatedTaskRequest = Effect.fn(+ "orchestrationV2.dispatch.remoteDelegatedTaskRequest",+ )(function* (+ command: Extract<+ OrchestrationV2InternalCommand,+ { readonly type: "delegated_task.remote.request" }+ >,+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,+ ) {+ const parentProjection = yield* projectionStore+ .getThreadRecords(command.parentThreadId, [+ "runs",+ "nodes",+ "subagents",+ "providerTurns",+ "attempts",+ ])+ .pipe(+ Effect.mapError(+ (cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }),+ ),+ );+ const parentRun = parentProjection.runs.find(+ (candidate) => candidate.id === command.parentRunId,+ );+ if (parentRun === undefined || !isBlockingRun(parentRun) || parentRun.rootNodeId === null) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: `Parent run ${command.parentRunId} is not active.`,+ });+ }+ if (yield* stopReachedRun(command, command.parentThreadId, parentRun.id)) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: `Parent run ${command.parentRunId} is stopping.`,+ });+ }+ const now = yield* DateTime.now;+ const taskNodeId = idAllocator.derive.delegatedTaskNode({ commandId: command.commandId });+ const taskTurnItemId = idAllocator.derive.delegatedTaskTurnItem({+ commandId: command.commandId,+ });+ const taskTitle = subagentThreadTitle({+ parentTitle: parentProjection.thread.title,+ prompt: command.task,+ ...(command.title === undefined ? {} : { title: command.title }),+ ordinal: parentProjection.subagents.length + 1,+ });+ const common = {+ threadId: command.parentThreadId,+ runId: parentRun.id,+ nodeId: taskNodeId,+ driver: command.driver,+ providerInstanceId: command.modelSelection.instanceId,+ occurredAt: now,+ };+ const emitEvent = emit(events, command);+ yield* emitEvent({+ ...common,+ type: "node.updated",+ payload: {+ id: taskNodeId,+ threadId: command.parentThreadId,+ runId: parentRun.id,+ parentNodeId: command.parentNodeId,+ rootNodeId: parentRun.rootNodeId,+ kind: "subagent",+ status: "running",+ countsForRun: false,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ runtimeRequestId: null,+ checkpointScopeId: null,+ startedAt: now,+ completedAt: null,+ },+ });+ yield* emitEvent({+ ...common,+ type: "subagent.updated",+ payload: {+ id: taskNodeId,+ threadId: command.parentThreadId,+ runId: parentRun.id,+ parentNodeId: command.parentNodeId,+ origin: "app_owned",+ createdBy: "agent",+ driver: command.driver,+ providerInstanceId: command.modelSelection.instanceId,+ providerThreadId: null,+ childThreadId: null,+ remoteChild: command.remoteChild,+ nativeTaskRef: null,+ prompt: command.task,+ title: command.title ?? null,+ model: command.modelSelection.model,+ ...(command.completionWake === undefined ? {} : { completionWake: command.completionWake }),+ status: "running",+ result: null,+ startedAt: now,+ completedAt: null,+ updatedAt: now,+ },+ });+ yield* emitEvent({+ ...common,+ type: "turn-item.updated",+ payload: {+ id: taskTurnItemId,+ threadId: command.parentThreadId,+ runId: parentRun.id,+ nodeId: taskNodeId,+ providerThreadId: parentRun.providerThreadId,+ providerTurnId: providerTurnForRun(parentProjection, parentRun)?.id ?? null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: yield* nextTurnItemOrdinal(parentProjection),+ status: "running",+ title: command.title ?? taskTitle,+ startedAt: now,+ completedAt: null,+ updatedAt: now,+ type: "subagent",+ subagentId: taskNodeId,+ origin: "app_owned",+ driver: command.driver,+ providerInstanceId: command.modelSelection.instanceId,+ childThreadId: null,+ remoteChild: command.remoteChild,+ prompt: command.task,+ result: null,+ },+ });+ });++ /**+ * Completes a task that ran in a linked environment: the parent half of+ * `finalizeAppOwnedSubagent`, with the result its thread there ended with.+ * It runs under the parent's lock, so it never interleaves with a wake+ * policy change or a delivery on the same task.+ */+ const dispatchRemoteDelegatedTaskComplete = Effect.fn(+ "orchestrationV2.dispatch.remoteDelegatedTaskComplete",+ )(function* (+ command: Extract<+ OrchestrationV2InternalCommand,+ { readonly type: "delegated_task.remote.complete" }+ >,+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,+ ) {+ const parentProjection = yield* projectionStore+ .getThreadRecords(+ command.parentThreadId,+ ["runs", "messages", "subagents", "providerTurns", "nodes", "turnItems"],+ { turnItemTypes: ["subagent"], messageRoles: ["user"] },+ )+ .pipe(+ Effect.mapError(+ (cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }),+ ),+ );+ const task = parentProjection.subagents.find(+ (candidate) =>+ candidate.id === command.taskId &&+ candidate.origin === "app_owned" &&+ candidate.remoteChild !== undefined,+ );+ if (task === undefined) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: `Delegated task ${command.taskId} is not a remote task of thread ${command.parentThreadId}.`,+ });+ }+ if (+ command.stoppedThere === "stopped" &&+ (command.stopCount ?? 0) !== (task.remoteChild?.stopCount ?? 0)+ )+ return;+ const remoteChild =+ command.stoppedThere === undefined+ ? task.remoteChild+ : { ...task.remoteChild!, stoppedThere: true };+ // The first result stands; a repeated follower report records nothing, which+ // the dispatcher refuses. A stop there after the result is still recorded, but+ // a run that ended by itself does not settle a stop the task here still owes.+ if (task.result !== null) {+ // A Stop or cancel here that lost the race to the result still owes its stop.+ if (command.stoppedThere === undefined) {+ return yield* emitRemoteStopOwed(events, command, task, task.remoteChild!);+ }+ const owesStop =+ task.status === "cancelled" ||+ task.status === "interrupted" ||+ task.remoteChild?.stoppedThere === false;+ if (+ task.remoteChild?.stoppedThere === true ||+ (owesStop && command.stoppedThere !== "stopped")+ )+ return;+ const now = yield* DateTime.now;+ yield* emit(+ events,+ command,+ )({+ type: "subagent.updated",+ threadId: command.parentThreadId,+ ...(task.runId === null ? {} : { runId: task.runId }),+ nodeId: task.id,+ driver: task.driver,+ occurredAt: now,+ payload: { ...task, remoteChild, updatedAt: now },+ });+ return;+ }+ const now = yield* DateTime.now;+ const updatedTask: OrchestrationV2Subagent = {+ ...task,+ remoteChild,+ status: command.status,+ result: command.result,+ completedAt: now,+ updatedAt: now,+ };+ const parentRun =+ task.runId === null+ ? undefined+ : parentProjection.runs.find((candidate) => candidate.id === task.runId);+ const plan = yield* planDelegatedCompletionDelivery({+ parentProjection,+ parentRun,+ task,+ updatedTask,+ now,+ }).pipe(mapDispatchError(command));+ const emitEvent = emit(events, command);+ yield* emitEvent({+ type: "subagent.updated",+ threadId: command.parentThreadId,+ ...(task.runId === null ? {} : { runId: task.runId }),+ nodeId: task.id,+ driver: task.driver,+ occurredAt: now,+ payload: plan.task,+ });+ if (plan.parentRun !== undefined) {+ yield* emitEvent({+ type: "run.updated",+ threadId: command.parentThreadId,+ runId: plan.parentRun.id,+ ...(plan.parentRun.rootNodeId === null ? {} : { nodeId: plan.parentRun.rootNodeId }),+ providerInstanceId: plan.parentRun.providerInstanceId,+ occurredAt: now,+ payload: plan.parentRun,+ });+ }+ if (plan.message !== undefined) {+ yield* emitEvent({+ type: "message.updated",+ threadId: command.parentThreadId,+ ...(plan.message.runId === null ? {} : { runId: plan.message.runId }),+ ...(plan.message.nodeId === null ? {} : { nodeId: plan.message.nodeId }),+ providerInstanceId:+ plan.parentRun?.providerInstanceId ?? parentProjection.thread.providerInstanceId,+ occurredAt: now,+ payload: plan.message,+ });+ }+ const node = parentProjection.nodes.find((candidate) => candidate.id === task.id);+ if (node !== undefined) {+ yield* emitEvent({+ type: "node.updated",+ threadId: command.parentThreadId,+ ...(node.runId === null ? {} : { runId: node.runId }),+ nodeId: node.id,+ driver: task.driver,+ occurredAt: now,+ payload: { ...node, status: command.status, completedAt: now },+ });+ }+ const item = parentProjection.turnItems.find(+ (candidate) => candidate.type === "subagent" && candidate.subagentId === task.id,+ );+ if (item !== undefined) {+ yield* emitEvent({+ type: "turn-item.updated",+ threadId: command.parentThreadId,+ ...(item.runId === null ? {} : { runId: item.runId }),+ ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),+ driver: task.driver,+ occurredAt: now,+ payload: {+ ...item,+ status: command.status,+ result: command.result,+ completedAt: now,+ updatedAt: now,+ } as OrchestrationV2TurnItem,+ });+ }+ });++ /**+ * Owes a stop to the thread there of a remote task that already has its+ * result. Only `remoteChild.stoppedThere` changes, so the result and its+ * delivery stand; the follower sends the stop and clears it.+ */+ const dispatchRemoteDelegatedTaskStop = Effect.fn(+ "orchestrationV2.dispatch.remoteDelegatedTaskStop",+ )(function* (+ command: Extract<+ OrchestrationV2InternalCommand,+ { readonly type: "delegated_task.remote.stop" }+ >,+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,+ ) {+ const { subagents } = yield* projectionStore+ .getThreadRecords(command.parentThreadId, ["subagents"])+ .pipe(+ Effect.mapError(+ (cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }),+ ),+ );+ const task = subagents.find(+ (candidate) =>+ candidate.id === command.taskId &&+ candidate.origin === "app_owned" &&+ candidate.remoteChild !== undefined &&+ candidate.result !== null,+ );+ if (task?.remoteChild === undefined) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: `Delegated task ${command.taskId} is not a finished remote task of thread ${command.parentThreadId}.`,+ });+ }+ yield* emitRemoteStopOwed(events, command, task, task.remoteChild);+ });++ const emitRemoteStopOwed = Effect.fn("orchestrationV2.dispatch.remoteStopOwed")(function* (+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,+ command: Extract<+ OrchestrationV2InternalCommand,+ { readonly type: "delegated_task.remote.complete" | "delegated_task.remote.stop" }+ >,+ task: OrchestrationV2Subagent,+ remoteChild: OrchestrationV2RemoteTaskChild,+ ) {+ const now = yield* DateTime.now;+ yield* emit(+ events,+ command,+ )({+ type: "subagent.updated",+ threadId: command.parentThreadId,+ ...(task.runId === null ? {} : { runId: task.runId }),+ nodeId: task.id,+ driver: task.driver,+ occurredAt: now,+ payload: {+ ...task,+ remoteChild: {+ ...remoteChild,+ stoppedThere: false,+ stopCount: (remoteChild.stopCount ?? 0) + 1,+ },+ updatedAt: now,+ },+ });+ });+// After blocking waits time out, enable later completions to wake the parent.// Hold the parent dispatch lock shared with finalization to serialize full-row writes.const dispatchDelegatedTaskWakePolicy = Effect.fn(@@ -12117,6 +12505,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocase "delegated_task.request":yield* dispatchDelegatedTaskRequest(command, events, effects);break;+ case "delegated_task.remote.request":+ yield* dispatchRemoteDelegatedTaskRequest(command, events);+ break;+ case "delegated_task.remote.complete":+ yield* dispatchRemoteDelegatedTaskComplete(command, events);+ break;+ case "delegated_task.remote.stop":+ yield* dispatchRemoteDelegatedTaskStop(command, events);+ break;case "delegated_task.wake-policy":yield* dispatchDelegatedTaskWakePolicy(command, events);break;@@ -12350,7 +12747,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioif (command.type === "notification.delivery.accept") {yield* mapDispatchError(command)(offerDelegatedCompletionDeliveries(command.threadId));}- if (command.type === "delegated_task.wake-policy") {+ if (+ command.type === "delegated_task.wake-policy" ||+ command.type === "delegated_task.remote.complete"+ ) {yield* mapDispatchError(command)(offerDelegatedCompletionDeliveries(command.parentThreadId));}diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.tsindex 7f70a2ec25e..288378d09fe 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts@@ -964,6 +964,56 @@ const runlessNativeSubagentNeedsRecovery = Effect.gen(function* () {}});+const subagentRecordsSelectById = Effect.gen(function* () {+ const store = yield* ProjectionStore.ProjectionStoreV2;+ const threadId = yield* addRolledBackRecoveryCandidate("subagent-records-by-id");+ const now = yield* DateTime.now;+ const ids = [NodeId.make("node:subagent-by-id:a"), NodeId.make("node:subagent-by-id:b")];+ for (const id of ids) {+ yield* store.apply({+ id: EventId.make(`event:${id}`),+ type: "subagent.updated",+ threadId,+ nodeId: id,+ driver,+ providerInstanceId,+ occurredAt: now,+ payload: {+ id,+ threadId,+ runId: null,+ parentNodeId: NodeId.make("node:subagent-by-id:parent"),+ origin: "app_owned",+ createdBy: "agent",+ driver,+ providerInstanceId,+ providerThreadId: null,+ childThreadId: null,+ nativeTaskRef: null,+ prompt: "Do the work",+ title: "Delegated task",+ model: null,+ status: "running",+ result: null,+ startedAt: now,+ completedAt: null,+ updatedAt: now,+ },+ });+ }+ const read = (subagentIds?: ReadonlyArray<NodeId>) =>+ store+ .getThreadRecords(threadId, ["subagents"], subagentIds === undefined ? {} : { subagentIds })+ .pipe(Effect.map(({ subagents }) => subagents.map((task) => task.id)));+ assert.deepEqual(yield* read(), ids);+ assert.deepEqual(yield* read([ids[1]!]), [ids[1]]);+ assert.deepEqual(yield* read([]), []);+});++it.effect("memory record reads select subagents by id", () =>+ subagentRecordsSelectById.pipe(Effect.provide(ProjectionStore.layerMemory)),+);+const assertProjectScopedShells = Effect.fn("assertProjectScopedShells")(function* (suffix: string,) {@@ -1392,6 +1442,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {assert.deepEqual(recovery?.restartCancelledBackgroundWork, work);}),);+ it.effect("record reads select subagents by id", () => subagentRecordsSelectById);it.effect("command reads skip finished leaf nodes of finished runs",() => commandReadsSkipSettledLeafNodes,diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex dff0bd31fa9..224e57c822e 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -333,6 +333,7 @@ export interface ProjectionRecordFilter {readonly messageRunIds?: ReadonlyArray<RunId>;readonly turnItemRunIds?: ReadonlyArray<RunId | null>;readonly runIds?: ReadonlyArray<RunId>;+ readonly subagentIds?: ReadonlyArray<NodeId>;readonly turnItemTypes?: ReadonlyArray<OrchestrationV2TurnItem["type"]>;readonly turnItemStatuses?: ReadonlyArray<OrchestrationV2TurnItem["status"]>;readonly omitSettledLeafNodes?: boolean;@@ -518,6 +519,15 @@ export interface ProjectionStoreV2Shape {ReadonlyArray<{ readonly threadId: ThreadId; readonly worktreePath: string }>,ProjectionStoreV2Error>;+ /**+ * Delegated tasks in a linked environment with work left for this one: no+ * result yet, or cancelled or stopped here without that stop reaching there,+ * including a Stop after the task had its result.+ */+ readonly getOpenRemoteDelegatedTasks: Effect.Effect<+ ReadonlyArray<{ readonly parentThreadId: ThreadId; readonly taskId: NodeId }>,+ ProjectionStoreV2Error+ >;readonly getTurnStartContext: (threadId: ThreadId,runId: RunId,@@ -1660,6 +1670,9 @@ export function threadShellFromProjection(...(projection.thread.linkOrigin === undefined? {}: { linkOrigin: projection.thread.linkOrigin }),+ ...(projection.thread.delegatedFrom === undefined+ ? {}+ : { delegatedFrom: projection.thread.delegatedFrom }),latestRunId: latestRun?.id ?? null,latestRunRequestedAt: latestRun?.requestedAt ?? null,latestRunStartedAt: latestRun?.startedAt ?? null,@@ -1939,6 +1952,9 @@ function shellFromState(input: {...(input.state.thread.linkOrigin === undefined? {}: { linkOrigin: input.state.thread.linkOrigin }),+ ...(input.state.thread.delegatedFrom === undefined+ ? {}+ : { delegatedFrom: input.state.thread.delegatedFrom }),latestRunId: input.state.latestRunId,latestRunRequestedAt: input.state.latestRunRequestedAt,latestRunStartedAt: input.state.latestRunStartedAt,@@ -3350,13 +3366,15 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =rows.toSorted((left, right) => left.position - right.position),),),- fields !== undefined && !fields.includes("subagents")+ (fields !== undefined && !fields.includes("subagents")) ||+ (window === undefined && matchesNothing(filter?.subagentIds))? Effect.succeed([]): window === undefined? sql<PayloadRow>`SELECT payload_jsonFROM orchestration_v2_projection_subagentsWHERE thread_id = ${threadId}+ ${filter?.subagentIds === undefined ? sql`` : sql`AND subagent_id IN (SELECT value FROM json_each(${encodeIdList(filter.subagentIds)}))`}ORDER BY COALESCE(started_at, ''), subagent_id ASC`: sql<PayloadRow>`@@ -6268,6 +6286,32 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =).pipe(Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })));+ const getOpenRemoteDelegatedTasks: ProjectionStoreV2Shape["getOpenRemoteDelegatedTasks"] = sql<{+ readonly thread_id: string;+ readonly subagent_id: string;+ }>`+ SELECT thread_id, subagent_id FROM orchestration_v2_projection_subagents+ WHERE origin = 'app_owned'+ AND child_thread_id IS NULL+ AND json_type(payload_json, '$.remoteChild') = 'object'+ AND (+ json_type(payload_json, '$.result') = 'null'+ OR (+ json_extract(payload_json, '$.status') IN ('cancelled', 'interrupted')+ AND json_type(payload_json, '$.remoteChild.stoppedThere') IS NOT 'true'+ )+ OR json_type(payload_json, '$.remoteChild.stoppedThere') = 'false'+ )+ `.pipe(+ Effect.map((rows) =>+ rows.map((row) => ({+ parentThreadId: ThreadId.make(row.thread_id),+ taskId: NodeId.make(row.subagent_id),+ })),+ ),+ Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })),+ );+const getThreadsWithPullRequests: ProjectionStoreV2Shape["getThreadsWithPullRequests"] =Effect.fn("ProjectionStore.getThreadsWithPullRequests")(function* (threadId) {@@ -6787,6 +6831,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =getSettlementCandidates: readOnReader(getSettlementCandidates),getThreadsWithPullRequests: readOnReader(getThreadsWithPullRequests),getThreadWorktreePaths: readOnReader(getThreadWorktreePaths),+ getOpenRemoteDelegatedTasks: getOpenRemoteDelegatedTasks.pipe(NodeSqliteClient.readOnly),getThreadProjection,getTurnStartContext: readOnReader(getTurnStartContext),getTurnStartHistory: readOnReader(getTurnStartHistory),@@ -7039,6 +7084,7 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(),),),+ getOpenRemoteDelegatedTasks: Effect.succeed([]),getThreadsWithPullRequests: (threadId) =>Ref.get(replayState).pipe(Effect.map((state) =>@@ -7235,6 +7281,10 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(filter?.runIds === undefined? projection.runs: projection.runs.filter((row) => filter.runIds!.includes(row.id)),+ subagents:+ filter?.subagentIds === undefined+ ? projection.subagents+ : projection.subagents.filter((row) => filter.subagentIds!.includes(row.id)),turnItems: projection.turnItems.filter((row) =>(filter?.turnItemRunIds === undefined ||diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.tsindex f8434619256..82ae02fb54a 100644--- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts+++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts@@ -100,11 +100,19 @@ function isNonterminalNodeStatus(status: string): boolean {return status === "pending" || status === "running" || status === "waiting";}+/**+ * A delegate_task child. Its own thread is reconciled and continued on its own+ * (here, or in the linked environment it runs in) and reports back through+ * the app, so it is not provider background work.+ */function isAppOwnedDelegation(task: {readonly origin: OrchestrationV2Subagent["origin"];readonly childThreadId: ThreadId | null;+ readonly remoteChild?: OrchestrationV2Subagent["remoteChild"];}): boolean {- return task.origin === "app_owned" && task.childThreadId !== null;+ return (+ task.origin === "app_owned" && (task.childThreadId !== null || task.remoteChild !== undefined)+ );}function isAppOwnedDelegationItem(diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.tsindex 4837c4a2ac1..a39f6b7f036 100644--- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts@@ -210,6 +210,7 @@ it.effect(ProjectionStore.ProjectionStoreV2.of({apply: () => Effect.void,getLimitRecoveryCandidates: () => Effect.die("unused getLimitRecoveryCandidates"),+ getOpenRemoteDelegatedTasks: Effect.die("unused getOpenRemoteDelegatedTasks"),getShellSnapshot: () => Effect.die("unused getShellSnapshot"),listActiveSubagentThreadIds: () => Effect.die("unused listActiveSubagentThreadIds"),listOlderSettledThreads: () => Effect.die("unused listOlderSettledThreads"),diff --git a/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts b/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.tsnew file mode 100644index 00000000000..4bb8c103f6d--- /dev/null+++ b/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts@@ -0,0 +1,411 @@+import { assert, it } from "@effect/vitest";+import {+ CommandId,+ EnvironmentId,+ EventId,+ MessageId,+ NodeId,+ ProjectId,+ ProviderDriverKind,+ ProviderInstanceId,+ ProviderThreadId,+ RunId,+ ThreadId,+} from "@t3tools/contracts";+import * as Context from "effect/Context";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Ref from "effect/Ref";++import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";+import * as EventSink from "./EventSink.ts";+import * as Orchestrator from "./Orchestrator.ts";+import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";+import * as ProjectionStore from "./ProjectionStore.ts";+import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";+import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";+import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";+import * as SqlitePersistence from "../persistence/Sqlite.ts";++// A delegated task whose child runs in a linked environment is recorded on+// its parent without a child thread here, and completing it wakes the parent+// the way a local child's result does.++const instanceId = ProviderInstanceId.make("codex");+const driver = ProviderDriverKind.make("codex");+const modelSelection = { instanceId, model: "gpt-5.4" };+const adapter = {+ instanceId,+ driver,+ getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),+ openSession: () => Effect.die("No provider process needed for delegated task records"),+} as ProviderAdapter.ProviderAdapterV2["Service"];++/** Every parent wake the orchestrator offers, for the tests to read. */+class Offers extends Context.Service<+ Offers,+ Ref.Ref<ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>>+>()("t3/orchestration-v2/RemoteDelegatedTask.test/Offers") {}+const layerOffers = Layer.effect(+ Offers,+ Ref.make<ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>>([]),+);+const layerDatabase = SqlitePersistence.layerMemory;+const layerTest = Layer.mergeAll(+ layerDatabase,+ ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),+ ProviderReplayHarness.layerWithRegistry(+ { name: "remote-delegated-task" },+ ProviderAdapterRegistry.layerFromAdapters([adapter]),+ { databaseLayer: layerDatabase, runEffectWorker: false },+ ),+).pipe(+ Layer.provide(+ Layer.effect(+ ProviderContinuationRequests.ProviderContinuationRequests,+ Offers.pipe(+ Effect.map((offers) => ({+ offer: (request: ProviderContinuationRequests.ProviderContinuationRequest) =>+ Ref.update(offers, (seen) => [...seen, request]),+ take: Effect.never,+ })),+ ),+ ),+ ),+ Layer.provideMerge(layerOffers),+);++/** A parent thread whose run is live, as when its agent calls delegate_task. */+const seedLiveParent = (name: string) =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const sink = yield* EventSink.EventSinkV2;+ const now = yield* DateTime.now;+ const threadId = ThreadId.make(`thread:${name}`);+ const runId = RunId.make(`run:${name}`);+ const rootNodeId = NodeId.make(`node:${name}:root`);+ const providerThreadId = ProviderThreadId.make(`provider-thread:${name}`);+ yield* orchestrator.dispatch({+ type: "thread.create",+ createdBy: "user",+ creationSource: "web",+ commandId: CommandId.make(`command:create:${name}`),+ threadId,+ projectId: ProjectId.make("project:remote-delegated-task"),+ title: "Parent",+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ });+ yield* sink.write({+ commandId: CommandId.make(`command:seed:${name}`),+ events: [+ {+ id: EventId.make(`event:seed-provider-thread:${name}`),+ type: "provider-thread.updated",+ threadId,+ driver,+ providerInstanceId: instanceId,+ occurredAt: now,+ payload: {+ id: providerThreadId,+ driver,+ providerInstanceId: instanceId,+ providerSessionId: null,+ appThreadId: threadId,+ ownerNodeId: rootNodeId,+ nativeThreadRef: { driver, nativeId: `native:${name}`, strength: "strong" },+ nativeConversationHeadRef: null,+ status: "active",+ firstRunOrdinal: 1,+ lastRunOrdinal: 1,+ handoffIds: [],+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ },+ },+ {+ id: EventId.make(`event:seed-node:${name}`),+ type: "node.updated",+ threadId,+ runId,+ nodeId: rootNodeId,+ driver,+ providerInstanceId: instanceId,+ occurredAt: now,+ payload: {+ id: rootNodeId,+ threadId,+ runId,+ parentNodeId: null,+ rootNodeId,+ kind: "root_turn",+ status: "running",+ countsForRun: true,+ providerThreadId,+ providerTurnId: null,+ nativeItemRef: null,+ runtimeRequestId: null,+ checkpointScopeId: null,+ startedAt: now,+ completedAt: null,+ },+ },+ {+ id: EventId.make(`event:seed-run:${name}`),+ type: "run.updated",+ threadId,+ runId,+ nodeId: rootNodeId,+ providerInstanceId: instanceId,+ occurredAt: now,+ payload: {+ id: runId,+ threadId,+ ordinal: 1,+ providerInstanceId: instanceId,+ modelSelection,+ providerThreadId,+ userMessageId: MessageId.make(`message:seed-user:${name}`),+ rootNodeId,+ activeAttemptId: null,+ status: "running",+ requestedAt: now,+ startedAt: now,+ completedAt: null,+ checkpointId: null,+ contextHandoffId: null,+ },+ },+ ],+ });+ return { threadId, runId, rootNodeId };+ });++const remoteChild = {+ environmentId: EnvironmentId.make("environment:box"),+ threadId: ThreadId.make("thread:on-the-box"),+ label: "Box",+};++it.layer(layerTest)("a delegated task in a linked environment", (it) => {+ it.effect("is recorded on its parent without a child thread here, once", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const parent = yield* seedLiveParent("records");+ const request = {+ type: "delegated_task.remote.request" as const,+ commandId: CommandId.make("command:remote-delegate:records"),+ parentThreadId: parent.threadId,+ parentRunId: parent.runId,+ parentNodeId: parent.rootNodeId,+ task: "Run the suite there.",+ driver: ProviderDriverKind.make("remote"),+ modelSelection,+ remoteChild,+ completionWake: "always" as const,+ };+ yield* orchestrator.dispatch(request);+ yield* orchestrator.dispatch(request);+ const projection = yield* orchestrator.getThreadProjection(parent.threadId);+ assert.equal(projection.subagents.length, 1);+ const [task] = projection.subagents;+ assert.equal(task?.childThreadId, null);+ assert.deepEqual(task?.remoteChild, remoteChild);+ assert.equal(task?.status, "running");+ const item = projection.turnItems.find((candidate) => candidate.type === "subagent");+ assert.deepEqual(item?.type === "subagent" ? item.remoteChild : undefined, remoteChild);+ // No thread was created here for the child.+ assert.equal(yield* orchestrator.getThreadShell(remoteChild.threadId), null);+ }),+ );++ it.effect("keeps a newer stop recoverable after an older acknowledgement", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ const parent = yield* seedLiveParent("stop-generation");+ yield* orchestrator.dispatch({+ type: "delegated_task.remote.request",+ commandId: CommandId.make("command:remote-delegate:stop-generation"),+ parentThreadId: parent.threadId,+ parentRunId: parent.runId,+ parentNodeId: parent.rootNodeId,+ task: "Run a check.",+ driver: ProviderDriverKind.make("remote"),+ modelSelection,+ remoteChild,+ });+ const task = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!;+ const openFor = projections.getOpenRemoteDelegatedTasks.pipe(+ Effect.map((open) => open.filter((entry) => entry.parentThreadId === parent.threadId)),+ );+ const complete = {+ type: "delegated_task.remote.complete" as const,+ parentThreadId: parent.threadId,+ taskId: task.id,+ status: "completed" as const,+ result: "Original result.",+ };+ yield* orchestrator.dispatch({+ ...complete,+ commandId: CommandId.make("command:result:stop-generation"),+ stoppedThere: "ran-out",+ });+ for (const count of [1, 2]) {+ yield* orchestrator.dispatch({+ type: "delegated_task.remote.stop",+ parentThreadId: parent.threadId,+ taskId: task.id,+ commandId: CommandId.make(`command:stop-generation:${count}`),+ });+ }+ // Reports from before generation tracking cannot clear a later numbered Stop either.+ for (const stopCount of [undefined, 1]) {+ const rejected = yield* orchestrator+ .dispatch({+ ...complete,+ commandId: CommandId.make(`command:stale-stop:${stopCount}`),+ stoppedThere: "stopped",+ ...(stopCount === undefined ? {} : { stopCount }),+ })+ .pipe(Effect.flip);+ assert.equal(rejected._tag, "OrchestratorDispatchError");+ assert.deepEqual(yield* openFor, [{ parentThreadId: parent.threadId, taskId: task.id }]);+ }+ yield* orchestrator.dispatch({+ ...complete,+ commandId: CommandId.make("command:current-stop:2"),+ stoppedThere: "stopped",+ stopCount: 2,+ });+ const settled = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!;+ assert.equal(settled.result, "Original result.");+ assert.equal(settled.status, "completed");+ assert.equal(settled.remoteChild?.stoppedThere, true);+ assert.deepEqual(yield* openFor, []);+ }),+ );++ it.effect("owes a stop there for a Stop here that loses the race to its result", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ const parent = yield* seedLiveParent("stop-after-result");+ yield* orchestrator.dispatch({+ type: "delegated_task.remote.request",+ commandId: CommandId.make("command:remote-delegate:stop-after-result"),+ parentThreadId: parent.threadId,+ parentRunId: parent.runId,+ parentNodeId: parent.rootNodeId,+ task: "Run a check.",+ driver: ProviderDriverKind.make("remote"),+ modelSelection,+ remoteChild,+ });+ const task = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!;+ const complete = {+ type: "delegated_task.remote.complete" as const,+ parentThreadId: parent.threadId,+ taskId: task.id,+ };+ yield* orchestrator.dispatch({+ ...complete,+ commandId: CommandId.make("command:result:stop-after-result"),+ status: "completed",+ result: "Done there.",+ stoppedThere: "ran-out",+ });+ // The parent's Stop read the task before its result landed.+ yield* orchestrator.dispatch({+ ...complete,+ commandId: CommandId.make("command:parent-stop:stop-after-result"),+ status: "interrupted",+ result: "Stopped with its parent.",+ });++ const stopped = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!;+ assert.equal(stopped.status, "completed");+ assert.equal(stopped.result, "Done there.");+ assert.equal(stopped.remoteChild?.stoppedThere, false);+ assert.equal(stopped.remoteChild?.stopCount, 1);+ const open = yield* projections.getOpenRemoteDelegatedTasks;+ assert.deepEqual(+ open.filter((entry) => entry.parentThreadId === parent.threadId),+ [{ parentThreadId: parent.threadId, taskId: task.id }],+ );+ }),+ );++ it.effect("wakes its parent with the result when it completes there", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const parent = yield* seedLiveParent("completes");+ const recorded = yield* orchestrator.dispatch({+ type: "delegated_task.remote.request",+ commandId: CommandId.make("command:remote-delegate:completes"),+ parentThreadId: parent.threadId,+ parentRunId: parent.runId,+ parentNodeId: parent.rootNodeId,+ task: "Run the suite there.",+ driver: ProviderDriverKind.make("remote"),+ modelSelection,+ remoteChild,+ completionWake: "always",+ });+ const taskEvent = recorded.storedEvents.find(+ (stored) => stored.event.type === "subagent.updated",+ );+ const taskId =+ taskEvent?.event.type === "subagent.updated" ? taskEvent.event.payload.id : undefined;+ assert.isDefined(taskId);+ // Until it completes, it is open, and a restarted follower picks it up.+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ const openFor = projections.getOpenRemoteDelegatedTasks.pipe(+ Effect.map((open) => open.filter((task) => task.parentThreadId === parent.threadId)),+ );+ assert.deepEqual(yield* openFor, [{ parentThreadId: parent.threadId, taskId: taskId! }]);+ const offers = yield* Offers;+ yield* Ref.set(offers, []);+ const complete = (result: string) =>+ orchestrator.dispatch({+ type: "delegated_task.remote.complete",+ commandId: CommandId.make(`command:remote-complete:${result}`),+ parentThreadId: parent.threadId,+ taskId: taskId!,+ status: "completed",+ result,+ stoppedThere: "ran-out",+ });+ yield* complete("All 412 tests pass on the box.");+ // A second report is refused, so the first result stands.+ const late = yield* complete("A late, different answer.").pipe(Effect.flip);+ assert.equal(late._tag, "OrchestratorDispatchError");++ const projection = yield* orchestrator.getThreadProjection(parent.threadId);+ const task = projection.subagents.find((candidate) => candidate.id === taskId);+ assert.equal(task?.status, "completed");+ assert.equal(task?.result, "All 412 tests pass on the box.");+ // The live parent run claimed it, so task_status acknowledges it as for a local child.+ assert.equal(task?.completionDelivery?.state, "claimed");+ // Nothing is left for the follower to pick up after a restart.+ assert.deepEqual(yield* openFor, []);+ const item = projection.turnItems.find(+ (candidate) => candidate.type === "subagent" && candidate.subagentId === taskId,+ );+ assert.equal(item?.status, "completed");+ // The parent's live run is offered the delivery, as for a local child.+ const delivery = projection.runs.find((run) => run.id === parent.runId)?.delegatedCompletion+ ?.delivery;+ assert.deepEqual(delivery?.taskIds, [taskId]);+ const offered = yield* Ref.get(offers);+ assert.equal(offered.length, 1);+ assert.equal(offered[0]?.threadId, parent.threadId);+ }),+ );+});diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.tsindex f3a7ede9972..1e3fd1a8b36 100644--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts@@ -63,6 +63,7 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as ThreadManagement from "./ThreadManagementService.ts";import * as ThreadTitleRegeneration from "./ThreadTitleRegenerationService.ts";import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";+import * as RemoteDelegation from "../peer/RemoteDelegation.ts";import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";const projectId = ProjectId.make("project:launch-test");@@ -179,6 +180,7 @@ function makeHarness(options: HarnessOptions = {}) {bootstrap: () => Effect.die("unused"),update: () => Effect.die("unused"),delete: () => Effect.die("unused"),+ listPage: () => Effect.die("unused"),getById: (id) =>Effect.succeed(id === projectId@@ -321,6 +323,7 @@ it.effect.each(NodeCrypto.layer,Scheduler.layer,Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),),),);diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.tsindex faef398df10..289df535c12 100644--- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts@@ -9,6 +9,7 @@ import {type ModelSelection,type OrchestrationV2Actor,type OrchestrationV2CreationSource,+ type OrchestrationV2DelegatedFrom,type OrchestrationV2LinkOrigin,type OrchestrationV2ProviderThreadNativeMetadata,type OrchestrationV2ThreadProjection,@@ -100,6 +101,8 @@ export interface ThreadLaunchInput {readonly creationSource: OrchestrationV2CreationSource;/** The linked environment this launch is for, if one asked for it. */readonly linkOrigin?: OrchestrationV2LinkOrigin;+ /** The parent there, when that environment's agent delegated this as a task. */+ readonly delegatedFrom?: OrchestrationV2DelegatedFrom;}type PreparationInput = Pick<@@ -916,6 +919,9 @@ const make = Effect.gen(function* () {? {}: { importedNativeThread: input.importedNativeThread }),...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),+ ...(input.delegatedFrom === undefined+ ? {}+ : { delegatedFrom: input.delegatedFrom }),createdBy: input.createdBy,creationSource: input.creationSource,});diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.tsindex 2b75cd7633b..dfd244ebe2f 100644--- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts+++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts@@ -1,6 +1,7 @@import { expect, it } from "@effect/vitest";import {CommandId,+ EnvironmentId,MessageId,type OrchestrationV2Command,type OrchestrationV2Run,@@ -17,12 +18,14 @@ import {} from "@t3tools/contracts";import * as Deferred from "effect/Deferred";import * as DateTime from "effect/DateTime";+import * as Duration from "effect/Duration";import * as Option from "effect/Option";import * as Effect from "effect/Effect";import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as Queue from "effect/Queue";import * as Stream from "effect/Stream";+import * as TestClock from "effect/testing/TestClock";import * as ServerSettings from "../serverSettings.ts";import * as SqlitePersistence from "../persistence/Sqlite.ts";@@ -50,8 +53,13 @@ it("stamps authoritative provenance on commands that create threads or messages"interactionMode: "default",branch: null,worktreePath: null,- // A client cannot claim a linked environment's origin for its own thread.+ // A client cannot claim a linked environment's origin, or a parent there.linkOrigin: { sessionId: "forged", label: "Somewhere else" },+ delegatedFrom: {+ environmentId: EnvironmentId.make("environment:elsewhere"),+ threadId: ThreadId.make("thread:elsewhere"),+ title: "Somewhere else",+ },};const stamped = ThreadManagementService.withCreationProvenance(command, {@@ -63,6 +71,7 @@ it("stamps authoritative provenance on commands that create threads or messages"creationSource: "web",});expect(stamped).not.toHaveProperty("linkOrigin");+ expect(stamped).not.toHaveProperty("delegatedFrom");});const layerReceiptsTest = CommandReceiptStore.layer.pipe(@@ -290,6 +299,151 @@ it.effect("waitForThread follows a restart continuation instead of the cut run",}),);+it.effect("waitForThread can wait past an ended run for the thread's delegated work", () =>+ Effect.gen(function* () {+ const projectId = ProjectId.make("project:thread-management:wait-delegated");+ const threadId = ThreadId.make("thread:thread-management:wait-delegated");+ const runId = RunId.make("run:thread-management:wait-delegated");+ const wakeRunId = RunId.make("run:thread-management:wait-delegated:wake");+ const subscribed = yield* Deferred.make<void>();+ const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();+ const at = (seconds: number) => DateTime.makeUnsafe(seconds * 1_000);+ const run = (id: RunId, ordinal: number, status: OrchestrationV2Run["status"], end: number) =>+ ({+ id,+ ordinal,+ status,+ startedAt: at(end - 1),+ completedAt: status === "running" ? null : at(end),+ }) as unknown as OrchestrationV2Run;+ // The run ended, but a task it delegated still runs and will wake the thread.+ let runs = [run(runId, 1, "completed", 1)];+ let subagents = [{ status: "running" }];+ const stored = (sequence: number, event: object) =>+ ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent;+ const layerTest = ThreadManagementService.layer.pipe(+ Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),+ Layer.provide(+ Layer.mock(Orchestrator.OrchestratorV2)({+ getThreadEventSequence: () => Effect.succeed(0),+ restartContinuationPending: () => Effect.succeed(false),+ delegatedTaskResultPending: () => Effect.succeed(false),+ streamStoredEventsFrom: (input) =>+ input?.eventType === "subagent.updated"+ ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(+ Stream.drain,+ Stream.concat(Stream.fromQueue(events)),+ )+ : Stream.never,+ getThreadRecords: () =>+ Effect.sync(+ () =>+ ({+ thread: { id: threadId, projectId, deletedAt: null },+ runs,+ messages: [],+ subagents,+ providerThreads: [],+ }) as unknown as OrchestrationV2ThreadProjection,+ ),+ }),+ ),+ Layer.provide(ServerSettings.layerTest()),+ Layer.provide(layerReceiptsTest),+ );+ const service = yield* ThreadManagementService.ThreadManagementService.pipe(+ Effect.provide(layerTest),+ );+ // Without the option, the ended run is the answer, as before.+ expect(+ yield* service.waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }),+ ).toMatchObject({ timedOut: false, run: { id: runId } });+ expect(+ yield* service.waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }),+ ).not.toHaveProperty("resultRun");++ const fiber = yield* service+ .waitForThread({+ projectId,+ threadId,+ runId,+ timeoutMs: 60 * 60 * 1_000,+ untilDelegatedWorkSettled: true,+ })+ .pipe(Effect.forkChild);+ // A wait that returns early fails below instead of hanging here.+ yield* Effect.raceFirst(Deferred.await(subscribed), Fiber.await(fiber));+ // The task finishes; its delivery wakes the thread, whose next run answers.+ subagents = [{ status: "completed" }];+ runs = [...runs, run(wakeRunId, 2, "completed", 3)];+ yield* Queue.offer(events, stored(1, { type: "subagent.updated", payload: {} }));+ const result = yield* Fiber.join(fiber);++ expect(result).toMatchObject({+ timedOut: false,+ run: { id: runId, status: "completed" },+ resultRun: { id: wakeRunId, status: "completed" },+ });+ }),+);++it.effect("waitForThread settles delegated work on a thread rolled back past its only run", () =>+ Effect.gen(function* () {+ const projectId = ProjectId.make("project:thread-management:wait-rolled-back");+ const threadId = ThreadId.make("thread:thread-management:wait-rolled-back");+ const runId = RunId.make("run:thread-management:wait-rolled-back");+ const rolledBack = {+ id: runId,+ ordinal: 1,+ status: "rolled_back",+ startedAt: DateTime.makeUnsafe(0),+ completedAt: DateTime.makeUnsafe(1_000),+ } as unknown as OrchestrationV2Run;+ const layerTest = ThreadManagementService.layer.pipe(+ Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),+ Layer.provide(+ Layer.mock(Orchestrator.OrchestratorV2)({+ getThreadEventSequence: () => Effect.succeed(0),+ restartContinuationPending: () => Effect.succeed(false),+ delegatedTaskResultPending: () => Effect.succeed(false),+ streamStoredEventsFrom: () => Stream.never,+ getThreadRecords: () =>+ Effect.succeed({+ thread: { id: threadId, projectId, deletedAt: null },+ runs: [rolledBack],+ messages: [],+ subagents: [],+ providerThreads: [],+ } as unknown as OrchestrationV2ThreadProjection),+ }),+ ),+ Layer.provide(ServerSettings.layerTest()),+ Layer.provide(layerReceiptsTest),+ );+ const service = yield* ThreadManagementService.ThreadManagementService.pipe(+ Effect.provide(layerTest),+ );+ const fiber = yield* service+ .waitForThread({+ projectId,+ threadId,+ runId,+ timeoutMs: 60_000,+ untilDelegatedWorkSettled: true,+ })+ .pipe(Effect.forkChild);+ // Nothing will ever run there again, so a wait still open runs out here.+ yield* TestClock.adjust(Duration.millis(60_000));+ const result = yield* Fiber.join(fiber);++ expect(result).toMatchObject({+ timedOut: false,+ run: { id: runId, status: "rolled_back" },+ resultRun: { id: runId, status: "rolled_back" },+ });+ }),+);+it.effect("waitForThread returns the cut run once its continuation is declined", () =>Effect.gen(function* () {const projectId = ProjectId.make("project:thread-management:wait-declined");diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.tsindex 6f5656ce83b..aeeaf2ed822 100644--- a/apps/server/src/orchestration-v2/ThreadManagementService.ts+++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts@@ -36,6 +36,7 @@ import {ThreadId,type TurnItemId,} from "@t3tools/contracts";+import { delegatedTaskProgress } from "@t3tools/provider-core/server/subagentProjection";import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";@@ -72,7 +73,7 @@ export function withCreationProvenance(switch (command.type) {case "thread.create": {// Only the server stamps a link's origin, so a client cannot set one.- const { linkOrigin: _linkOrigin, ...rest } = command;+ const { linkOrigin: _linkOrigin, delegatedFrom: _delegatedFrom, ...rest } = command;return { ...rest, ...provenance };}case "message.dispatch":@@ -108,6 +109,9 @@ function existingThreadIdsForCommand(case "delegated_task.wake-policy":case "delegated_task.completion-delivery.acknowledge":case "delegated_task.completion-delivery.dispose":+ case "delegated_task.remote.request":+ case "delegated_task.remote.complete":+ case "delegated_task.remote.stop":return [command.parentThreadId];case "thread.created.record":return command.parentThreadId === command.targetThreadId@@ -155,12 +159,20 @@ export interface ThreadManagementWaitInput {readonly threadId: ThreadId;readonly runId?: RunId;readonly timeoutMs: number;+ /**+ * Also wait until the thread's own delegated work settles: an ended run+ * still owes the thread's answer while a child, a background task or a+ * completion delivery will wake it again, as a delegated task's result does.+ */+ readonly untilDelegatedWorkSettled?: boolean;}export interface ThreadManagementWaitResult {readonly threadId: ThreadId;readonly run: OrchestrationV2Run | null;readonly timedOut: boolean;+ /** With `untilDelegatedWorkSettled`, once settled: the run with the thread's final answer. */+ readonly resultRun?: OrchestrationV2Run;}export interface ThreadManagementInterruptInput {@@ -899,29 +911,73 @@ const make = Effect.gen(function* () {isTerminalRunStatus(run.status) && (yield* orchestrator.restartContinuationPending(run));return { run, pending, settled: isTerminalRunStatus(run.status) && !pending };});- const initial = yield* outcome(target.runs);- if (initial.settled) {- return { threadId: input.threadId, run: initial.run, timedOut: false };- }+ const untilDelegatedWorkSettled = input.untilDelegatedWorkSettled === true;+ const delegatedWorkResult = Effect.gen(function* () {+ const records = yield* getProjectThreadRecords(+ input,+ ["runs", "messages", "subagents", "providerThreads"],+ { messageRoles: ["user"] },+ );+ const progress = delegatedTaskProgress(records);+ // A thread rolled back past all its work, with nothing left running, has no answer to wait for.+ if (+ progress.resultRun === undefined &&+ records.runs.every((run) => isTerminalRunStatus(run.status))+ ) {+ return latestRun(records);+ }+ if (progress.state !== "result_available") return undefined;+ const pending = yield* orchestrator+ .delegatedTaskResultPending(input.threadId)+ .pipe(Effect.mapError(loadError));+ return pending ? undefined : progress.resultRun;+ });+ const evaluate = Effect.fn("orchestrationV2.threadManagement.evaluate")(function* (+ runs: ReadonlyArray<OrchestrationV2Run>,+ ) {+ const current = yield* outcome(runs);+ if (!current.settled || !untilDelegatedWorkSettled) {+ return { ...current, resultRun: undefined };+ }+ const resultRun = yield* delegatedWorkResult;+ return { ...current, settled: resultRun !== undefined, resultRun };+ });+ const settledResult = (current: Effect.Success<ReturnType<typeof evaluate>>) => ({+ threadId: input.threadId,+ run: current.run,+ timedOut: !current.settled,+ ...(current.resultRun === undefined ? {} : { resultRun: current.resultRun }),+ });+ const initial = yield* evaluate(target.runs);+ if (initial.settled) return settledResult(initial);// A declined continuation records no event, so its effect settling wakes// the wait too.const wait = Stream.merge(- Stream.merge(- orchestrator.streamStoredEventsFrom({- threadId: input.threadId,- afterSequence,- eventType: "run.updated",- }),- orchestrator.streamStoredEventsFrom({- threadId: input.threadId,- afterSequence,- eventType: "thread.deleted",- }),+ Stream.mergeAll(+ (+ [+ "run.updated",+ "thread.deleted",+ // What delegated work reads besides runs: tasks and their+ // deliveries, and a provider thread's background tasks.+ ...(untilDelegatedWorkSettled+ ? (["subagent.updated", "provider-thread.updated"] as const)+ : []),+ ] as const+ ).map((eventType) =>+ orchestrator.streamStoredEventsFrom({+ threadId: input.threadId,+ afterSequence,+ eventType,+ }),+ ),+ { concurrency: "unbounded" },).pipe(Stream.mapError(loadError),Stream.filter((stored) =>+ untilDelegatedWorkSettled ||stored.event.type !== "run.updated" ||stored.event.payload.id === selectedRun.id ||stored.event.payload.restartContinuationOfRunId !== undefined,@@ -933,7 +989,7 @@ const make = Effect.gen(function* () {).pipe(Stream.mapEffect(() =>getProjectThreadRecords(input, ["runs"]).pipe(- Effect.flatMap((current) => outcome(current.runs)),+ Effect.flatMap((current) => evaluate(current.runs)),),),Stream.filter((current) => current.settled),@@ -941,14 +997,11 @@ const make = Effect.gen(function* () {Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),);const waited = Option.flatten(yield* wait);- if (Option.isSome(waited)) {- return { threadId: input.threadId, run: waited.value.run, timedOut: false };- }+ if (Option.isSome(waited)) return settledResult(waited.value);// The run may have reached a terminal status while the timeout was// winning the race; the final projection read decides what actually// happened, so only a still-active run counts as timed out.- const final = yield* outcome((yield* getProjectThreadRecords(input, ["runs"])).runs);- return { threadId: input.threadId, run: final.run, timedOut: !final.settled };+ return settledResult(yield* evaluate((yield* getProjectThreadRecords(input, ["runs"])).runs));});const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(@@ -1175,7 +1228,42 @@ const make = Effect.gen(function* () {> = [];const stoppedChildThreadIds = new Set<ThreadId>();for (const task of subagents) {- if (task.origin !== "app_owned" || task.childThreadId === null) continue;+ if (task.origin !== "app_owned") continue;+ if (task.childThreadId === null) {+ // A task in a linked environment ends here; its follower then stops it there.+ // One with its result keeps it, but its thread there may run follow-up work.+ if (task.remoteChild === undefined) continue;+ const commandId = CommandId.make(`${input.commandId}:stop:${task.id}`);+ yield* dispatch(+ task.result === null+ ? {+ type: "delegated_task.remote.complete",+ commandId,+ parentThreadId: input.threadId,+ taskId: task.id,+ status: "interrupted",+ result:+ input.reason === undefined+ ? "Stopped with its parent."+ : `Stopped with its parent: ${input.reason}`,+ }+ : {+ type: "delegated_task.remote.stop",+ commandId,+ parentThreadId: input.threadId,+ taskId: task.id,+ },+ ).pipe(+ Effect.catch((error) =>+ Effect.logWarning("Unable to stop a delegated task", {+ parentThreadId: input.threadId,+ taskId: task.id,+ error,+ }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),+ ),+ );+ continue;+ }const threadId = task.childThreadId;// Follow-up tasks reuse a child thread; walk its subtree only once.if (stoppedChildThreadIds.has(threadId)) continue;diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.tsindex 025191f0988..425c00af4b1 100644--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts@@ -614,6 +614,7 @@ const layerSharedApplicationDataPlaneTest = Layer.mergeAll(repositoryIdentityResolved: false,}),request: () => Effect.void,+ readRepositoryIdentity: () => Effect.succeed(null),getAvailable: () =>Effect.succeed({repositoryIdentity: null,diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.tsindex 6a4fb2937c0..59a4e810c9b 100644--- a/apps/server/src/peer/PeerForwarding.test.ts+++ b/apps/server/src/peer/PeerForwarding.test.ts@@ -32,6 +32,7 @@ import * as ProviderRegistry from "../provider/ProviderRegistry.ts";import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";import * as SecretRequests from "../secrets/SecretRequests.ts";import * as ServerSettings from "../serverSettings.ts";+import * as RemoteDelegation from "./RemoteDelegation.ts";import * as McpHttpServer from "../mcp/McpHttpServer.ts";import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";import { liveThreadShell } from "../mcp/McpToolAccess.testkit.ts";@@ -228,6 +229,7 @@ const serveBox = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) =>Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),Layer.provide(ServerSettings.layerTest()),Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),),);@@ -296,12 +298,17 @@ const makeLaptop = Effect.gen(function* () {} as never),}),),- Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),- Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),- Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),- Layer.provide(Layer.mock(ProjectService.ProjectService)({})),- Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),- Layer.provide(ServerSettings.layerTest()),+ Layer.provide(+ Layer.mergeAll(+ Layer.mock(ProviderRegistry.ProviderRegistry)({}),+ Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}),+ Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),+ Layer.mock(ProjectService.ProjectService)({}),+ Layer.mock(SecretRequests.SecretRequests)({}),+ ServerSettings.layerTest(),+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),+ ),+ ),Layer.fresh,);const here = yield* Layer.build(layerHere);diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.tsindex 05b9db6afa9..be9db1e4895 100644--- a/apps/server/src/peer/PeerForwarding.ts+++ b/apps/server/src/peer/PeerForwarding.ts@@ -2,6 +2,10 @@ import {type EnvironmentId,OrchestratorMcpFailure,type OrchestratorMcpEnvironmentLinksResult,+ OrchestratorMcpThreadInterruptInput,+ OrchestratorMcpThreadInterruptResult,+ OrchestratorMcpThreadReadInput,+ OrchestratorMcpThreadReadResult,OrchestratorMcpThreadWaitInput,OrchestratorMcpThreadWaitResult,} from "@t3tools/contracts";@@ -51,6 +55,18 @@ export class PeerForwarding extends Context.Service<environmentId: EnvironmentId,params: Tool.Parameters<T>,) => Effect.Effect<Tool.Success<T>, OrchestratorMcpFailure>;+ /** `t3_thread_read` there. */+ readonly readThread: (+ scope: Scope,+ environmentId: EnvironmentId,+ input: OrchestratorMcpThreadReadInput,+ ) => Effect.Effect<OrchestratorMcpThreadReadResult, OrchestratorMcpFailure>;+ /** `t3_thread_interrupt` there. */+ readonly interruptThread: (+ scope: Scope,+ environmentId: EnvironmentId,+ input: OrchestratorMcpThreadInterruptInput,+ ) => Effect.Effect<OrchestratorMcpThreadInterruptResult, OrchestratorMcpFailure>;/** `t3_thread_wait` there, in pieces short enough to survive any route. */readonly waitForThread: (scope: Scope,@@ -132,6 +148,30 @@ const make = Effect.gen(function* () {});});+ const readThread: PeerForwarding["Service"]["readThread"] = (scope, environmentId, input) =>+ forward<OrchestratorMcpThreadReadResult>(+ scope,+ "t3_thread_read",+ OrchestratorMcpThreadReadInput,+ OrchestratorMcpThreadReadResult,+ environmentId,+ input,+ );++ const interruptThread: PeerForwarding["Service"]["interruptThread"] = (+ scope,+ environmentId,+ input,+ ) =>+ forward<OrchestratorMcpThreadInterruptResult>(+ scope,+ "t3_thread_interrupt",+ OrchestratorMcpThreadInterruptInput,+ OrchestratorMcpThreadInterruptResult,+ environmentId,+ input,+ );+const waitForThread: PeerForwarding["Service"]["waitForThread"] = Effect.fn("PeerForwarding.waitForThread",)(function* (scope, environmentId, input) {@@ -148,7 +188,14 @@ const make = Effect.gen(function* () {OrchestratorMcpThreadWaitInput,OrchestratorMcpThreadWaitResult,environmentId,- { threadId: input.threadId, ...(runId === undefined ? {} : { runId }), timeoutMs: chunk },+ {+ threadId: input.threadId,+ ...(runId === undefined ? {} : { runId }),+ timeoutMs: chunk,+ ...(input.untilDelegatedWorkSettled === undefined+ ? {}+ : { untilDelegatedWorkSettled: input.untilDelegatedWorkSettled }),+ },);remaining -= chunk;if (!result.timedOut || remaining <= 0) return result;@@ -189,7 +236,13 @@ const make = Effect.gen(function* () {},);- return PeerForwarding.of({ call, waitForThread, links: listLinks });+ return PeerForwarding.of({+ call,+ readThread,+ interruptThread,+ waitForThread,+ links: listLinks,+ });});export const layer = Layer.effect(PeerForwarding, make);diff --git a/apps/server/src/peer/PeerLinks.testkit.ts b/apps/server/src/peer/PeerLinks.testkit.tsindex da9dbc2a1b8..59be493d92d 100644--- a/apps/server/src/peer/PeerLinks.testkit.ts+++ b/apps/server/src/peer/PeerLinks.testkit.ts@@ -152,15 +152,13 @@ export const layerLinkingEnvironment = (descriptor: ExecutionEnvironmentDescriptPeerMcpClient.layer.pipe(Layer.provideMerge(PeerLinks.layer),Layer.provideMerge(Sqlite.layerMemory),- Layer.provide(- Layer.mergeAll(- ServerSecretStore.layer,- FetchHttpClient.layer,- Layer.succeed(ServerEnvironment.ServerEnvironment, {- getEnvironmentId: Effect.succeed(descriptor.environmentId),- getDescriptor: Effect.succeed(descriptor),- }),- ),+ Layer.provide(Layer.mergeAll(ServerSecretStore.layer, FetchHttpClient.layer)),+ // Services that act for this environment, such as delegation, name it too.+ Layer.provideMerge(+ Layer.succeed(ServerEnvironment.ServerEnvironment, {+ getEnvironmentId: Effect.succeed(descriptor.environmentId),+ getDescriptor: Effect.succeed(descriptor),+ }),),Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-here-" })),Layer.provideMerge(NodeServices.layer),diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.tsnew file mode 100644index 00000000000..249a5a90729--- /dev/null+++ b/apps/server/src/peer/RemoteDelegation.test.ts@@ -0,0 +1,1697 @@+import * as DocumentText from "../provider/DocumentText.ts";+import { NodeHttpServer } from "@effect/platform-node";+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";+import * as NodeServices from "@effect/platform-node/NodeServices";+import {+ CommandId,+ EventId,+ MessageId,+ NodeId,+ type OrchestrationV2Run,+ ProjectId,+ ProviderDriverKind,+ ProviderInstanceId,+ ProviderThreadId,+ type Project,+ type RepositoryIdentity,+ RunId,+ ThreadId,+ TurnItemId,+} from "@t3tools/contracts";+import { expect, it } from "@effect/vitest";+import * as Context from "effect/Context";+import * as DateTime from "effect/DateTime";+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 Schedule from "effect/Schedule";+import * as Stream from "effect/Stream";+import * as SubscriptionRef from "effect/SubscriptionRef";+import type * as SqlClient from "effect/sql/SqlClient";+import { McpSchema, McpServer } from "effect/ai";++import * as ServerConfig from "../config.ts";+import * as McpHttpServer from "../mcp/McpHttpServer.ts";+import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";+import { idleThreadProjection, liveThreadShell } from "../mcp/McpToolAccess.testkit.ts";+import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";+import * as EventSink from "../orchestration-v2/EventSink.ts";+import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";+import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";+import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";+import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";+import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";+import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";+import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";+import * as SqlitePersistence from "../persistence/Sqlite.ts";+import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";+import * as ProjectService from "../project/ProjectService.ts";+import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";+import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";+import * as SecretRequests from "../secrets/SecretRequests.ts";+import * as ServerSettings from "../serverSettings.ts";+import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";+import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";+import * as PeerForwarding from "./PeerForwarding.ts";+import * as PeerLinks from "./PeerLinks.ts";+import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";+import * as RemoteDelegation from "./RemoteDelegation.ts";++// The laptop's agent delegates a task to the box through a link. The box is+// its real /mcp behind real OAuth, with one thread the test finishes; the+// laptop is its real orchestrator and toolkits. The parent here wakes as it+// would for a local child.++const laptop = descriptorOf("environment-laptop", "Laptop");+const box = descriptorOf("environment-box", "Box");+const boxProject = ProjectId.make("project:box");+const instanceId = ProviderInstanceId.make("codex");+const driver = ProviderDriverKind.make("codex");+const modelSelection = { instanceId, model: "gpt-5.4" };++type LaunchedWith = Pick<+ ThreadLaunch.ThreadLaunchInput,+ "modelSelection" | "runtimeMode" | "interactionMode"+>;++/** The thread the box launches for the task, which the test finishes. */+interface BoxThread {+ readonly launched: Ref.Ref<ThreadId | null>;+ /** The link session that launched it, as the box stamps it. */+ readonly linkOrigin: Ref.Ref<{ readonly sessionId: string; readonly label: string } | null>;+ /** The parent the launch names, so the thread there can link back to it. */+ readonly delegatedFrom: Ref.Ref<ThreadLaunch.ThreadLaunchInput["delegatedFrom"] | null>;+ /** The model and modes it was launched with. */+ readonly launchedWith: Ref.Ref<LaunchedWith | null>;+ /** The first message the thread there was launched with. */+ readonly message: Ref.Ref<string | null>;+ readonly status: Ref.Ref<OrchestrationV2Run["status"]>;+ readonly reply: Ref.Ref<string | null>;+ readonly error: Ref.Ref<string | null>;+ readonly laterError: Ref.Ref<string | null>;+ /** A later run's reply, after the task's own, as a follow-up message would leave. */+ readonly laterReply: Ref.Ref<string | null>;+ /** The run each wait asked for, in order. */+ readonly waitedFor: Ref.Ref<ReadonlyArray<RunId | undefined>>;+ /** The thread's run ends with a task of its own still running, whose result wakes it again. */+ readonly nested: Ref.Ref<boolean>;+ /** Completed once a wait there blocks on that task. */+ readonly nestedWaiting: Deferred.Deferred<void>;+ /** That task settled and the run it woke answered, with `laterReply`. */+ readonly nestedSettled: Deferred.Deferred<void>;+ /** Waiting there fails with this, as a thread deleted there does. */+ readonly gone: Ref.Ref<boolean>;+ readonly interrupted: Ref.Ref<number>;+ /** What each interrupt or stop there did, once per command id. */+ readonly stops: Ref.Ref<ReadonlyArray<"interrupt" | "thread.stop" | "delegated-tasks">>;+ /** The launch starts no run, as one recorded before its run was kept. */+ readonly runless: Ref.Ref<boolean>;+ /** Completed on the first interrupt there. */+ readonly interruptedOnce: Deferred.Deferred<void>;+ readonly finished: Deferred.Deferred<void>;+ /** While set, reading the thread there waits: completed once a read starts, released by `releaseRead`. */+ readonly holdRead: Ref.Ref<boolean>;+ readonly readStarted: Deferred.Deferred<void>;+ readonly releaseRead: Deferred.Deferred<void>;+ readonly holdFirstStop: Ref.Ref<boolean>;+ readonly stopStarted: Deferred.Deferred<void>;+ readonly releaseStop: Deferred.Deferred<void>;+ /** Messages sent to the thread there after its launch, each starting a later run. */+ readonly sent: Ref.Ref<ReadonlyArray<string>>;+ /** Runs as the launch there is answered, before the laptop hears back. */+ readonly afterLaunch: Ref.Ref<Effect.Effect<void>>;+}++const makeBoxThread = Effect.gen(function* () {+ return {+ launched: yield* Ref.make<ThreadId | null>(null),+ linkOrigin: yield* Ref.make<{ readonly sessionId: string; readonly label: string } | null>(+ null,+ ),+ delegatedFrom: yield* Ref.make<ThreadLaunch.ThreadLaunchInput["delegatedFrom"] | null>(null),+ launchedWith: yield* Ref.make<LaunchedWith | null>(null),+ message: yield* Ref.make<string | null>(null),+ status: yield* Ref.make<OrchestrationV2Run["status"]>("running"),+ reply: yield* Ref.make<string | null>("Working…"),+ error: yield* Ref.make<string | null>(null),+ laterError: yield* Ref.make<string | null>(null),+ laterReply: yield* Ref.make<string | null>(null),+ waitedFor: yield* Ref.make<ReadonlyArray<RunId | undefined>>([]),+ nested: yield* Ref.make(false),+ nestedWaiting: yield* Deferred.make<void>(),+ nestedSettled: yield* Deferred.make<void>(),+ gone: yield* Ref.make(false),+ interrupted: yield* Ref.make(0),+ stops: yield* Ref.make<ReadonlyArray<"interrupt" | "thread.stop" | "delegated-tasks">>([]),+ runless: yield* Ref.make(false),+ interruptedOnce: yield* Deferred.make<void>(),+ finished: yield* Deferred.make<void>(),+ holdRead: yield* Ref.make(false),+ readStarted: yield* Deferred.make<void>(),+ releaseRead: yield* Deferred.make<void>(),+ holdFirstStop: yield* Ref.make(false),+ stopStarted: yield* Deferred.make<void>(),+ releaseStop: yield* Deferred.make<void>(),+ sent: yield* Ref.make<ReadonlyArray<string>>([]),+ afterLaunch: yield* Ref.make<Effect.Effect<void>>(Effect.void),+ } satisfies BoxThread;+});++/** The box's projects: more than a page, with this repository's last. */+const boxProjects: ReadonlyArray<Project> = [+ ...Array.from({ length: 120 }, (_, index) => ({+ id: ProjectId.make(`project:box-other-${index}`),+ title: `other ${index}`,+ workspaceRoot: `/srv/other-${index}`,+ repositoryIdentity: null,+ defaultModelSelection: null,+ scripts: [],+ createdAt: "2026-10-01T00:00:00.000Z",+ updatedAt: "2026-10-01T00:00:00.000Z",+ deletedAt: null,+ })),+ {+ id: boxProject,+ title: "app",+ workspaceRoot: "/srv/app",+ repositoryIdentity: {+ canonicalKey: "github.com/acme/app",+ locator: {+ source: "git-remote",+ remoteName: "origin",+ remoteUrl: "[email protected]:acme/app.git",+ },+ },+ defaultModelSelection: null,+ scripts: [],+ createdAt: "2026-10-01T00:00:00.000Z",+ updatedAt: "2026-10-01T00:00:00.000Z",+ deletedAt: null,+ },+];++const serveBox = (thread: BoxThread) => {+ return servePeer(box, boxToolkitLayer(thread));+};++const boxRunId = RunId.make("run:box");+const boxLaterRunId = RunId.make("run:box-later");++const boxToolkitLayer = (thread: BoxThread) => {+ const runId = boxRunId;+ const interrupts = new Set<string>();+ const shellOf = (threadId: ThreadId) =>+ Effect.gen(function* () {+ if ((yield* Ref.get(thread.launched)) !== threadId) return null;+ const linkOrigin = yield* Ref.get(thread.linkOrigin);+ return {+ ...liveThreadShell(threadId, { runtimeMode: "full-access" }),+ projectId: boxProject,+ ...(linkOrigin === null ? {} : { linkOrigin }),+ };+ });+ const runOf = (status: OrchestrationV2Run["status"]) =>+ ({+ id: runId,+ threadId: ThreadId.make("thread:box"),+ ordinal: 1,+ status,+ modelSelection,+ requestedAt: DateTime.makeUnsafe(0),+ startedAt: DateTime.makeUnsafe(0),+ completedAt: null,+ }) as unknown as OrchestrationV2Run;+ const projectionOf = (threadId: ThreadId) =>+ Effect.gen(function* () {+ const shell = yield* shellOf(threadId);+ const status = yield* Ref.get(thread.status);+ const runless = yield* Ref.get(thread.runless);+ return shell === null+ ? (null as never)+ : { ...idleThreadProjection(shell), runs: runless ? [] : [runOf(status)] };+ });+ // One record per command id, as its receipt replays a repeat.+ const recordStop = (commandId: string, kind: "interrupt" | "thread.stop" | "delegated-tasks") =>+ Effect.gen(function* () {+ if (interrupts.has(`${kind}:${commandId}`)) return;+ interrupts.add(`${kind}:${commandId}`);+ yield* Ref.update(thread.stops, (seen) => [...seen, kind]);+ if (kind !== "delegated-tasks") {+ yield* Ref.update(thread.interrupted, (count) => count + 1);+ yield* Deferred.succeed(thread.interruptedOnce, undefined);+ }+ });+ const layerBoxThreads = Layer.mock(ThreadManagement.ThreadManagementService)({+ getThreadShell: shellOf,+ getProjectThreadRecords: (input) => projectionOf(input.threadId),+ getThreadRecords: (threadId) => projectionOf(threadId),+ waitForThread: (input) =>+ Effect.gen(function* () {+ yield* Ref.update(thread.waitedFor, (seen) => [...seen, input.runId]);+ // A thread with no run has nothing to wait for.+ if (yield* Ref.get(thread.runless)) {+ return { threadId: input.threadId, run: null, timedOut: false };+ }+ if (yield* Ref.get(thread.gone)) {+ return yield* new ThreadManagement.ThreadManagementThreadNotFoundError({+ projectId: boxProject,+ threadId: input.threadId,+ });+ }+ const done = yield* Deferred.await(thread.finished).pipe(+ Effect.timeoutOption(input.timeoutMs),+ );+ // Only a waiter that asks waits past the run for the thread's own task.+ if (+ Option.isSome(done) &&+ input.untilDelegatedWorkSettled === true &&+ (yield* Ref.get(thread.nested))+ ) {+ yield* Deferred.succeed(thread.nestedWaiting, undefined);+ const settled = yield* Deferred.await(thread.nestedSettled).pipe(+ Effect.timeoutOption(input.timeoutMs),+ );+ return {+ threadId: input.threadId,+ run: { id: runId, status: yield* Ref.get(thread.status) } as OrchestrationV2Run,+ timedOut: Option.isNone(settled),+ ...(Option.isSome(settled)+ ? { resultRun: { id: boxLaterRunId, status: "completed" } as OrchestrationV2Run }+ : {}),+ };+ }+ // Unpinned, a wait reports the latest run: a later one once there is one.+ const later = input.runId === undefined && (yield* Ref.get(thread.laterReply)) !== null;+ return {+ threadId: input.threadId,+ run: {+ id: later ? boxLaterRunId : runId,+ status: later ? "completed" : yield* Ref.get(thread.status),+ } as OrchestrationV2Run,+ timedOut: Option.isNone(done),+ };+ }),+ getTimelinePage: (threadId, options) =>+ Effect.gen(function* () {+ if (yield* Ref.get(thread.holdRead)) {+ yield* Deferred.succeed(thread.readStarted, undefined);+ yield* Deferred.await(thread.releaseRead);+ }+ const reply = yield* Ref.get(thread.reply);+ const later = yield* Ref.get(thread.laterReply);+ const error = yield* Ref.get(thread.error);+ const laterError = yield* Ref.get(thread.laterError);+ // One item per page, with errors available only in the activity view.+ const replies = [+ ...(reply === null+ ? []+ : [+ {+ id: TurnItemId.make("item:reply"),+ runId,+ text: reply,+ type: "assistant_message",+ },+ ]),+ ...(error === null+ ? []+ : [{ id: TurnItemId.make("item:error"), runId, text: error, type: "error" }]),+ ...(later === null+ ? []+ : [+ {+ id: TurnItemId.make("item:later-reply"),+ runId: boxLaterRunId,+ text: later,+ type: "assistant_message",+ },+ ]),+ ...(laterError === null+ ? []+ : [+ {+ id: TurnItemId.make("item:later-error"),+ runId: boxLaterRunId,+ text: laterError,+ type: "error",+ },+ ]),+ ].map((entry, position) => ({ ...entry, position }));+ const visible =+ options.itemId === undefined+ ? replies.filter(+ (entry) => options.view === "activity" || entry.type === "assistant_message",+ )+ : replies.filter((entry) => entry.id === options.itemId);+ const matching = visible+ .filter((entry) => entry.position > (options.afterPosition ?? -1))+ .slice(0, 1);+ return {+ items: matching.map(({ id, runId: itemRunId, text, position, type }) => ({+ position,+ visibility: "local" as const,+ sourceThreadId: threadId,+ sourceItemId: id,+ item: {+ id,+ threadId,+ runId: itemRunId,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 1,+ status: "completed" as const,+ title: null,+ startedAt: DateTime.makeUnsafe(0),+ completedAt: DateTime.makeUnsafe(0),+ updatedAt: DateTime.makeUnsafe(0),+ ...(type === "error"+ ? { type, failure: { message: text } }+ : {+ type: "assistant_message" as const,+ messageId: MessageId.make(`message:${id}`),+ text,+ streaming: false,+ }),+ } as never,+ })),+ totalItems: replies.length,+ hasMore:+ options.itemId === undefined &&+ matching.length > 0 &&+ visible.some((entry) => entry.position > matching.at(-1)!.position),+ };+ }),+ interruptThread: (input) =>+ recordStop(input.commandId, "interrupt").pipe(+ Effect.as({ type: "interrupt_requested", run: runOf("running") } as never),+ ),+ dispatch: (command) =>+ command.type === "thread.stop"+ ? recordStop(command.commandId, "thread.stop").pipe(+ Effect.tap(() =>+ Effect.gen(function* () {+ if (!(yield* Ref.getAndSet(thread.holdFirstStop, false))) return;+ yield* Deferred.succeed(thread.stopStarted, undefined);+ yield* Deferred.await(thread.releaseStop);+ }),+ ),+ Effect.as({ sequence: 0, storedEvents: [] } as never),+ )+ : Effect.die(`The box does not expect ${command.type}`),+ stopDelegatedTasks: (input) => recordStop(input.commandId, "delegated-tasks"),+ sendToThread: (input) =>+ Ref.update(thread.sent, (seen) => [...seen, input.text]).pipe(+ Effect.as({+ run: { id: boxLaterRunId, status: "running" },+ delivery: "started",+ } as never),+ ),+ });+ const layerBoxLaunches = Layer.mock(ThreadLaunch.ThreadLaunchService)({+ launch: (input) =>+ Ref.get(thread.runless).pipe(+ Effect.flatMap((runless) =>+ Ref.set(thread.launched, input.threadId!).pipe(+ Effect.andThen(Ref.set(thread.linkOrigin, input.linkOrigin ?? null)),+ Effect.andThen(Ref.set(thread.delegatedFrom, input.delegatedFrom ?? null)),+ Effect.andThen(Ref.set(thread.message, input.initialMessage?.text ?? null)),+ Effect.andThen(+ Ref.set(thread.launchedWith, {+ modelSelection: input.modelSelection,+ runtimeMode: input.runtimeMode,+ interactionMode: input.interactionMode,+ }),+ ),+ Effect.andThen(Effect.flatten(Ref.get(thread.afterLaunch))),+ Effect.as({+ threadId: input.threadId,+ projection: {+ thread: {+ id: input.threadId,+ projectId: input.projectId,+ title: input.title,+ modelSelection: input.modelSelection,+ },+ runs:+ input.initialMessage?.messageId && !runless+ ? [+ {+ id: runId,+ status: "running",+ userMessageId: input.initialMessage.messageId,+ },+ ]+ : [],+ },+ resumed: false,+ } as unknown as ThreadLaunch.ThreadLaunchResult),+ ),+ ),+ ),+ });+ return Layer.merge(+ McpHttpServer.layerOrchestratorToolkit,+ McpHttpServer.layerProjectRegistration,+ ).pipe(+ Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),+ Layer.provide(NodeCrypto.layer),+ Layer.provide(layerBoxThreads),+ Layer.provide(layerBoxLaunches),+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),+ Layer.provide(+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/p" }),+ ),+ Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),+ Layer.provide(Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({})),+ Layer.provide(+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-remote-delegation-box-" }).pipe(+ Layer.provide(NodeServices.layer),+ ),+ ),+ Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),+ Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),+ Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),+ Layer.provide(+ Layer.mock(ProjectService.ProjectService)({+ getById: () => Effect.succeedNone,+ // More than a page, so finding the project with this repository pages.+ listPage: ({ cursor, limit }) =>+ Effect.succeed({+ projects: boxProjects.slice(cursor, cursor + limit),+ nextCursor: cursor + limit < boxProjects.length ? cursor + limit : null,+ }),+ }),+ ),+ Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),+ Layer.provide(ServerSettings.layerTest()),+ Layer.provide(NodeServices.layer),+ );+};++const mcpClient = McpSchema.McpServerClient.of({+ clientId: 1,+ protocolVersion: "2025-06-18",+ clientCapabilities: {},+ clientInfo: { name: "remote-delegation", version: "1" },+ initializePayload: {+ protocolVersion: "2025-06-18",+ capabilities: {},+ clientInfo: { name: "remote-delegation", version: "1" },+ },+ getClient: Effect.die("unused"),+});++const adapter = {+ instanceId,+ driver,+ getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),+ openSession: () => Effect.die("No provider process needed"),+} as ProviderAdapter.ProviderAdapterV2["Service"];++/**+ * The laptop: a real orchestrator (in-memory SQLite) whose parent thread has+ * a live run, the real orchestrator toolkit, and RemoteDelegation. Built in+ * its own scope so a test can tear it down and build it again on the same+ * database, as a restart does.+ */+const makeLaptop = (+ database: Context.Context<SqlClient.SqlClient>,+ offers: SubscriptionRef.SubscriptionRef<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >,+ /** The laptop's links from before a restart, which keep their sessions there. */+ kept?: Context.Context<Layer.Success<ReturnType<typeof layerLinkingEnvironment>>>,+) =>+ Effect.gen(function* () {+ const linking = kept ?? (yield* layerLinkingEnvironment(laptop).pipe(Layer.build));+ const layerDatabase = Layer.succeedContext(database);+ const layerOrchestrator = Layer.mergeAll(+ layerDatabase,+ ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),+ ProviderReplayHarness.layerWithRegistry(+ { name: "remote-delegation-laptop" },+ ProviderAdapterRegistry.layerFromAdapters([adapter]),+ { databaseLayer: layerDatabase, runEffectWorker: false },+ ),+ ).pipe(+ Layer.provide(+ Layer.succeed(ProviderContinuationRequests.ProviderContinuationRequests, {+ offer: (request) => SubscriptionRef.update(offers, (seen) => [...seen, request]),+ take: Effect.never,+ }),+ ),+ );+ const layerThreads = ThreadManagement.layer.pipe(+ Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),+ Layer.provideMerge(Layer.merge(layerOrchestrator, ServerSettings.layerTest())),+ );+ const layerHere = McpHttpServer.layerOrchestratorToolkit.pipe(+ Layer.provideMerge(McpServer.McpServer.layer),+ Layer.provideMerge(+ RemoteDelegation.layer.pipe(+ Layer.provideMerge(PeerForwarding.layer),+ Layer.provide(+ Layer.mock(ProjectService.ProjectService)({+ // A cold enrichment cache: the project itself reports no identity yet.+ getById: () =>+ Effect.succeedSome({+ workspaceRoot: "/home/me/app",+ repositoryIdentity: null,+ } as never),+ }),+ ),+ Layer.provide(+ Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({+ resolve: (cwd) =>+ Effect.succeed(+ cwd === "/home/me/app"+ ? ({ canonicalKey: "github.com/acme/app" } as RepositoryIdentity)+ : null,+ ),+ }),+ ),+ ),+ ),+ Layer.provide(Layer.succeedContext(linking)),+ Layer.provide(NodeCrypto.layer),+ Layer.provideMerge(layerThreads),+ Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),+ Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),+ Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),+ Layer.provide(Layer.mock(ProjectService.ProjectService)({})),+ Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),+ Layer.provide(Layer.mock(ThreadLaunch.ThreadLaunchService)({})),+ Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),+ Layer.fresh,+ );+ const here = yield* Layer.build(layerHere);+ const server = Context.get(here, McpServer.McpServer);+ return {+ links: Context.get(linking, PeerLinks.PeerLinks),+ orchestrator: Context.get(here, Orchestrator.OrchestratorV2),+ remote: Context.get(here, RemoteDelegation.RemoteDelegation),+ threads: Context.get(here, ThreadManagement.ThreadManagementService),+ projections: Context.get(here, ProjectionStore.ProjectionStoreV2),+ sink: Context.get(here, EventSink.EventSinkV2),+ call: (name: string, args: Record<string, unknown>, scope = parentScope) =>+ server+ .callTool({ name, arguments: args })+ .pipe(+ Effect.provideService(McpInvocationContext.McpInvocationContext, scope),+ Effect.provideService(McpSchema.McpServerClient, mcpClient),+ ),+ };+ });++const parentThreadId = ThreadId.make("thread:laptop-parent");+const parentRunId = RunId.make("run:laptop-parent");+const parentRootNode = NodeId.make("node:laptop-parent:root");+const parentScope: McpInvocationContext.McpInvocationScope = {+ environmentId: laptop.environmentId,+ requestNamespace: "provider-session:laptop-parent",+ thread: {+ threadId: parentThreadId,+ providerSessionId: "provider-session:laptop-parent",+ providerInstanceId: instanceId,+ },+ client: undefined,+ capabilities: new Set(["orchestration"]),+ issuedAt: 1,+};++/** The laptop's parent thread, mid-turn when its agent delegates. */+const seedParent = (laptopEnv: Effect.Success<ReturnType<typeof makeLaptop>>) =>+ Effect.gen(function* () {+ const now = yield* DateTime.now;+ const providerThreadId = ProviderThreadId.make("provider-thread:laptop-parent");+ yield* laptopEnv.orchestrator.dispatch({+ type: "thread.create",+ createdBy: "user",+ creationSource: "web",+ commandId: CommandId.make("command:create:laptop-parent"),+ threadId: parentThreadId,+ projectId: ProjectId.make("project:laptop"),+ title: "Laptop parent",+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ });+ yield* laptopEnv.sink.write({+ commandId: CommandId.make("command:seed:laptop-parent"),+ events: [+ {+ id: EventId.make("event:seed-provider-thread:laptop-parent"),+ type: "provider-thread.updated",+ threadId: parentThreadId,+ driver,+ providerInstanceId: instanceId,+ occurredAt: now,+ payload: {+ id: providerThreadId,+ driver,+ providerInstanceId: instanceId,+ providerSessionId: null,+ appThreadId: parentThreadId,+ ownerNodeId: parentRootNode,+ nativeThreadRef: { driver, nativeId: "native:laptop-parent", strength: "strong" },+ nativeConversationHeadRef: null,+ status: "active",+ firstRunOrdinal: 1,+ lastRunOrdinal: 1,+ handoffIds: [],+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ },+ },+ {+ id: EventId.make("event:seed-node:laptop-parent"),+ type: "node.updated",+ threadId: parentThreadId,+ runId: parentRunId,+ nodeId: parentRootNode,+ driver,+ providerInstanceId: instanceId,+ occurredAt: now,+ payload: {+ id: parentRootNode,+ threadId: parentThreadId,+ runId: parentRunId,+ parentNodeId: null,+ rootNodeId: parentRootNode,+ kind: "root_turn",+ status: "running",+ countsForRun: true,+ providerThreadId,+ providerTurnId: null,+ nativeItemRef: null,+ runtimeRequestId: null,+ checkpointScopeId: null,+ startedAt: now,+ completedAt: null,+ },+ },+ {+ id: EventId.make("event:seed-run:laptop-parent"),+ type: "run.updated",+ threadId: parentThreadId,+ runId: parentRunId,+ nodeId: parentRootNode,+ providerInstanceId: instanceId,+ occurredAt: now,+ payload: {+ id: parentRunId,+ threadId: parentThreadId,+ ordinal: 1,+ providerInstanceId: instanceId,+ modelSelection,+ providerThreadId,+ userMessageId: MessageId.make("message:seed-user:laptop-parent"),+ rootNodeId: parentRootNode,+ activeAttemptId: null,+ status: "running",+ requestedAt: now,+ startedAt: now,+ completedAt: null,+ checkpointId: null,+ contextHandoffId: null,+ },+ },+ ],+ });+ });++const delegateToBox = (laptopEnv: Effect.Success<ReturnType<typeof makeLaptop>>) =>+ laptopEnv+ .call("delegate_task", {+ task: "Run the full suite on the box.",+ target: {+ environmentId: box.environmentId,+ providerInstanceId: instanceId,+ model: "gpt-5.4",+ },+ mode: "async",+ clientRequestId: "suite-on-box",+ })+ .pipe(+ Effect.map((result) => {+ expect(result.isError, JSON.stringify(result.content)).toBe(false);+ return result.structuredContent as {+ taskId: NodeId;+ status: string;+ childThreadId: null;+ remoteChild: { environmentId: string; threadId: ThreadId; label: string };+ };+ }),+ );++/** Waits until the task here has the result its thread there ended with. */+const taskResult = (laptopEnv: Effect.Success<ReturnType<typeof makeLaptop>>, taskId: NodeId) =>+ laptopEnv.orchestrator+ .streamStoredEventsFrom({+ threadId: parentThreadId,+ afterSequence: 0,+ eventType: "subagent.updated",+ })+ .pipe(+ Stream.filter(+ (stored) =>+ stored.event.type === "subagent.updated" &&+ stored.event.payload.id === taskId &&+ stored.event.payload.result !== null,+ ),+ Stream.runHead,+ Effect.map((stored) =>+ Option.isSome(stored) && stored.value.event.type === "subagent.updated"+ ? stored.value.event.payload+ : undefined,+ ),+ );++it.effect("a task delegated to the box wakes the laptop's parent when it ends there", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);++ const delegated = yield* delegateToBox(a);+ expect(delegated).toMatchObject({+ status: "running",+ childThreadId: null,+ remoteChild: { environmentId: box.environmentId, label: "Box" },+ });+ // The box launched it in the project with the same repository.+ expect(yield* Ref.get(thread.launched)).toBe(delegated.remoteChild.threadId);+ // ...naming the parent here, so the thread there links back to it.+ expect(yield* Ref.get(thread.delegatedFrom)).toEqual({+ environmentId: laptop.environmentId,+ threadId: parentThreadId,+ title: "Laptop parent",+ });+ // A retry with the same key launches nothing new and records nothing new.+ const retried = yield* delegateToBox(a);+ expect(retried.taskId).toBe(delegated.taskId);+ expect((yield* a.orchestrator.getThreadProjection(parentThreadId)).subagents).toHaveLength(1);++ yield* Ref.set(thread.reply, "All 412 tests pass on the box.");+ yield* Ref.set(thread.status, "completed");+ yield* Deferred.succeed(thread.finished, undefined);+ const task = yield* taskResult(a, delegated.taskId);+ expect(task).toMatchObject({ status: "completed", result: "All 412 tests pass on the box." });+ // The parent's live run claims the result, as for a child here.+ const parentRun = (yield* a.orchestrator.getThreadProjection(parentThreadId)).runs.find(+ (run) => run.id === parentRunId,+ );+ expect(parentRun?.delegatedCompletion?.delivery?.taskIds).toEqual([delegated.taskId]);+ // The wake is offered after the result commits, so the result can be seen first.+ const offered = yield* SubscriptionRef.changes(offers).pipe(+ Stream.filter((seen) => seen.some((offer) => offer.threadId === parentThreadId)),+ Stream.runHead,+ );+ expect(Option.isSome(offered)).toBe(true);++ const status = yield* a.call("task_status", { taskId: delegated.taskId });+ expect(status.structuredContent).toMatchObject({+ status: "completed",+ summary: "All 412 tests pass on the box.",+ });+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("a task named only by environment inherits the parent's model, within the link", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ // The parent runs with full access; the link allows less.+ yield* linkTo(a.links, b, "auto-accept-edits");+ yield* seedParent(a);++ const result = yield* a.call("delegate_task", {+ task: "Run the suite on the box.",+ target: { environmentId: box.environmentId },+ });+ expect(result.isError, JSON.stringify(result.content)).toBe(false);+ // The parent's model, and the link's modes rather than the parent's.+ expect(yield* Ref.get(thread.launchedWith)).toEqual({+ modelSelection,+ runtimeMode: "auto-accept-edits",+ interactionMode: "default",+ });++ // Asking for more than the link allows is still refused there.+ const broader = yield* a.call("delegate_task", {+ task: "Run the suite on the box.",+ target: { environmentId: box.environmentId },+ runtimeMode: "full-access",+ clientRequestId: "broader",+ });+ expect(broader.isError).toBe(true);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("refuses worktree isolation for a task there before launching anything", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "auto");+ yield* seedParent(a);++ const result = yield* a.call("delegate_task", {+ task: "Run the suite on the box.",+ target: { environmentId: box.environmentId },+ isolation: "worktree",+ });+ expect(result.isError).toBe(true);+ expect(JSON.stringify(result.content)).toContain("isolation");+ expect(yield* Ref.get(thread.launched)).toBeNull();+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("follows an open task again after the laptop restarts", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ // The laptop before the restart delegates, then goes away.+ const delegated = yield* Effect.scoped(+ Effect.gen(function* () {+ const before = yield* makeLaptop(database, offers);+ yield* linkTo(before.links, b, "full-access");+ yield* seedParent(before);+ return yield* delegateToBox(before);+ }),+ );+ // The task finishes on the box while the laptop is down.+ yield* Ref.set(thread.reply, "Finished while you were away.");+ yield* Ref.set(thread.status, "completed");+ yield* Deferred.succeed(thread.finished, undefined);++ const after = yield* makeLaptop(database, offers);+ // The link lives in the laptop's own store, so it needs linking again here.+ yield* linkTo(after.links, b, "full-access");+ yield* after.remote.start();+ const task = yield* taskResult(after, delegated.taskId);+ expect(task).toMatchObject({ status: "completed", result: "Finished while you were away." });+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("fails the task when the box revokes the link, and cancel interrupts it there", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);++ const cancelled = yield* delegateToBox(a);+ const cancel = yield* a.call("task_cancel", {+ taskId: cancelled.taskId,+ reason: "Not needed",+ });+ expect(cancel.structuredContent).toEqual({+ taskId: cancelled.taskId,+ status: "cancel_requested",+ });+ // Cancelling stops the thread there as Stop does: its queue and its own tasks too.+ expect(yield* Ref.get(thread.stops)).toEqual(["thread.stop", "delegated-tasks"]);+ expect(yield* taskResult(a, cancelled.taskId)).toMatchObject({ status: "cancelled" });++ // Cancelling again, once the result is in, still stops what came after it there.+ const again = yield* a.call("task_cancel", {+ taskId: cancelled.taskId,+ clientRequestId: "cancel-again",+ });+ expect(again.structuredContent).toEqual({ taskId: cancelled.taskId, status: "cancelled" });+ expect(yield* Ref.get(thread.interrupted)).toBe(2);+ // ...and a retry of that cancel stops nothing new.+ yield* a.call("task_cancel", { taskId: cancelled.taskId, clientRequestId: "cancel-again" });+ expect(yield* Ref.get(thread.interrupted)).toBe(2);++ // A second task, then the box revokes the link before it ends.+ const revoked = yield* a+ .call("delegate_task", {+ task: "Another one.",+ target: {+ environmentId: box.environmentId,+ providerInstanceId: instanceId,+ model: "gpt-5.4",+ },+ clientRequestId: "second",+ })+ .pipe(Effect.map((result) => result.structuredContent as { taskId: NodeId }));+ const [session] = yield* b.linkedSessions;+ yield* b.auth.revokeSession(session!.sessionId);+ yield* Deferred.succeed(thread.finished, undefined);+ const failed = yield* taskResult(a, revoked.taskId);+ expect(failed?.status).toBe("failed");+ expect(failed?.result).toBe(+ "The linked environment no longer accepts this link. It may have been revoked there; link it again.",+ );+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("a task's result is its own run's whole last reply, not a later run's", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);++ const result = yield* a.call("delegate_task", {+ task: "Review the diff.",+ role: "review",+ target: { environmentId: box.environmentId },+ clientRequestId: "review-on-box",+ });+ expect(result.isError, JSON.stringify(result.content)).toBe(false);+ const { taskId } = result.structuredContent as { taskId: NodeId };+ // The role reaches the thread there, as it does a child here.+ expect(yield* Ref.get(thread.message)).toBe(+ "Act as the review sub-agent for this task.\n\nReview the diff.",+ );++ // A reply longer than one read, then a later run's reply on the same thread.+ const long = "x".repeat(45_000);+ yield* Ref.set(thread.reply, long);+ yield* Ref.set(thread.laterReply, "Someone else asked a follow-up.");+ yield* Ref.set(thread.status, "completed");+ yield* Deferred.succeed(thread.finished, undefined);+ const task = yield* taskResult(a, taskId);+ expect(task?.status).toBe("completed");+ expect(task?.result).toBe(long);+ // Every wait was for the run the launch started.+ const waits = yield* Ref.get(thread.waitedFor);+ expect(waits.length).toBeGreaterThan(0);+ expect(waits.every((runId) => runId === boxRunId)).toBe(true);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("a task whose thread there waits on its own task ends with the answer after it", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);+ const delegated = yield* delegateToBox(a);++ // The task's run there ends after delegating a review of its own.+ yield* Ref.set(thread.nested, true);+ yield* Ref.set(thread.reply, "Started a review; I will answer when it reports.");+ yield* Ref.set(thread.status, "completed");+ yield* Deferred.succeed(thread.finished, undefined);+ const first = yield* Effect.raceFirst(+ Deferred.await(thread.nestedWaiting).pipe(Effect.as("waiting there" as const)),+ taskResult(a, delegated.taskId).pipe(Effect.as("completed here" as const)),+ );+ expect(first).toBe("waiting there");++ // The review reports and wakes the thread there, whose next run answers.+ yield* Ref.set(thread.laterReply, "The review found two issues; both are fixed.");+ yield* Deferred.succeed(thread.nestedSettled, undefined);+ expect(yield* taskResult(a, delegated.taskId)).toMatchObject({+ status: "completed",+ result: "The review found two issues; both are fixed.",+ });+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("the same key from another provider session is another task", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);++ const first = yield* delegateToBox(a);+ const later = yield* a.call(+ "delegate_task",+ {+ task: "Run the full suite on the box.",+ target: { environmentId: box.environmentId },+ clientRequestId: "suite-on-box",+ },+ { ...parentScope, requestNamespace: "provider-session:laptop-parent-2" },+ );+ expect(later.isError, JSON.stringify(later.content)).toBe(false);+ const second = later.structuredContent as {+ taskId: NodeId;+ remoteChild: { threadId: ThreadId };+ };+ expect(second.taskId).not.toBe(first.taskId);+ expect(second.remoteChild.threadId).not.toBe(first.remoteChild.threadId);+ expect((yield* a.orchestrator.getThreadProjection(parentThreadId)).subagents).toHaveLength(2);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect.each([null, "Working before the provider failed."])(+ "reports the failed remote run's error instead of its earlier reply (%s)",+ (reply) =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);+ const delegated = yield* delegateToBox(a);+ yield* Ref.set(thread.reply, reply);+ const error = "Provider failed: authentication expired on the destination.";+ yield* Ref.set(thread.error, error);+ yield* Ref.set(thread.status, "failed");+ yield* Deferred.succeed(thread.finished, undefined);+ expect(yield* taskResult(a, delegated.taskId)).toMatchObject({+ status: "failed",+ result: error,+ });+ const status = yield* a.call("task_status", { taskId: delegated.taskId });+ expect(status.structuredContent).toMatchObject({+ status: "failed",+ summary: error,+ latestTerminalSummary: error,+ });+ const offered = yield* SubscriptionRef.changes(offers).pipe(+ Stream.filter((seen) => seen.some((offer) => offer.threadId === parentThreadId)),+ Stream.runHead,+ );+ expect(Option.isSome(offered)).toBe(true);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect.each([false, true])(+ "ignores later-run errors and reads the failed run's full error (ownError=%s)",+ (ownError) =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);+ const delegated = yield* delegateToBox(a);+ yield* Ref.set(thread.reply, null);+ const error = `Provider failed: ${"detail ".repeat(10_000)}end of error.`;+ if (ownError) yield* Ref.set(thread.error, error);+ yield* Ref.set(thread.laterReply, "A later user run answered.");+ yield* Ref.set(thread.laterError, "Another run's provider error.");+ yield* Ref.set(thread.status, "failed");+ yield* Deferred.succeed(thread.finished, undefined);+ expect(yield* taskResult(a, delegated.taskId)).toMatchObject({+ status: "failed",+ result: ownError+ ? error+ : "(The thread in the linked environment ended without a reply.)",+ });+ expect(yield* Ref.get(thread.waitedFor)).toEqual([boxRunId]);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("keeps a successful remote reply despite an error item in the run's activity", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);+ const delegated = yield* delegateToBox(a);+ yield* Ref.set(thread.reply, "Recovered and completed the task.");+ yield* Ref.set(thread.error, "A recoverable tool error.");+ yield* Ref.set(thread.status, "completed");+ yield* Deferred.succeed(thread.finished, undefined);+ expect(yield* taskResult(a, delegated.taskId)).toMatchObject({+ status: "completed",+ result: "Recovered and completed the task.",+ });+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("fails the task when its thread there is gone, or the link here is", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);++ yield* Ref.set(thread.gone, true);+ const gone = yield* delegateToBox(a);+ const failed = yield* taskResult(a, gone.taskId);+ expect(failed?.status).toBe("failed");+ expect(failed?.result).toContain("was not found");++ // The link is forgotten here while the task runs there.+ yield* Ref.set(thread.gone, false);+ const forgotten = yield* a+ .call("delegate_task", {+ task: "Another one.",+ target: { environmentId: box.environmentId },+ clientRequestId: "forgotten",+ })+ .pipe(Effect.map((result) => result.structuredContent as { taskId: NodeId }));+ yield* a.links.unlink(box.environmentId);+ yield* Ref.set(thread.status, "completed");+ yield* Deferred.succeed(thread.finished, undefined);+ const unlinked = yield* taskResult(a, forgotten.taskId);+ expect(unlinked?.status).toBe("failed");+ expect(unlinked?.result).toContain("not linked to");+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("cancel ends the task here even when the link is gone", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);++ const delegated = yield* delegateToBox(a);+ yield* a.links.unlink(box.environmentId);+ const cancel = yield* a.call("task_cancel", { taskId: delegated.taskId });+ expect(cancel.structuredContent).toEqual({+ taskId: delegated.taskId,+ status: "cancel_requested",+ });+ const task = yield* taskResult(a, delegated.taskId);+ expect(task?.status).toBe("cancelled");+ expect(task?.result).toContain("could not be stopped in Box");+ expect(yield* Ref.get(thread.interrupted)).toBe(0);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("a parent stopped while the task's result is read still stops its thread there", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);+ const delegated = yield* delegateToBox(a);++ // The task's run ends there, and while the follower reads its reply,+ // the parent here is stopped: more work may follow that run there.+ yield* Ref.set(thread.holdRead, true);+ yield* Ref.set(thread.reply, "Done there.");+ yield* Ref.set(thread.status, "completed");+ yield* Deferred.succeed(thread.finished, undefined);+ yield* Deferred.await(thread.readStarted);+ yield* a.threads.stopDelegatedTasks({+ threadId: parentThreadId,+ commandId: CommandId.make("command:stop:laptop-parent-mid-read"),+ });+ yield* Deferred.succeed(thread.releaseRead, undefined);++ // The Stop's result stands, and the thread there is still stopped.+ expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ status: "interrupted" });+ yield* Deferred.await(thread.interruptedOnce);+ expect(yield* Ref.get(thread.stops)).toContain("thread.stop");+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("a stop the box refuses because the parent was lowered ends instead of retrying", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);+ const delegated = yield* delegateToBox(a);++ // The parent is lowered below the full-access thread there, then stopped.+ yield* a.orchestrator.dispatch({+ type: "thread.runtime-mode.set",+ commandId: CommandId.make("command:lower:laptop-parent"),+ threadId: parentThreadId,+ runtimeMode: "approval-required",+ });+ yield* a.threads.stopDelegatedTasks({+ threadId: parentThreadId,+ commandId: CommandId.make("command:stop:laptop-parent-lowered"),+ });++ // The box refuses that stop; the follower records it as settled and+ // stops, so nothing retries it, now or after a restart.+ const settled = yield* a.orchestrator+ .streamStoredEventsFrom({+ threadId: parentThreadId,+ afterSequence: 0,+ eventType: "subagent.updated",+ })+ .pipe(+ Stream.filter(+ (stored) =>+ stored.event.type === "subagent.updated" &&+ stored.event.payload.id === delegated.taskId &&+ stored.event.payload.remoteChild?.stoppedThere === true,+ ),+ Stream.runHead,+ );+ expect(Option.isSome(settled)).toBe(true);+ expect(yield* Ref.get(thread.stops)).toEqual([]);+ expect(yield* a.projections.getOpenRemoteDelegatedTasks).toEqual([]);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("stopping the parent stops its task there", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);++ const delegated = yield* delegateToBox(a);+ // What the delegated-tasks.stop effect runs once the parent's Stop commits.+ yield* a.threads.stopDelegatedTasks({+ threadId: parentThreadId,+ commandId: CommandId.make("command:stop:laptop-parent"),+ reason: "User stopped",+ });+ expect(yield* taskResult(a, delegated.taskId)).toMatchObject({+ status: "interrupted",+ result: "Stopped with its parent: User stopped",+ });+ // The follower sees it ended here and stops it there.+ yield* Deferred.await(thread.interruptedOnce);+ expect(yield* Ref.get(thread.interrupted)).toBe(1);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++/** A follower retry schedule the test steps: each failed attempt is offered, then waits for `retry`. */+const steppedRetries = Effect.gen(function* () {+ const failed = yield* Queue.unbounded<void>();+ const retry = yield* Queue.unbounded<void>();+ const schedule = Schedule.forever.pipe(+ Schedule.tap(() => Queue.offer(failed, undefined).pipe(Effect.andThen(Queue.take(retry)))),+ );+ return { failed, retry, schedule };+});++/** Waits until the task here records that the `stopCount`th Stop after its result reached there. */+const stoppedThere = (+ laptopEnv: Effect.Success<ReturnType<typeof makeLaptop>>,+ taskId: NodeId,+ // `null` for a cancel's stop, which carries no count.+ stopCount: number | null = 1,+) =>+ laptopEnv.orchestrator+ .streamStoredEventsFrom({+ threadId: parentThreadId,+ afterSequence: 0,+ eventType: "subagent.updated",+ })+ .pipe(+ Stream.filter(+ (stored) =>+ stored.event.type === "subagent.updated" &&+ stored.event.payload.id === taskId &&+ stored.event.payload.remoteChild?.stoppedThere === true &&+ stored.event.payload.remoteChild.stopCount === (stopCount ?? undefined),+ ),+ Stream.runHead,+ Effect.map((stored) =>+ Option.isSome(stored) && stored.value.event.type === "subagent.updated"+ ? stored.value.event.payload+ : undefined,+ ),+ );++it.effect("stopping the parent stops follow-up work on a task there that has its result", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* a.remote.start();+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);+ const delegated = yield* delegateToBox(a);+ yield* Ref.set(thread.reply, "All green.");+ yield* Ref.set(thread.status, "completed");+ yield* Deferred.succeed(thread.finished, undefined);+ expect(yield* taskResult(a, delegated.taskId)).toMatchObject({+ status: "completed",+ result: "All green.",+ });++ // The parent sends the thread there a follow-up, which starts a run there.+ const sent = yield* a.call("t3_thread_send", {+ environmentId: box.environmentId,+ threadId: delegated.remoteChild.threadId,+ message: "Now run the slow suite too.",+ });+ expect(sent.isError, JSON.stringify(sent.content)).toBe(false);+ expect(yield* Ref.get(thread.sent)).toEqual(["Now run the slow suite too."]);+ expect(yield* Ref.get(thread.interrupted)).toBe(0);++ yield* a.threads.stopDelegatedTasks({+ threadId: parentThreadId,+ commandId: CommandId.make("command:stop:laptop-parent-after-result"),+ });+ // The thread there is stopped as Stop does, and the task keeps its result.+ const task = yield* stoppedThere(a, delegated.taskId);+ expect(yield* Ref.get(thread.stops)).toEqual(["thread.stop", "delegated-tasks"]);+ expect(task).toMatchObject({ status: "completed", result: "All green." });+ expect(yield* a.projections.getOpenRemoteDelegatedTasks).toEqual([]);++ // A second Stop owes a second stop there, not a replay of the first.+ yield* a.threads.stopDelegatedTasks({+ threadId: parentThreadId,+ commandId: CommandId.make("command:stop:laptop-parent-again"),+ });+ expect(yield* stoppedThere(a, delegated.taskId, 2)).toMatchObject({ status: "completed" });+ expect(yield* Ref.get(thread.interrupted)).toBe(2);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("a delayed Stop acknowledgement leaves a newer Stop owed", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* a.remote.start();+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);+ const delegated = yield* delegateToBox(a);+ yield* Ref.set(thread.reply, "All green.");+ yield* Ref.set(thread.status, "completed");+ yield* Deferred.succeed(thread.finished, undefined);+ yield* taskResult(a, delegated.taskId);++ yield* Ref.set(thread.holdFirstStop, true);+ yield* a.threads.stopDelegatedTasks({+ threadId: parentThreadId,+ commandId: CommandId.make("command:stop:delayed-first"),+ });+ yield* Deferred.await(thread.stopStarted);+ // Work starts after the first Stop landed there, but before its acknowledgement returns.+ yield* a.call("t3_thread_send", {+ environmentId: box.environmentId,+ threadId: delegated.remoteChild.threadId,+ message: "Run another check.",+ });+ yield* a.threads.stopDelegatedTasks({+ threadId: parentThreadId,+ commandId: CommandId.make("command:stop:delayed-second"),+ });+ const pending = yield* a.threads.getThreadRecords(parentThreadId, ["subagents"]);+ expect(+ pending.subagents.find((task) => task.id === delegated.taskId)?.remoteChild,+ ).toMatchObject({ stoppedThere: false, stopCount: 2 });+ yield* Deferred.succeed(thread.releaseStop, undefined);+ expect(yield* stoppedThere(a, delegated.taskId, 2)).toMatchObject({+ status: "completed",+ result: "All green.",+ });+ expect(yield* Ref.get(thread.interrupted)).toBe(2);+ expect(yield* a.projections.getOpenRemoteDelegatedTasks).toEqual([]);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("a Stop on a task that has its result reaches there after a restart", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);+ // The laptop records the Stop, then goes away before its follower sends it.+ const delegated = yield* Effect.scoped(+ Effect.gen(function* () {+ const before = yield* makeLaptop(database, offers, linking);+ yield* linkTo(before.links, b, "full-access");+ yield* seedParent(before);+ const task = yield* delegateToBox(before);+ yield* Ref.set(thread.status, "completed");+ yield* Deferred.succeed(thread.finished, undefined);+ yield* taskResult(before, task.taskId);+ yield* before.threads.stopDelegatedTasks({+ threadId: parentThreadId,+ commandId: CommandId.make("command:stop:laptop-parent-before-restart"),+ });+ return task;+ }),+ );+ expect(yield* Ref.get(thread.interrupted)).toBe(0);++ const after = yield* makeLaptop(database, offers, linking);+ expect(yield* after.projections.getOpenRemoteDelegatedTasks).toEqual([+ { parentThreadId, taskId: delegated.taskId },+ ]);+ yield* after.remote.start();+ expect(yield* stoppedThere(after, delegated.taskId)).toMatchObject({ status: "completed" });+ expect(yield* Ref.get(thread.stops)).toEqual(["thread.stop", "delegated-tasks"]);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("a parent stopped while the box is unreachable still stops its task there", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const retries = yield* steppedRetries;+ const a = yield* makeLaptop(database, offers).pipe(+ Effect.provideService(RemoteDelegation.FollowRetrySchedule, retries.schedule),+ );+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);+ // The box sleeps as soon as the task is there, so its follower's first attempt fails.+ yield* Ref.set(+ thread.afterLaunch,+ Ref.set(b.descriptor, descriptorOf("environment-elsewhere", "Elsewhere")),+ );+ const delegated = yield* delegateToBox(a);+ yield* Queue.take(retries.failed);+ // The parent is stopped meanwhile.+ yield* a.threads.stopDelegatedTasks({+ threadId: parentThreadId,+ commandId: CommandId.make("command:stop:laptop-parent-offline"),+ });+ expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ status: "interrupted" });++ // Once the box is back, the follower's next attempt stops the task there.+ yield* Ref.set(b.descriptor, box);+ yield* Queue.offer(retries.retry, undefined);+ yield* Deferred.await(thread.interruptedOnce);+ expect(yield* Ref.get(thread.interrupted)).toBe(1);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("a task cancelled while the box is unreachable is stopped there after a restart", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ // Its links outlive the restart, so the box knows it as the same link session.+ const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);+ // The laptop cancels while the box sleeps, then restarts before it wakes.+ const delegated = yield* Effect.scoped(+ Effect.gen(function* () {+ const before = yield* makeLaptop(database, offers, linking);+ yield* linkTo(before.links, b, "full-access");+ yield* seedParent(before);+ const task = yield* delegateToBox(before);+ yield* Ref.set(b.descriptor, descriptorOf("environment-elsewhere", "Elsewhere"));+ yield* before.call("task_cancel", { taskId: task.taskId });+ expect(yield* taskResult(before, task.taskId)).toMatchObject({ status: "cancelled" });+ return task;+ }),+ );+ expect(yield* Ref.get(thread.interrupted)).toBe(0);++ yield* Ref.set(b.descriptor, box);+ const after = yield* makeLaptop(database, offers, linking);+ yield* after.remote.start();+ yield* Deferred.await(thread.interruptedOnce);+ // Once the stop is recorded, nothing is owed there any more.+ yield* stoppedThere(after, delegated.taskId, null);+ expect(yield* after.projections.getOpenRemoteDelegatedTasks).toEqual([]);+ expect(yield* Ref.get(thread.stops)).toEqual(["thread.stop", "delegated-tasks"]);+ // The result here is still the cancel's.+ expect(yield* taskResult(after, delegated.taskId)).toMatchObject({ status: "cancelled" });+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("a task whose thread there has no run ends with its last reply", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const thread = yield* makeBoxThread;+ const b = yield* serveBox(thread);+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* linkTo(a.links, b, "full-access");+ yield* seedParent(a);+ // As a task recorded before its run was kept, whose thread there is idle.+ yield* Ref.set(thread.runless, true);+ yield* Ref.set(thread.reply, "Done before it was followed.");++ const delegated = yield* delegateToBox(a);+ expect(yield* taskResult(a, delegated.taskId)).toMatchObject({+ status: "completed",+ result: "Done before it was followed.",+ });+ // One look, not a loop.+ expect(yield* Ref.get(thread.waitedFor)).toEqual([undefined]);+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);++it.effect("a local task runs in this thread's project", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const offers = yield* SubscriptionRef.make<+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>+ >([]);+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);+ const a = yield* makeLaptop(database, offers);+ yield* seedParent(a);++ const result = yield* a.call("delegate_task", {+ task: "Run it here.",+ target: { projectId: "project:elsewhere" },+ });+ expect(result.isError).toBe(true);+ expect(JSON.stringify(result.content)).toContain("invalid_request");+ }),+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),+);diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.tsnew file mode 100644index 00000000000..739edc0a603--- /dev/null+++ b/apps/server/src/peer/RemoteDelegation.ts@@ -0,0 +1,801 @@+import {+ CommandId,+ type EnvironmentId,+ NodeId,+ OrchestratorMcpFailure,+ type OrchestratorMcpDelegateTaskInput,+ type OrchestratorMcpTaskCancelResult,+ type OrchestratorMcpThreadTimelineItem,+ type OrchestrationV2RemoteTaskChild,+ type OrchestrationV2Subagent,+ type ProjectId,+ type ProviderInstanceId,+ ProviderDriverKind,+ type RunId,+ type ThreadId,+} from "@t3tools/contracts";+import * as Context from "effect/Context";+import * as Crypto from "effect/Crypto";+import * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import * as Schedule from "effect/Schedule";+import * as Scope from "effect/Scope";+import * as Stream from "effect/Stream";+import type * as Tool from "effect/ai/Tool";++import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts";+import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts";+import {+ resolveInteractionMode,+ resolveRuntimeMode,+ taskPrompt,+} from "../mcp/delegatedTaskModes.ts";+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";+import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";+import * as ServerEnvironment from "../environment/ServerEnvironment.ts";+import * as ProjectService from "../project/ProjectService.ts";+import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";+import { forkParked } from "../serverActivation.ts";+import * as PeerForwarding from "./PeerForwarding.ts";+import * as PeerLinks from "./PeerLinks.ts";++/** How long one follow of a remote task waits on its thread there before checking again. */+const FOLLOW_WAIT_MS = 10 * 60 * 1_000;+/** A linked environment that stops answering is retried, backing off to this. */+const FOLLOW_MAX_BACKOFF = Duration.minutes(5);+/** How a follower retries; tests step it by hand. */+export const FollowRetrySchedule = Context.Reference<Schedule.Schedule<unknown>>(+ "t3/peer/RemoteDelegation/FollowRetrySchedule",+ {+ defaultValue: () =>+ Schedule.exponential(Duration.seconds(2)).pipe(+ Schedule.modifyDelay(({ duration }) =>+ Effect.succeed(Duration.min(duration, FOLLOW_MAX_BACKOFF)),+ ),+ ),+ },+);++type ThreadScope = McpInvocationContext.McpThreadInvocationScope;++/**+ * `delegate_task` to a linked environment. The task's child is an ordinary+ * thread there, launched through the link; the parent here records the task+ * like a local one, without a child thread, and a follower completes it when+ * the thread there ends, so the parent wakes as it would for a local child.+ */+export class RemoteDelegation extends Context.Service<+ RemoteDelegation,+ {+ readonly delegate: (+ scope: ThreadScope,+ input: OrchestratorMcpDelegateTaskInput & {+ readonly target: NonNullable<OrchestratorMcpDelegateTaskInput["target"]> & {+ readonly environmentId: EnvironmentId;+ };+ },+ ) => Effect.Effect<{ readonly taskId: NodeId }, OrchestratorMcpFailure>;+ /**+ * Stops the task's thread there, then completes it here as cancelled. A+ * task that already has its result keeps it; its thread there is still+ * stopped, as cancelling a local task stops follow-up work on its child.+ */+ readonly cancel: (+ scope: ThreadScope,+ task: OrchestrationV2Subagent,+ input: {+ readonly reason?: string | undefined;+ readonly clientRequestId?: string | undefined;+ },+ ) => Effect.Effect<OrchestratorMcpTaskCancelResult, OrchestratorMcpFailure>;+ /**+ * Follows every open remote task until it ends, including after a+ * restart, and a finished one again when a Stop here owes it a stop there.+ */+ readonly start: () => Effect.Effect<void, never, Scope.Scope>;+ }+>()("t3/peer/RemoteDelegation") {}++/** The other side refused because the thread there runs above this caller's modes. */+const isModeRefusal = (error: OrchestratorMcpFailure) =>+ error.code === "runtime_mode_escalation_denied" ||+ error.code === "interaction_mode_escalation_denied";++/**+ * Refusals that following again cannot change: the link was revoked, expired+ * or forgotten, or the thread or run there is gone. Anything else (the other+ * machine asleep, a dropped route) is worth retrying.+ */+const isFinal = (error: OrchestratorMcpFailure) =>+ error.code === "capability_denied" ||+ error.code === "thread_not_found" ||+ error.code === "run_not_found";++const make = Effect.gen(function* () {+ const followRetry = yield* FollowRetrySchedule;+ const forwarding = yield* PeerForwarding.PeerForwarding;+ const links = yield* PeerLinks.PeerLinks;+ const threads = yield* ThreadManagement.ThreadManagementService;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ const projects = yield* ProjectService.ProjectService;+ const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;+ const crypto = yield* Crypto.Crypto;+ const hereId = yield* ServerEnvironment.ServerEnvironment.pipe(+ Effect.flatMap((environment) => environment.getEnvironmentId),+ );+ // Followers live as long as this service, so shutting down stops them.+ const followers = yield* Scope.Scope;++ // One follower runs per open task and holds what it read across a wait of+ // up to FOLLOW_WAIT_MS, so it reads its own task, never the parent's whole+ // task list: a parent with thousands of tasks made every restart decode+ // that list once per open task at the same time and ran out of heap.+ const readTask = (parentThreadId: ThreadId, taskId: NodeId) =>+ threads+ .getThreadRecords(parentThreadId, ["subagents"], { subagentIds: [taskId] })+ .pipe(Effect.map(({ thread, subagents }) => ({ thread, task: subagents[0] })));++ /** The peer's project with this thread's repository, or the one the caller named. */+ const resolveRemoteProject = Effect.fn("RemoteDelegation.resolveRemoteProject")(function* (+ scope: ThreadScope,+ environmentId: EnvironmentId,+ parentProjectId: ProjectId,+ requested: ProjectId | undefined,+ ) {+ if (requested !== undefined) return requested;+ const here = yield* projects.getById(parentProjectId).pipe(+ Effect.map(Option.getOrUndefined),+ Effect.orElseSucceed(() => undefined),+ );+ // The project's own identity is a one-minute cache that reads blank when+ // cold, so resolve it here, as the other side's t3_project_list does.+ const key =+ here === undefined+ ? undefined+ : (yield* repositoryIdentities.resolve(here.workspaceRoot))?.canonicalKey;+ if (key === undefined) {+ return yield* new OrchestratorMcpFailure({+ code: "target_required",+ message: "Pass target.projectId: this thread's project has no repository to match there.",+ });+ }+ const matches: Array<{ readonly id: ProjectId; readonly title: string }> = [];+ let cursor: number | null = 0;+ while (cursor !== null) {+ const listed: Tool.Success<typeof ProjectToolkit.tools.t3_project_list> =+ yield* forwarding.call(scope, ProjectToolkit.tools.t3_project_list, environmentId, {+ cursor,+ limit: 100,+ });+ matches.push(+ ...listed.projects.filter((project) => project.repositoryIdentity?.canonicalKey === key),+ );+ cursor = listed.nextCursor;+ }+ if (matches.length === 1) return matches[0]!.id;+ return yield* new OrchestratorMcpFailure({+ code: "invalid_request",+ message:+ matches.length === 0+ ? `No project there has this repository (${key}). Pass target.projectId; t3_project_list with this environmentId lists them. To bring the repository there, use t3_project_clone and then t3_project_create with this environmentId.`+ : `Several projects there have this repository: ${matches.map((project) => `${project.title} (${project.id})`).join(", ")}. Pass target.projectId.`,+ });+ });++ const delegate: RemoteDelegation["Service"]["delegate"] = Effect.fn("RemoteDelegation.delegate")(+ function* (scope, input) {+ const parent = yield* threads.getThreadRecords(scope.thread.threadId, ["runs"]).pipe(+ Effect.mapError(+ () =>+ new OrchestratorMcpFailure({+ code: "thread_not_found",+ message: "The calling thread was not found.",+ }),+ ),+ );+ const parentRun = parent.runs+ .filter(ThreadManagement.isActiveRun)+ .toSorted((left, right) => right.ordinal - left.ordinal)[0];+ if (+ parentRun === undefined ||+ parentRun.rootNodeId === null ||+ parentRun.providerInstanceId !== scope.thread.providerInstanceId+ ) {+ return yield* new OrchestratorMcpFailure({+ code: "parent_not_active",+ message: "Delegated tasks require an active run owned by this MCP provider session.",+ });+ }+ const parentNodeId = parentRun.rootNodeId;+ const { target } = input;+ // A worktree there would branch from a commit this checkout has and the+ // other may not, so a remote task runs in that project's checkout.+ if (input.isolation === "worktree") {+ return yield* new OrchestratorMcpFailure({+ code: "invalid_request",+ message:+ 'A task in a linked environment runs in that project\'s checkout; isolation "worktree" is not supported there. Omit isolation, or use t3_thread_launch with environmentId and a worktree workspaceStrategy.',+ });+ }+ // The provider and model inherit as they do for a task here. Another+ // provider there has no model to inherit, so the caller names one.+ const inherited = parent.thread.modelSelection;+ const instanceId = target.providerInstanceId ?? inherited.instanceId;+ const model =+ target.model ?? (instanceId === inherited.instanceId ? inherited.model : undefined);+ if (model === undefined) {+ return yield* new OrchestratorMcpFailure({+ code: "target_required",+ message: "Pass target.model from orchestrator_capabilities with this environmentId.",+ });+ }+ const options =+ target.options ??+ (instanceId === inherited.instanceId && model === inherited.model+ ? inherited.options+ : undefined);+ // Modes asked for are checked against this thread. Omitted ones are left+ // to the other side, which inherits this thread's modes capped by the+ // link's access, so a narrower link still takes the task.+ const runtimeMode =+ input.runtimeMode === undefined || input.runtimeMode === "inherit"+ ? undefined+ : yield* resolveRuntimeMode(parent.thread.runtimeMode, input.runtimeMode);+ const interactionMode =+ input.interactionMode === undefined || input.interactionMode === "inherit"+ ? undefined+ : yield* resolveInteractionMode(parent.thread.interactionMode, input.interactionMode);+ const projectId = yield* resolveRemoteProject(+ scope,+ target.environmentId,+ parent.thread.projectId,+ target.projectId,+ );+ // One key for the launch there and the record here, so a retry finds both.+ // Both are scoped to the provider session, as every key a caller passes is:+ // the forwarder scopes the launch's, and the record's names it.+ const key = input.clientRequestId ?? (yield* crypto.randomUUIDv4().pipe(Effect.orDie));+ const task = taskPrompt(input);+ const launched = yield* forwarding.call(+ scope,+ ProjectToolkit.tools.t3_thread_launch,+ target.environmentId,+ {+ projectId,+ title: input.title ?? parent.thread.title,+ modelSelection: { instanceId, model, ...(options === undefined ? {} : { options }) },+ ...(runtimeMode === undefined ? {} : { runtimeMode }),+ ...(interactionMode === undefined ? {} : { interactionMode }),+ message: task,+ clientRequestId: `delegate:${scope.thread.threadId}:${key}`,+ // The thread there shows it is this thread's subagent, with a way back.+ delegatedFrom: {+ environmentId: hereId,+ threadId: parent.thread.id,+ title: parent.thread.title,+ },+ },+ );+ const link = yield* links.get(target.environmentId).pipe(+ Effect.map(Option.getOrUndefined),+ Effect.orElseSucceed(() => undefined),+ );+ const commandId = CommandId.make(+ `command:mcp:${encodeURIComponent(scope.requestNamespace)}:remote-delegate:${encodeURIComponent(key)}`,+ );+ const remoteChild: OrchestrationV2RemoteTaskChild = {+ environmentId: target.environmentId,+ threadId: launched.threadId,+ label: link?.label ?? target.environmentId,+ ...(launched.runId === null ? {} : { runId: launched.runId }),+ };+ const recorded = yield* threads+ .dispatch({+ type: "delegated_task.remote.request",+ commandId,+ parentThreadId: scope.thread.threadId,+ parentRunId: parentRun.id,+ parentNodeId,+ task,+ ...(input.title === undefined ? {} : { title: input.title }),+ // The driver runs there; this side only labels the task with it.+ driver: ProviderDriverKind.make("remote"),+ modelSelection: launched.modelSelection,+ remoteChild,+ completionWake: input.mode === "wait" ? "settled_only" : "always",+ })+ .pipe(+ // The cause goes to the log; the caller learns only that recording failed.+ Effect.tapError((cause) =>+ Effect.logWarning("remote-delegation.record-failed", {+ parentThreadId: scope.thread.threadId,+ cause,+ }),+ ),+ Effect.mapError(+ () =>+ new OrchestratorMcpFailure({+ code: "orchestration_error",+ message: "Unable to record the delegated task.",+ }),+ ),+ // Nothing here follows a thread the task was never recorded for, so stop it there.+ // A crash between the launch and this record still leaves it running there+ // until a retry with the same clientRequestId records it.+ Effect.tapError(() =>+ stopThere(followScope(scope.thread, remoteChild), remoteChild, "stop").pipe(+ Effect.ignoreCause({ log: true }),+ ),+ ),+ );+ const taskEvent = recorded.storedEvents.find(+ (stored) => stored.event.type === "subagent.updated",+ );+ const taskId =+ taskEvent?.event.type === "subagent.updated"+ ? taskEvent.event.payload.id+ : // A replayed request recorded the task the first time.+ yield* threads.getThreadRecords(scope.thread.threadId, ["subagents"]).pipe(+ Effect.map(+ ({ subagents }) =>+ subagents.find((task) => task.remoteChild?.threadId === launched.threadId)?.id,+ ),+ Effect.orElseSucceed(() => undefined),+ );+ if (taskId === undefined) {+ return yield* new OrchestratorMcpFailure({+ code: "orchestration_error",+ message: "The delegated task was not recorded.",+ });+ }+ yield* followOne(scope.thread.threadId, taskId).pipe(Effect.forkIn(followers));+ return { taskId };+ },+ );++ /**+ * Completes `task` here with its thread there's final state. Each attempt is its own+ * command, so a failed one never blocks the next; a report refused because the task already+ * has its result (a cancel, a Stop or an earlier report) is done. `stoppedThere` records that+ * nothing is left to stop there, even on a task that already has its result.+ */+ const complete = Effect.fn("RemoteDelegation.complete")(function* (+ parentThreadId: ThreadId,+ taskId: NodeId,+ status: "completed" | "failed" | "cancelled" | "interrupted",+ result: string,+ stoppedThere: "ran-out" | "stopped" | undefined,+ stopCount?: number,+ ) {+ const attempt = yield* crypto.randomUUIDv4().pipe(Effect.orDie);+ yield* threads+ .dispatch({+ type: "delegated_task.remote.complete",+ commandId: CommandId.make(`command:remote-task-complete:${taskId}:${attempt}`),+ parentThreadId,+ taskId,+ status,+ result,+ ...(stoppedThere === undefined ? {} : { stoppedThere }),+ ...(stopCount === undefined ? {} : { stopCount }),+ })+ .pipe(+ Effect.catch((error) =>+ readTask(parentThreadId, taskId).pipe(+ Effect.flatMap(({ task }) => (task?.result != null ? Effect.void : Effect.fail(error))),+ ),+ ),+ );+ });++ /**+ * How this environment reaches a task's thread there: as the parent+ * thread, under one namespace per parent, so a stop sent again after a+ * restart or a dropped route is recorded there once.+ */+ const followScope = (+ parent: { readonly threadId: ThreadId; readonly providerInstanceId: ProviderInstanceId },+ remote: OrchestrationV2RemoteTaskChild,+ ): ThreadScope => ({+ environmentId: hereId,+ requestNamespace: `remote-task:${parent.threadId}`,+ thread: {+ threadId: parent.threadId,+ providerSessionId: `remote-task:${remote.threadId}`,+ providerInstanceId: parent.providerInstanceId,+ },+ client: undefined,+ capabilities: new Set(["orchestration"]),+ issuedAt: 0,+ });++ /**+ * Stops the task's own thread there as its Stop button does: its running turn, queued+ * messages, pull request watches and delegated tasks. `key` names the stop (the follower+ * sends one, each cancel its own), and each is recorded there once however often it is sent.+ */+ const stopThere = (+ scope: ThreadScope,+ remote: OrchestrationV2RemoteTaskChild,+ key: string,+ reason?: string,+ ) =>+ forwarding+ .interruptThread(scope, remote.environmentId, {+ threadId: remote.threadId,+ stop: true,+ ...(reason === undefined ? {} : { reason }),+ clientRequestId: `${key}:${remote.threadId}`,+ })+ .pipe(Effect.asVoid);++ /**+ * The last reply `runId` gave on the task's thread there, which is its+ * result, read whole however long it is. A failed run prefers its error+ * from the activity view over an earlier reply, without taking another run's.+ */+ const lastReply = Effect.fn("RemoteDelegation.lastReply")(function* (+ scope: ThreadScope,+ remote: OrchestrationV2RemoteTaskChild,+ runId: RunId | null,+ failed = false,+ ) {+ let reply: OrchestratorMcpThreadTimelineItem | undefined;+ let error: OrchestratorMcpThreadTimelineItem | undefined;+ let afterPosition: number | undefined;+ while (true) {+ const read = yield* forwarding.readThread(scope, remote.environmentId, {+ threadId: remote.threadId,+ view: failed ? "activity" : "messages",+ limit: 100,+ ...(afterPosition === undefined ? {} : { afterPosition }),+ });+ reply =+ read.items.findLast(+ (item) => item.type === "assistant_message" && (runId === null || item.runId === runId),+ ) ?? reply;+ if (failed) {+ error =+ read.items.findLast(+ (item) => item.type === "error" && (runId === null || item.runId === runId),+ ) ?? error;+ }+ if (!read.hasMore || read.nextPosition === null) break;+ afterPosition = read.nextPosition;+ }+ reply = error ?? reply;+ if (reply === undefined) return undefined;+ let text = reply.text ?? "";+ let textOffset = reply.textTruncated ? (reply.nextTextOffset ?? null) : null;+ while (textOffset !== null) {+ const rest = yield* forwarding.readThread(scope, remote.environmentId, {+ threadId: remote.threadId,+ itemId: reply.itemId,+ textOffset,+ maxCharsPerItem: 50_000,+ });+ const part = rest.items[0];+ if (part === undefined) break;+ text += part.text ?? "";+ textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null;+ }+ return text;+ });++ /**+ * Why following a task can never succeed, if that is what `error` means.+ * The far side's message already says what was refused and what to do; a+ * link forgotten here only reads as a bad request, so it is named.+ */+ const finalReason = Effect.fn("RemoteDelegation.finalReason")(+ function* (parentThreadId: ThreadId, taskId: NodeId, error: OrchestratorMcpFailure) {+ if (isFinal(error)) return error.message;+ if (error.code !== "invalid_request") return undefined;+ const { task } = yield* readTask(parentThreadId, taskId);+ const environmentId = task?.remoteChild?.environmentId;+ if (environmentId === undefined) return error.message;+ const link = yield* links.get(environmentId);+ return Option.isSome(link) ? undefined : error.message;+ },+ Effect.orElseSucceed(() => undefined),+ );++ /** A task's thread there that ended without a reply. */+ const noReply = "(The thread in the linked environment ended without a reply.)";++ /**+ * Waits for the task's run there to end, completes the task here, and stops it there if it+ * ended here first. A revoked, expired or forgotten link, or a thread or run gone there,+ * fails the task with nothing left to stop; anything else (the other machine asleep, a+ * dropped route) is retried with back-off, and so is completing.+ */+ const follow = (parentThreadId: ThreadId, taskId: NodeId): Effect.Effect<void> =>+ followOnce(parentThreadId, taskId).pipe(+ // `false` means it is still running there: follow again straight away.+ Effect.repeat({ while: (done) => !done }),+ Effect.catchTags({+ OrchestratorMcpFailure: Effect.fn("RemoteDelegation.followFailed")(function* (error) {+ const reason = yield* finalReason(parentThreadId, taskId, error);+ if (reason === undefined) return yield* error;+ // Gone there, or no link to reach it by: nothing left to stop there.+ const { task } = yield* readTask(parentThreadId, taskId);+ const stopCount = task?.remoteChild?.stopCount;+ yield* complete(parentThreadId, taskId, "failed", reason, "stopped", stopCount);+ }),+ }),+ Effect.retry(followRetry),+ Effect.ignoreCause({ log: true }),+ );++ /**+ * One wait on the task's thread there; true once the task here is done.+ * A task completed here first (cancelled, or its parent stopped) is+ * stopped there, and done once that stop is recorded here.+ */+ const followOnce = Effect.fn("RemoteDelegation.followOnce")(function* (+ parentThreadId: ThreadId,+ taskId: NodeId,+ ) {+ const sequence = yield* threads.getThreadEventSequence(parentThreadId);+ const { thread, task } = yield* readTask(parentThreadId, taskId);+ if (task?.remoteChild === undefined) return true;+ const remote = task.remoteChild;+ const scope = followScope(+ { threadId: parentThreadId, providerInstanceId: thread.providerInstanceId },+ remote,+ );+ // Ended here, maybe while this follower backed off from an unreachable+ // machine or before a restart: it still has to be stopped there. So+ // does one its parent here was stopped after, for what followed there.+ if (task.result !== null) {+ if (+ remote.stoppedThere === false ||+ ((task.status === "cancelled" || task.status === "interrupted") &&+ remote.stoppedThere !== true)+ ) {+ const key = remote.stopCount === undefined ? "stop" : `stop-${remote.stopCount}`;+ yield* stopThere(scope, remote, key).pipe(+ // Its thread there now runs above what this side may touch, say+ // because the parent here was lowered since; no retry changes that.+ Effect.catchIf(isModeRefusal, (error) =>+ Effect.logWarning("A linked environment refused to stop a delegated task", {+ taskId,+ reason: error.message,+ }),+ ),+ );+ yield* complete(+ parentThreadId,+ taskId,+ terminalStatus(task.status),+ task.result,+ "stopped",+ remote.stopCount,+ );+ return yield* settled(parentThreadId, taskId);+ }+ return true;+ }+ const endedHere = threads+ .streamStoredEventsFrom({+ threadId: parentThreadId,+ afterSequence: sequence,+ eventType: "subagent.updated",+ })+ .pipe(+ Stream.filter(+ (stored) =>+ stored.event.type === "subagent.updated" &&+ stored.event.payload.id === taskId &&+ stored.event.payload.result !== null,+ ),+ Stream.runHead,+ Effect.flatMap((ended) =>+ Option.isSome(ended) ? Effect.succeed({ endedHere: true } as const) : Effect.never,+ ),+ );+ const waited = yield* forwarding+ .waitForThread(scope, remote.environmentId, {+ threadId: remote.threadId,+ ...(remote.runId === undefined ? {} : { runId: remote.runId }),+ timeoutMs: FOLLOW_WAIT_MS,+ // A thread there whose run ended may still be waiting on its own+ // tasks to wake it for the answer, which a task here waits for too.+ // An older peer ignores this and reports the run alone.+ untilDelegatedWorkSettled: true,+ })+ .pipe(Effect.raceFirst(endedHere));+ // The next look reads the result and stops it there.+ if ("endedHere" in waited) return false;+ if (waited.timedOut) return false;+ // A task recorded without its run waits on the thread's latest; a+ // thread there with none has nothing left to wait for.+ if (waited.runId === null) {+ const reply = yield* lastReply(scope, remote, null);+ yield* complete(+ parentThreadId,+ taskId,+ reply === undefined ? "failed" : "completed",+ reply ?? "The thread in the linked environment has no run to follow.",+ "ran-out",+ );+ return yield* settled(parentThreadId, taskId);+ }+ if (!isTerminal(waited.status)) return false;+ const resultRun = waited.resultRun ?? {+ runId: remote.runId ?? waited.runId,+ status: waited.status,+ };+ const result = yield* lastReply(scope, remote, resultRun.runId, resultRun.status === "failed");+ yield* complete(+ parentThreadId,+ taskId,+ terminalStatus(resultRun.status),+ result ?? noReply,+ "ran-out",+ );+ return yield* settled(parentThreadId, taskId);+ });++ /**+ * Whether the task is done here after the follower reported its run ran+ * out there. A cancel or Stop that landed while the reply was read keeps+ * its result, and still owes a stop there for what may follow the run;+ * the next look sends it.+ */+ const settled = (parentThreadId: ThreadId, taskId: NodeId) =>+ readTask(parentThreadId, taskId).pipe(+ Effect.map(({ task }) => task?.remoteChild?.stoppedThere === true),+ );++ const following = new Map<NodeId, { again: boolean }>();++ /**+ * `follow`, at most once per task. Asked again while it runs, say by a+ * Stop here on a task that already has its result, it looks once more+ * before it ends, so that stop is not missed.+ */+ const followOne = (parentThreadId: ThreadId, taskId: NodeId) =>+ Effect.suspend(() => {+ const running = following.get(taskId);+ if (running !== undefined) {+ running.again = true;+ return Effect.void;+ }+ const state = { again: false };+ following.set(taskId, state);+ return follow(parentThreadId, taskId).pipe(+ // Checked and released in one step, so a request between them is never lost.+ Effect.repeat({+ while: () => {+ if (state.again) {+ state.again = false;+ return true;+ }+ following.delete(taskId);+ return false;+ },+ }),+ Effect.ensuring(+ Effect.sync(() => {+ if (following.get(taskId) === state) following.delete(taskId);+ }),+ ),+ );+ });++ const cancel: RemoteDelegation["Service"]["cancel"] = Effect.fn("RemoteDelegation.cancel")(+ function* (scope, task, input) {+ const remote = task.remoteChild;+ if (remote === undefined) {+ return yield* new OrchestratorMcpFailure({+ code: "task_not_found",+ message: `Delegated task ${task.id} is not remote.`,+ });+ }+ const { reason } = input;+ const there = followScope(scope.thread, remote);+ // A later cancel stops what started there since; a retry of this one, nothing new.+ const key = `cancel:${encodeURIComponent(scope.requestNamespace)}:${+ input.clientRequestId ?? (yield* crypto.randomUUIDv4().pipe(Effect.orDie))+ }`;+ if (task.result !== null) {+ // Best effort: the result stands whether or not the stop gets there.+ yield* stopThere(there, remote, key, reason).pipe(+ Effect.andThen(+ complete(+ task.threadId,+ task.id,+ terminalStatus(task.status),+ task.result,+ "stopped",+ remote.stopCount,+ ),+ ),+ Effect.ignoreCause({ log: true }),+ );+ return {+ taskId: task.id,+ status:+ task.status === "completed" || task.status === "failed" || task.status === "interrupted"+ ? task.status+ : "cancelled",+ } satisfies OrchestratorMcpTaskCancelResult;+ }+ // A link that is gone or a machine that is down still cancels the task+ // here; its follower keeps trying to stop it there, across restarts.+ const unstopped = yield* stopThere(there, remote, key, reason).pipe(+ Effect.as(undefined),+ Effect.catch((error) => Effect.succeed(error.message)),+ );+ const cancelled = reason === undefined ? "Cancelled." : `Cancelled: ${reason}`;+ yield* complete(+ task.threadId,+ task.id,+ "cancelled",+ unstopped === undefined+ ? cancelled+ : `${cancelled} It could not be stopped in ${remote.label} and may still run there: ${unstopped}`,+ unstopped === undefined ? "stopped" : undefined,+ remote.stopCount,+ ).pipe(+ Effect.tapError((cause) =>+ Effect.logWarning("remote-delegation.cancel-record-failed", { taskId: task.id, cause }),+ ),+ Effect.mapError(+ () =>+ new OrchestratorMcpFailure({+ code: "orchestration_error",+ message: "Unable to record the cancellation.",+ }),+ ),+ );+ return {+ taskId: task.id,+ status: "cancel_requested",+ } satisfies OrchestratorMcpTaskCancelResult;+ },+ );++ const start: RemoteDelegation["Service"]["start"] = () =>+ forkParked(+ Effect.gen(function* () {+ // A finished task's follower has ended, so a Stop here that owes its+ // thread there a stop starts it again. Started before the scan below;+ // a Stop that slips between the two stays owed for the next start.+ yield* Stream.runForEach(threads.streamDomainEvents, (event) =>+ event.type === "subagent.updated" && event.payload.remoteChild?.stoppedThere === false+ ? followOne(event.threadId, event.payload.id).pipe(Effect.forkIn(followers))+ : Effect.void,+ ).pipe(+ Effect.ignoreCause({ log: true }),+ Effect.forkIn(followers, { startImmediately: true }),+ );+ const open = yield* projections.getOpenRemoteDelegatedTasks;+ yield* Effect.forEach(+ open,+ ({ parentThreadId, taskId }) => followOne(parentThreadId, taskId),+ {+ concurrency: "unbounded",+ discard: true,+ },+ );+ }).pipe(Effect.ignoreCause({ log: true })),+ );++ return RemoteDelegation.of({ delegate, cancel, start });+});++const isTerminal = (status: string) =>+ status === "completed" ||+ status === "failed" ||+ status === "cancelled" ||+ status === "interrupted" ||+ status === "rolled_back";++const terminalStatus = (status: string): "completed" | "failed" | "cancelled" | "interrupted" =>+ status === "completed" || status === "failed" || status === "interrupted" ? status : "cancelled";++export const layer = Layer.effect(RemoteDelegation, make);diff --git a/apps/server/src/project/ProjectEnrichmentService.ts b/apps/server/src/project/ProjectEnrichmentService.tsindex cbee7275b12..f7fe236fe5f 100644--- a/apps/server/src/project/ProjectEnrichmentService.ts+++ b/apps/server/src/project/ProjectEnrichmentService.ts@@ -50,6 +50,9 @@ export class ProjectEnrichmentService extends Context.Service<readonly peek: (workspaceRoot: string) => Effect.Effect<ProjectEnrichment>;readonly request: (workspaceRoot: string) => Effect.Effect<void>;readonly getAvailable: (workspaceRoot: string) => Effect.Effect<ProjectEnrichment>;+ readonly readRepositoryIdentity: (+ workspaceRoot: string,+ ) => Effect.Effect<RepositoryIdentity | null>;readonly invalidate: (workspaceRoots: Iterable<string>) => Effect.Effect<void>;readonly subscribeChanges: Effect.Effect<PubSub.Subscription<ProjectEnrichmentChange>,@@ -271,6 +274,12 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* (return available;});+ const readRepositoryIdentity: ProjectEnrichmentService["Service"]["readRepositoryIdentity"] =+ Effect.fn("ProjectEnrichmentService.readRepositoryIdentity")(function* (workspaceRoot) {+ const resolved = yield* Cache.get(repositoryIdentityCache, workspaceRoot);+ return Exit.isSuccess(resolved) ? resolved.value : null;+ });+const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn("ProjectEnrichmentService.invalidate",)(function* (workspaceRoots) {@@ -294,6 +303,7 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* (peek,request,getAvailable,+ readRepositoryIdentity,invalidate,subscribeChanges: PubSub.subscribe(changes),});diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.tsindex 5c646e1ea7b..18004510baa 100644--- a/apps/server/src/project/ProjectService.ts+++ b/apps/server/src/project/ProjectService.ts@@ -132,6 +132,17 @@ export class ProjectService extends Context.Service<options?: { readonly includeDeleted?: boolean },) => Effect.Effect<Option.Option<Project>, ProjectOperationError>;readonly snapshot: Effect.Effect<ProjectSnapshot, ProjectOperationError>;+ /**+ * A page of active projects in creation order, each with its repository+ * identity resolved, so a caller can match projects by repository.+ */+ readonly listPage: (input: {+ readonly cursor: number;+ readonly limit: number;+ }) => Effect.Effect<+ { readonly projects: ReadonlyArray<Project>; readonly nextCursor: number | null },+ ProjectOperationError+ >;readonly getShell: (projectId: ProjectId,) => Effect.Effect<Option.Option<OrchestrationProjectShell>, ProjectOperationError>;@@ -557,6 +568,23 @@ export const make = Effect.gen(function* () {} satisfies ProjectSnapshot;});+ const listPage: ProjectService["Service"]["listPage"] = Effect.fn("ProjectService.listPage")(+ function* ({ cursor, limit }) {+ const rows = (yield* snapshot).projects.filter((project) => project.deletedAt === null);+ const projects = yield* Effect.forEach(+ rows.slice(cursor, cursor + limit),+ (project) =>+ project.repositoryIdentity !== null+ ? Effect.succeed(project)+ : projectEnrichment+ .readRepositoryIdentity(project.workspaceRoot)+ .pipe(Effect.map((repositoryIdentity) => ({ ...project, repositoryIdentity }))),+ { concurrency: 8 },+ );+ return { projects, nextCursor: cursor + limit < rows.length ? cursor + limit : null };+ },+ );+return ProjectService.of({create,bootstrap,@@ -565,6 +593,7 @@ export const make = Effect.gen(function* () {getById,getByWorkspaceRoot,snapshot,+ listPage,getShell,listShells,});diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.tsindex 1f7bdb48417..99a8493eaaf 100644--- a/apps/server/src/provider/AgentContextBudget.test.ts+++ b/apps/server/src/provider/AgentContextBudget.test.ts@@ -23,6 +23,7 @@ import { ThreadLaunchService } from "../orchestration-v2/ThreadLaunchService.ts"import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";import { ThreadSearch } from "../orchestration-v2/ThreadSearch.ts";import { PeerForwarding } from "../peer/PeerForwarding.ts";+import { RemoteDelegation } from "../peer/RemoteDelegation.ts";import { PreviewManager } from "../preview/Manager.ts";import { PreviewBrowser } from "../preview/PreviewBrowser.ts";import { ManagedProjectFolders } from "../project/ManagedProjectFolders.ts";@@ -58,6 +59,7 @@ const toolHandlerServices = Layer.mergeAll(Layer.mock(ProviderAdapterRegistryV2)({}),Layer.mock(ProviderRegistry)({}),Layer.mock(PullRequestReviewGuideService)({}),+ Layer.mock(RemoteDelegation)({}),Layer.mock(ScheduledTaskService)({}),Layer.mock(SecretRequests)({}),ServerConfig.layerTest(process.cwd(), { prefix: "t3-agent-context-budget-" }),diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.jsonindex 946416154dd..41a9242f28a 100644--- a/apps/server/src/provider/agentContextBudget.json+++ b/apps/server/src/provider/agentContextBudget.json@@ -1,5 +1,5 @@{"claudeSystemAppendBytes": 5086,"codexAdditionalContextBytes": 5638,- "mcpToolListJsonBytes": 44232+ "mcpToolListJsonBytes": 44745}diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.tsindex e101b7475cd..0cbf8ebbba9 100644--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts@@ -267,6 +267,7 @@ const makeTestRelay = Effect.fnUntraced(function* (delete: unused,getByWorkspaceRoot: unused,snapshot: Effect.succeed({ projects: [] } as never),+ listPage: unused,getShell: unused,listShells: unused,getById: () =>diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 5226e1469b2..161e3275a74 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -68,6 +68,7 @@ import * as ProjectSettingsOverrideSweep from "./provider/ProjectSettingsOverridimport * as TerminalManager from "./terminal/Manager.ts";import * as McpHttpServer from "./mcp/McpHttpServer.ts";import * as PeerForwarding from "./peer/PeerForwarding.ts";+import * as RemoteDelegation from "./peer/RemoteDelegation.ts";import * as PeerLinks from "./peer/PeerLinks.ts";import * as PeerMcpClient from "./peer/PeerMcpClient.ts";import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";@@ -730,10 +731,16 @@ const layerMakeRoutes = Layer.mergeAll(Layer.provide(ProviderAdapterRegistry.layerFromProviderInstanceRegistry),Layer.provide(McpOAuth.layerMcpClientAuthenticator),),+ // Follows delegated tasks running in linked environments, including after a restart.+ Layer.effectDiscard(+ RemoteDelegation.RemoteDelegation.pipe(Effect.flatMap((remote) => remote.start())),+ ),).pipe(Layer.provide(PullRequestReviewGuideService.layer.pipe(Layer.provide(PullRequestReviewGuides.layer)),),+ // delegate_task to a linked environment, from /mcp and the follower above.+ Layer.provide(RemoteDelegation.layer.pipe(Layer.provide(ProjectionStoreV2.layer))),// Share the service so HTTP/WS clients single-flight reads and invalidate each other's cached patches.Layer.provide(layerPullRequestService),// The same activity instance RunExecutionService reports to, by layer memoization.diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 7bb833cb905..5b44cc0b247 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -138,6 +138,7 @@ import {import { type LegendListRef } from "@legendapp/list/react";import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";import { DEFAULT_INTERACTION_MODE, type ChatMessage } from "../types";+import { buildThreadRouteParams } from "../threadRoutes";import { useTheme } from "../hooks/useTheme";import { writeTextToClipboard } from "../hooks/useCopyToClipboard";import { subscribeSnapShotComposerFocus } from "../lib/desktopSnapShot";@@ -231,6 +232,7 @@ import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkiimport { vcsEnvironment } from "../state/vcs";import {type EnvironmentPresentation,+ useEnvironment,useEnvironmentProviders,useEnvironments,usePrimaryEnvironment,@@ -829,7 +831,47 @@ export default function ChatView(props: ChatViewProps) {messages: serverProjection.messages,parentSubagents: workflowOpeningParentProjection?.projection.subagents ?? null,});- const parentThreadLink =+ // A linked environment's agent may have delegated this thread from there.+ const delegatedFrom = activeThread?.delegatedFrom ?? null;+ const delegatedFromEnvironment = useEnvironment(delegatedFrom?.environmentId ?? null);+ const delegatedFromRef =+ delegatedFrom === null+ ? null+ : scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);+ // The title it had at delegation, until this client sees the parent itself.+ const delegatedFromThread = useQuietThreadShell(delegatedFromRef);+ const parentThreadLink = (() => {+ if (parentSubagentThreadRef !== null) {+ return {+ title: parentSubagentThread?.title ?? "Parent thread",+ open: (): void => {+ void navigate({+ to: "/$environmentId/$threadId",+ params: buildThreadRouteParams(parentSubagentThreadRef),+ });+ },+ };+ }+ if (delegatedFrom === null || delegatedFromRef === null) return null;+ const parentRef = delegatedFromRef;+ return {+ title: delegatedFromThread?.title ?? delegatedFrom.title,+ environmentLabel: delegatedFromEnvironment?.label ?? activeThread?.linkOrigin?.label ?? "",+ // Only an environment this client is connected to can open the parent.+ ...(delegatedFromEnvironment === null+ ? {}+ : {+ open: (): void => {+ void navigate({+ to: "/$environmentId/$threadId",+ params: buildThreadRouteParams(parentRef),+ });+ },+ }),+ };+ })();+ // The header's breadcrumb opens a parent in this environment only.+ const headerParentThreadLink =parentSubagentThreadRef === null? null: {@@ -2328,7 +2370,6 @@ export default function ChatView(props: ChatViewProps) {handleSwitchCheckoutToThread,handleSwitchCheckoutToThreadStable,isRestoringThreadBranch,- onOpenRelatedThread,onOpenRelatedThreadStable,sendStandaloneCommand,setBranchMismatchDismissTick,@@ -3161,7 +3202,7 @@ export default function ChatView(props: ChatViewProps) {activeThreadTitle={activeThread.title}activeThreadLinkOrigin={activeThreadShell?.linkOrigin?.label ?? null}activeProject={activeProject ?? null}- parentThreadLink={parentThreadLink}+ parentThreadLink={headerParentThreadLink}onOpenThread={onOpenRelatedThreadStable}rightPanelOpen={inlineRightPanelOwnsTitleBar}onNewThreadInProject={handleNewThreadInActiveProjectStable}@@ -3381,11 +3422,7 @@ export default function ChatView(props: ChatViewProps) {modelLabel={providerSubagentModelLabel}effortLabel={providerSubagentEffortLabel}status={providerSubagentStatus}- onOpenParent={- parentThreadLink- ? () => onOpenRelatedThread(parentThreadLink.threadId)- : null- }+ onOpenParent={parentThreadLink?.open ?? null}/>) : null}{!composerMounted ? null : (diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsxindex 10ff6ef6bef..05422aa57c5 100644--- a/apps/web/src/components/LegacySidebar.tsx+++ b/apps/web/src/components/LegacySidebar.tsx@@ -98,6 +98,7 @@ import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";import {readThreadShell,useProjects,+ useDelegatedUnderParent,useThreadShells,useThreadShellsForProjectRefs,waitForProjectRemoval,@@ -1124,6 +1125,7 @@ function useProjectThreads(project: SidebarProjectSnapshot) {(settings) => settings.sidebarThreadSortOrder,);const sidebarThreads = useThreadShellsForProjectRefs(project.memberProjectRefs);+ const delegatedUnderParent = useDelegatedUnderParent();const threadLastVisitedAts = useUiStateStore(useShallow((state) =>sidebarThreads.map(@@ -1168,7 +1170,7 @@ function useProjectThreads(project: SidebarProjectSnapshot) {]),);const visibleProjectThreads = sortThreads(- filterSidebarV2VisibleThreads(sidebarThreads, null),+ filterSidebarV2VisibleThreads(sidebarThreads, null, delegatedUnderParent),threadSortOrder,);const projectStatus = resolveProjectStatusIndicator(@@ -3121,6 +3123,7 @@ function useSortedLegacySidebarProjects(input: {sidebarProjectSortOrder,} = input;const sidebarThreads = useThreadShells();+ const delegatedUnderParent = useDelegatedUnderParent();const sidebarProjectByKey = new Map(sidebarProjects.map((project) => [project.projectKey, project] as const),);@@ -3128,7 +3131,11 @@ function useSortedLegacySidebarProjects(input: {...project,id: project.projectKey,}));- const sortableThreads = filterSidebarV2VisibleThreads(sidebarThreads, null).map((thread) => {+ const sortableThreads = filterSidebarV2VisibleThreads(+ sidebarThreads,+ null,+ delegatedUnderParent,+ ).map((thread) => {const physicalKey =projectPhysicalKeyByScopedRef.get(scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),@@ -3171,6 +3178,7 @@ function useLegacySidebarThreads(input: {expandedThreadListsByProject,} = input;const sidebarThreads = useThreadShells();+ const delegatedUnderParent = useDelegatedUnderParent();const projectExpandedById = useUiStateStore((store) => store.projectExpandedById);const sidebarThreadByKey = new Map(sidebarThreads.map(@@ -3201,7 +3209,11 @@ function useLegacySidebarThreads(input: {}const visibleSidebarThreadKeys = sortedProjects.flatMap((project) => {const projectThreads = sortThreads(- filterSidebarV2VisibleThreads(threadsByProjectKey.get(project.projectKey) ?? [], null),+ filterSidebarV2VisibleThreads(+ threadsByProjectKey.get(project.projectKey) ?? [],+ null,+ delegatedUnderParent,+ ),sidebarThreadSortOrder,);const projectExpanded = resolveProjectExpanded(diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.tsindex a66540ff4fd..ae17a94fb4f 100644--- a/apps/web/src/components/Sidebar.logic.test.ts+++ b/apps/web/src/components/Sidebar.logic.test.ts@@ -854,7 +854,7 @@ describe("sortSidebarV2ProjectGroups", () => {];expect(- sortSidebarV2ProjectGroups(projects, threads, "updated_at").map(+ sortSidebarV2ProjectGroups(projects, threads, "updated_at", new Set()).map((project) => project.projectKey,),).toEqual(["logical-newer", "logical-older"]);@@ -1306,6 +1306,7 @@ describe("resolveSidebarRouteReveal", () => {routeKey: hiddenKey,isSearching: false,scopedProjectKeys,+ delegatedUnderParent: new Set(),findThread,}),).toEqual({ pendingKey: hiddenKey, widensScope: true });@@ -1319,6 +1320,7 @@ describe("resolveSidebarRouteReveal", () => {routeKey: hiddenKey,isSearching: false,scopedProjectKeys,+ delegatedUnderParent: new Set(),findThread,}),).toEqual({ pendingKey: null, widensScope: false });@@ -1334,6 +1336,7 @@ describe("resolveSidebarRouteReveal", () => {routeKey,isSearching: false,scopedProjectKeys,+ delegatedUnderParent: new Set(),findThread,});resolve("environment-test:unlisted");@@ -1347,6 +1350,7 @@ describe("resolveSidebarRouteReveal", () => {routeKey: hiddenKey,isSearching: true,scopedProjectKeys,+ delegatedUnderParent: new Set(),findThread,}),).toEqual({ pendingKey: hiddenKey, widensScope: false });diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex 90264caa287..f2ab971e19a 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -1,4 +1,5 @@import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";+import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";import * as React from "react";@@ -580,16 +581,27 @@ export function resolveSidebarRowThreadId(return thread?.id ?? threadId;}+/**+ * `delegatedUnderParent` holds the tasks linked environments run for a thread+ * the sidebar lists, by thread key; they show under that thread, as subagents do.+ */export function filterSidebarV2VisibleThreads<- T extends Pick<SidebarThreadSummary, "archivedAt" | "lineage"> & {- environmentId: string;+ T extends Pick<SidebarThreadSummary, "archivedAt" | "environmentId" | "id" | "lineage"> & {projectId: string;},->(threads: readonly T[], scopedProjectKeys: ReadonlySet<string> | null): T[] {+>(+ threads: readonly T[],+ scopedProjectKeys: ReadonlySet<string> | null,+ delegatedUnderParent: ReadonlySet<string>,+): T[] {return threads.filter((thread) =>thread.archivedAt === null &&- !isSidebarSubagentThread(thread) &&+ !isShownUnderParent(+ { environmentId: thread.environmentId, threadId: thread.id },+ thread.lineage,+ delegatedUnderParent,+ ) &&(scopedProjectKeys === null ||scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),);@@ -1299,15 +1311,17 @@ export function sortLogicalProjectsForSidebar<export function sortSidebarV2ProjectGroups<TProject extends LogicalSidebarProject,- TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,+ TThread extends ScopedSidebarThread &+ Pick<SidebarThreadSummary, "environmentId" | "id" | "lineage">,>(projects: readonly TProject[],threads: readonly TThread[],sortOrder: SidebarProjectSortOrder,+ delegatedUnderParent: ReadonlySet<string>,): TProject[] {return sortLogicalProjectsForSidebar(projects,- filterSidebarV2VisibleThreads(threads, null),+ filterSidebarV2VisibleThreads(threads, null, delegatedUnderParent),sortOrder,);}diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex 99f42874066..748b006b380 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -127,6 +127,7 @@ import {import {readThreadShell,useAllEnvironmentProjectSnapshotsReady,+ useDelegatedUnderParent,useProjects,useServerConfigs,useQuietThreadShells,@@ -310,6 +311,8 @@ type SidebarOptimisticDrop = {interface SidebarThreadPartitionInput {readonly threads: readonly EnvironmentThreadShell[];readonly scopedProjectKeys: ReadonlySet<string> | null;+ /** Tasks linked environments run for a listed thread; they show under it. */+ readonly delegatedUnderParent: ReadonlySet<string>;readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;readonly optimisticDrop: SidebarOptimisticDrop | null;readonly workingShelfEnabled: boolean;@@ -371,6 +374,7 @@ function useSidebarThreads(input: {readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;readonly optimisticDrop: SidebarOptimisticDrop | null;readonly threads: readonly EnvironmentThreadShell[];+ readonly delegatedUnderParent: ReadonlySet<string>;readonly routeRowThreadKey: string | null;}) {const {@@ -379,6 +383,7 @@ function useSidebarThreads(input: {serverConfigs,optimisticDrop,threads,+ delegatedUnderParent,routeRowThreadKey,} = input;const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled);@@ -417,6 +422,7 @@ function useSidebarThreads(input: {const partition = partitionSidebarThreads({threads,scopedProjectKeys,+ delegatedUnderParent,serverConfigs,optimisticDrop,workingShelfEnabled,@@ -520,9 +526,16 @@ function useSidebarThreads(input: {}function partitionSidebarThreads(input: SidebarThreadPartitionInput) {- const { threads, scopedProjectKeys, serverConfigs, optimisticDrop, workingShelfEnabled } = input;+ const {+ threads,+ scopedProjectKeys,+ delegatedUnderParent,+ serverConfigs,+ optimisticDrop,+ workingShelfEnabled,+ } = input;const preciseNow = new Date().toISOString();- const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys);+ const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys, delegatedUnderParent);const inboxObservation = inboxReturns.observe(workingShelfEnabled ? threads : null);const pinned: EnvironmentThreadShell[] = [];const active: EnvironmentThreadShell[] = [];@@ -791,6 +804,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveprojectGroupByScopeKey,projectScopeItems,} = useSidebarLookups();+ const delegatedUnderParent = useDelegatedUnderParent();const router = useRouter();const { isMobile, setOpenMobile } = useSidebar();const keybindings = useAtomValue(primaryServerKeybindingsAtom);@@ -996,6 +1010,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReverouteKey: routeRowThreadKey,isSearching: isSearchingThreads,scopedProjectKeys: chosenScopeProjectKeys,+ delegatedUnderParent,findThread: (key) => threads.find((candidate) => threadShellKey(candidate) === key),});const projectScopeKey = revealWidensScope ? null : chosenProjectScopeKey;@@ -1137,6 +1152,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveserverConfigs,optimisticDrop,threads,+ delegatedUnderParent,routeRowThreadKey,});diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsindex f253dd6be22..89128ff69ac 100644--- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts+++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts@@ -45,6 +45,19 @@ vi.mock(import("../state/presentation"), async (original) => {},};});+vi.mock(import("../state/threads"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ environmentThreadShells: {+ ...actual.environmentThreadShells,+ pendingSubagentRequestsAtom: (() => noRequestsAtom) as never,+ get delegatedUnderParentAtom() {+ return noDelegatedAtom as never;+ },+ },+ };+});vi.mock(import("../hooks/useSettings"), async (original) => ({...(await original()),subscribeClientSettings: ((listener: () => void) => {@@ -68,6 +81,8 @@ import { startThreadNotifications } from "./ThreadNotificationCoordinator";let registry: AtomRegistry.AtomRegistry;const shellAtom = Atom.family((_id: string) => Atom.make<unknown>(null));const environmentIdsAtom = Atom.make<ReadonlyArray<string>>([]);+const noRequestsAtom = Atom.make(new Map());+const noDelegatedAtom = Atom.make<ReadonlySet<string>>(new Set<string>());state.shells = { set: (id, value) => registry.set(shellAtom(id), value) };class TestNotification extends EventTarget {diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsxindex a782e24da65..9513ec7e182 100644--- a/apps/web/src/components/ThreadNotificationCoordinator.tsx+++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx@@ -3,7 +3,7 @@ import {type PendingSubagentRequest,presentThreadShell,} from "@t3tools/client-runtime/state/models";-import { pendingSubagentRequestsByThread } from "@t3tools/client-runtime/state/threads";+import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";import type { AnyRouter } from "@tanstack/react-router";import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";import type { ClientSettings } from "@t3tools/contracts/settings";@@ -20,6 +20,7 @@ import { getClientSettings, subscribeClientSettings } from "../hooks/useSettingsimport { isWindowsPlatform } from "../lib/utils";import { environmentSummaries } from "../state/presentation";import { environmentShell } from "../state/shell";+import { environmentThreadShells } from "../state/threads";import {hasDesktopNotifications,hasNotificationSound,@@ -173,10 +174,22 @@ export function startThreadNotifications() => {const previous = entry.previous;const next = new Map<ThreadId, NotificationState>();- const subagentRequests = pendingSubagentRequestsByThread(threads);+ // A parent here also hears of what its tasks on linked environments ask.+ const subagentRequests = registry.get(+ environmentThreadShells.pendingSubagentRequestsAtom(environmentId),+ );+ const delegatedUnderParent = registry.get(environmentThreadShells.delegatedUnderParentAtom);const changed: Array<[NotificationState | undefined, NotificationState]> = [];for (const rawThread of threads) {- if (rawThread.lineage.relationshipToParent === "subagent") continue;+ if (+ isShownUnderParent(+ { environmentId, threadId: rawThread.id },+ rawThread.lineage,+ delegatedUnderParent,+ )+ ) {+ continue;+ }const prior = previous.get(rawThread.id);const subagentRequest = subagentRequests.get(rawThread.id) ?? null;if (prior?.raw === rawThread && prior.subagentRequest === subagentRequest) {@@ -227,10 +240,11 @@ export function startThreadNotifications(if (state) present(environmentId, state, kind);}),};+ let threads: ReadonlyArray<OrchestrationV2ThreadShell> | null = null;const unsubscribeShell = registry.subscribe(environmentShell.stateValueAtom(environmentId),(shell) => {- const threads =+ threads =shell.status === "live" && Option.isSome(shell.snapshot)? shell.snapshot.value.threads: null;@@ -243,8 +257,21 @@ export function startThreadNotifications(},{ immediate: true },);+ const reobserve = () => {+ if (threads !== null) observeThreads(environmentId, entry, threads);+ };+ const unsubscribeRequests = registry.subscribe(+ environmentThreadShells.pendingSubagentRequestsAtom(environmentId),+ reobserve,+ );+ const unsubscribeDelegated = registry.subscribe(+ environmentThreadShells.delegatedUnderParentAtom,+ reobserve,+ );entry.unsubscribe = () => {unsubscribeShell();+ unsubscribeRequests();+ unsubscribeDelegated();entry.gate.clear();};return entry;diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex fbfa67e61bf..dfcdce4c557 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -237,9 +237,12 @@ interface MessagesTimelineProps {onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;renderHtmlRender?: TimelineRowSharedState["renderHtmlRender"];turnItemSource?: TimelineRowSharedState["turnItemSource"];+ /** The thread this one is a subagent of; `open` is absent when it cannot be opened from here. */parentThreadLink?: {- readonly threadId: ThreadId;readonly title: string;+ /** Where it runs, when that is another environment. */+ readonly environmentLabel?: string;+ readonly open?: () => void;} | null;workflowOpening?: WorkflowOpening | null;onForkFromRun?: (input: {@@ -1093,10 +1096,15 @@ const ConversationTimeline = memo(function ConversationTimeline({<div className="chat-content-lane pt-1 sm:pt-2"><TimelineSystemDividerlabel="Subagent of"- detail={parentThreadLink.title}+ detail={+ parentThreadLink.environmentLabel === undefined+ ? parentThreadLink.title+ : `${parentThreadLink.title} on ${parentThreadLink.environmentLabel}`+ }icon={BotIcon}- actionLabel="Open parent thread"- onAction={() => onOpenThread(parentThreadLink.threadId)}+ {...(parentThreadLink.open === undefined+ ? {}+ : { actionLabel: "Open parent thread", onAction: parentThreadLink.open })}/></div></div>diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsxindex 66fc6b6f21e..b37f9d1d107 100644--- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx@@ -32,8 +32,10 @@ import {isProviderNativeSubagentThread,NodeId,type EnvironmentId,+ type OrchestrationV2RemoteTaskChild,type OrchestrationV2Subagent,type OrchestrationV2ThreadShell,+ type ServerProvider,type ThreadId,} from "@t3tools/contracts";import { deriveSubagentElapsedMs } from "@t3tools/shared/orchestrationTiming";@@ -61,7 +63,7 @@ import {useThreadProjection,useThreadRelationshipShells,} from "../../state/entities";-import { useEnvironmentProviders } from "../../state/environments";+import { useEnvironment, useEnvironmentProviders } from "../../state/environments";import { threadEnvironment } from "../../state/threads";import { orchestrationEnvironment } from "../../state/orchestration";import { useAtomCommand } from "../../state/use-atom-command";@@ -217,6 +219,74 @@ function currentSubagent<Agent extends RuntimeSubagent>(};}+/**+ * A task delegated to a linked environment. It has no thread here, so it opens+ * the thread there, when this client is connected to that environment.+ */+function RemoteSubagentRow(props: {+ readonly agent: OrchestrationV2Subagent & {+ readonly remoteChild: OrchestrationV2RemoteTaskChild;+ };+ readonly provider: ServerProvider | undefined;+}) {+ const navigate = useNavigate();+ const environment = useEnvironment(props.agent.remoteChild.environmentId);+ const { remoteChild } = props.agent;+ const status = props.agent.status;+ const failed = status === "failed";+ const title = relationshipThreadTitle({+ title: props.agent.title ?? "Subagent",+ isSubagent: true,+ });+ return (+ <li className="group relative flex h-8 items-center rounded-lg">+ <Tooltip>+ <TooltipTrigger+ delay={200}+ render={+ <ThreadDetailsControl+ size="sm"+ variant="ghost"+ part="row"+ disabled={environment === null}+ onClick={() =>+ void navigate({+ to: "/$environmentId/$threadId",+ params: buildThreadRouteParams(+ scopeThreadRef(remoteChild.environmentId, remoteChild.threadId),+ ),+ })+ }+ />+ }+ >+ <ThreadRelationshipIcon+ driver={props.agent.driver}+ provider={props.provider}+ fallbackIcon={BotIcon}+ status={status}+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">+ {title}+ </span>+ </span>+ <span+ className={`shrink-0 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"}`}+ >+ on {remoteChild.label} · {threadRelationshipStatusLabel(status)}+ </span>+ </TooltipTrigger>+ <TooltipPopup side="left">+ {environment === null+ ? `Runs on ${remoteChild.label}. Connect to it to open the thread there.`+ : `Open on ${remoteChild.label}`}+ </TooltipPopup>+ </Tooltip>+ </li>+ );+}+export function ThreadRelationshipsPanel(props: {readonly environmentId: EnvironmentId;readonly threadId: ThreadId;@@ -332,12 +402,17 @@ export function ThreadRelationshipsPanel(props: {{ id: "active", label: null, rows: active, expanded: true },{ id: "previous", label: "Previous agents", rows: previous, expanded: false },];+ // Tasks running in a linked environment have no thread here; they get their own rows.+ const remoteSubagents = (projection?.subagents ?? []).filter(+ (agent): agent is OrchestrationV2Subagent & { remoteChild: OrchestrationV2RemoteTaskChild } =>+ agent.remoteChild !== undefined,+ );const runningCount =(projection?.subagents.filter((agent) => agent.childThreadId === null && agent.status === "running",).length ?? 0) + active.filter(({ edge }) => edge.status === "running").length;- if (relationshipRows.length === 0 && runningCount === 0) {+ if (relationshipRows.length === 0 && runningCount === 0 && remoteSubagents.length === 0) {return null;}@@ -700,6 +775,20 @@ export function ThreadRelationshipsPanel(props: {}</ThreadLineageGroup>))}+ {remoteSubagents.length > 0 ? (+ <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>+ {remoteSubagents.map((agent) => (+ <RemoteSubagentRow+ key={agent.id}+ agent={agent}+ // Its provider instance belongs to the environment it runs in.+ provider={providersByEnvironment+ .get(agent.remoteChild.environmentId)+ ?.find((entry) => entry.instanceId === agent.providerInstanceId)}+ />+ ))}+ </ThreadLineageRowList>+ ) : null}</ThreadDetailsSection>);}diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsxindex 25626011408..96387b59df2 100644--- a/apps/web/src/components/chat/V2LifecycleRow.tsx+++ b/apps/web/src/components/chat/V2LifecycleRow.tsx@@ -3,6 +3,9 @@ import { AgentElapsed } from "./AgentElapsed";import { projectedSubagentsToRuntime } from "@t3tools/client-runtime/state/subagentRuntime";import type { ReactNode } from "react";import { useThreadShell, useProject } from "../../state/entities";+import { useEnvironment } from "../../state/environments";+import { buildThreadRouteParams } from "../../threadRoutes";+import { useNavigate } from "@tanstack/react-router";import { SubagentTooltipContent } from "./SubagentTooltipContent";import { useAtomValue } from "@effect/atom-react";import { scopeThreadRef, scopeProjectRef } from "@t3tools/client-runtime/environment";@@ -21,6 +24,7 @@ import {ProviderDriverKind,type OrchestrationV2Notification,type OrchestrationV2TurnItem,+ type OrchestrationV2RemoteTaskChild,type OrchestrationV2Subagent,type ProviderInstanceId,type ServerProvider,@@ -199,6 +203,7 @@ export function V2LifecycleRow(props: {startedAt={item.startedAt}completedAt={item.completedAt}threadId={item.childThreadId}+ remote={item.remoteChild}onOpenThread={props.onOpenThread}/>);@@ -398,6 +403,8 @@ function SubagentTimelineLink(props: {readonly startedAt: DateTime.Utc | null;readonly completedAt: DateTime.Utc | null;readonly threadId: ThreadId | null;+ /** The thread in a linked environment that runs this task, when it runs there. */+ readonly remote?: OrchestrationV2RemoteTaskChild | undefined;readonly onOpenThread: (threadId: ThreadId) => void;readonly event?: {readonly status: OrchestrationV2TurnItem["status"] | null;@@ -409,7 +416,21 @@ function SubagentTimelineLink(props: {environmentThreadDetails.threadAtom(props.parentRef),(thread) => thread?.projection.subagents.find((agent) => agent.id === props.subagentId) ?? null,);+ const remote = props.remote ?? agent?.remoteChild;+ const remoteEnvironment = useEnvironment(remote?.environmentId ?? null);+ const navigate = useNavigate();const threadId = props.threadId;+ // A task in a linked environment opens there, if this client is connected to it.+ const open =+ threadId !== null+ ? () => props.onOpenThread(threadId)+ : remote !== undefined && remoteEnvironment !== null+ ? () =>+ void navigate({+ to: "/$environmentId/$threadId",+ params: buildThreadRouteParams(scopeThreadRef(remote.environmentId, remote.threadId)),+ })+ : null;const liveStatus = agent?.status ?? props.status;const status = props.event ? props.event.status : liveStatus;const statusLabel = props.event?.label ?? subagentStatusVisual(liveStatus).label;@@ -434,7 +455,14 @@ function SubagentTimelineLink(props: {status={status ?? undefined}/><span className="min-w-0 flex-1">- <span className="block truncate text-xs font-medium text-foreground">{props.title}</span>+ <span className="flex items-baseline gap-2">+ <span className="min-w-0 truncate text-xs font-medium text-foreground">+ {props.title}+ </span>+ {remote !== undefined ? (+ <span className="shrink-0 text-xs text-muted-foreground">on {remote.label}</span>+ ) : null}+ </span><spanclassName={cn("block text-2xs leading-relaxed",@@ -460,7 +488,7 @@ function SubagentTimelineLink(props: {<span className="shrink-0 text-xs text-muted-foreground tabular-nums">{props.event ? props.event.timestamp : <SubagentElapsed agent={timing} />}</span>- {threadId !== null ? (+ {open !== null ? (<ChevronRightIconaria-hiddenclassName="size-3.5 shrink-0 text-muted-foreground/60 transition-colors group-hover/subagent:text-foreground"@@ -475,7 +503,7 @@ function SubagentTimelineLink(props: {<TooltipTriggerdelay={200}render={- threadId === null ? (+ open === null ? (<div data-v2-item-type="subagent" aria-description={statusLabel} className={className}>{content}</div>@@ -485,7 +513,7 @@ function SubagentTimelineLink(props: {data-v2-item-type="subagent"aria-label={`Open ${props.title}`}aria-description={statusLabel}- onClick={() => props.onOpenThread(threadId)}+ onClick={open}className={cn(className,"cursor-pointer transition-colors hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70",diff --git a/apps/web/src/components/sidebar/routeReveal.ts b/apps/web/src/components/sidebar/routeReveal.tsindex de2a64ca858..df9d45dc9d3 100644--- a/apps/web/src/components/sidebar/routeReveal.ts+++ b/apps/web/src/components/sidebar/routeReveal.ts@@ -52,16 +52,18 @@ export function resolveSidebarRouteReveal<T extends RevealableThread>(input: {readonly routeKey: string | null;readonly isSearching: boolean;readonly scopedProjectKeys: ReadonlySet<string> | null;+ readonly delegatedUnderParent: ReadonlySet<string>;readonly findThread: (key: string) => T | undefined;}): { readonly pendingKey: string | null; readonly widensScope: boolean } {- const { reveal, routeKey, isSearching, scopedProjectKeys, findThread } = input;+ const { reveal, routeKey, isSearching, scopedProjectKeys, delegatedUnderParent, findThread } =+ input;const pendingKey = pendingSidebarRouteReveal(reveal, routeKey);// Search results replace the thread list; the reveal waits for it to return.const thread = pendingKey === null || isSearching ? undefined : findThread(pendingKey);const widensScope =thread !== undefined &&scopedProjectKeys !== null &&- filterSidebarV2VisibleThreads([thread], scopedProjectKeys).length === 0 &&- filterSidebarV2VisibleThreads([thread], null).length === 1;+ filterSidebarV2VisibleThreads([thread], scopedProjectKeys, delegatedUnderParent).length === 0 &&+ filterSidebarV2VisibleThreads([thread], null, delegatedUnderParent).length === 1;return { pendingKey, widensScope };}diff --git a/apps/web/src/hooks/useSidebarProjectGroups.ts b/apps/web/src/hooks/useSidebarProjectGroups.tsindex cb1b3b10132..5f4008aea48 100644--- a/apps/web/src/hooks/useSidebarProjectGroups.ts+++ b/apps/web/src/hooks/useSidebarProjectGroups.ts@@ -2,7 +2,7 @@ import { orderItemsByPreferredIds, sortSidebarV2ProjectGroups } from "../componeimport { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject";import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";import { useEnvironmentIdentities, usePrimaryEnvironmentId } from "../state/environments";-import { useProjects, useQuietThreadShells } from "../state/entities";+import { useDelegatedUnderParent, useProjects, useQuietThreadShells } from "../state/entities";import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";import { useClientSettings } from "./useSettings";@@ -11,6 +11,7 @@ export function useSidebarProjectGroups() {// Activity order lags a running thread's streaming ticks until its next// real change; reading every tick re-rendered the whole sidebar with it.const threads = useQuietThreadShells();+ const delegatedUnderParent = useDelegatedUnderParent();const projectOrder = useUiStateStore((store) => store.projectOrder);const sortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);const groupingSettings = useClientSettings(selectProjectGroupingSettings);@@ -35,5 +36,5 @@ export function useSidebarProjectGroups() {primaryEnvironmentId,resolveEnvironmentLabel: (environmentId) => labels.get(environmentId) ?? null,});- return sortSidebarV2ProjectGroups(unsortedGroups, threads, sortOrder);+ return sortSidebarV2ProjectGroups(unsortedGroups, threads, sortOrder, delegatedUnderParent);}diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.tsindex af71b314c4c..da3c500ca6b 100644--- a/apps/web/src/state/entities.ts+++ b/apps/web/src/state/entities.ts@@ -112,6 +112,11 @@ export function useAllEnvironmentProjectSnapshotsReady(): boolean {return useAtomValue(allEnvironmentProjectSnapshotsReadyAtom);}+/** Tasks linked environments run for a listed thread, by thread key; lists show them under it. */+export function useDelegatedUnderParent(): ReadonlySet<string> {+ return useAtomValue(environmentThreadShells.delegatedUnderParentAtom);+}+export function useThreadShellsForProjectRefs(refs: ReadonlyArray<ScopedProjectRef>,): ReadonlyArray<EnvironmentThreadShell> {diff --git a/docs/internals/remote.md b/docs/internals/remote.mdindex 5bc642e8d14..bb12f32621a 100644--- a/docs/internals/remote.md+++ b/docs/internals/remote.md@@ -117,6 +117,15 @@ shared access declarations, not tool by tool:Reads are not fenced, and a client's own `thread.create` can never carry`linkOrigin`.+**A delegated task can run in a linked environment.** Its child is then an+ordinary thread there, so the parent here records the task without a child+thread of its own (`remoteChild` instead of `childThreadId`). A follower in+[`RemoteDelegation`](../../apps/server/src/peer/RemoteDelegation.ts) waits on+that thread and completes the task with `delegated_task.remote.complete`. That+internal command reuses the parent half of a local finalize, so the parent+wakes the same way. Open remote tasks are followed again at startup, which is+also what keeps restart recovery from treating them as abandoned provider work.+The link is routing, not isolation: an agent the link starts runs as thereceiving environment's user. **A full-access link is therefore not fenced**:its agents can already do anything that user can, so the fence would only stopdiff --git a/docs/user/remote-access.md b/docs/user/remote-access.mdindex 6d6bc234290..a14285d9744 100644--- a/docs/user/remote-access.md+++ b/docs/user/remote-access.md@@ -269,6 +269,13 @@ it. From a terminal, useremoves it here.- Links last 30 days. Link again with a new pairing code to renew one.+An agent can also hand a task to a linked machine with `delegate_task`: it runs+there as an ordinary thread, in the project with the same repository (or the+one `target.projectId` names), and this thread wakes with its result when it+ends, as for any delegated task. It keeps following the task across restarts.+If the other machine revokes the link, or the link is removed here, the task+fails with that reason.+## Manage or revoke accessOn the host, **Settings → Sharing & access** lets authorized administrators creatediff --git a/evals/mcp-tool-use/run.test.ts b/evals/mcp-tool-use/run.test.tsindex b0241eeea8d..2e8f02f27e7 100644--- a/evals/mcp-tool-use/run.test.ts+++ b/evals/mcp-tool-use/run.test.ts@@ -17,7 +17,7 @@ import {shellRequest,t3SystemAppend,} from "./run.ts";-import { taskPrompt } from "../../apps/server/src/mcp/OrchestratorMcpService.ts";+import { taskPrompt } from "../../apps/server/src/mcp/delegatedTaskModes.ts";it("grades Codex shell and subagent calls with the shared rules", () => {const calls = [diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.tsindex f65ef239ed7..a83ab675cf8 100644--- a/evals/mcp-tool-use/run.ts+++ b/evals/mcp-tool-use/run.ts@@ -26,7 +26,7 @@ import { Tool } from "effect/ai";import * as McpSchema from "effect/ai/McpSchema";import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";-import { taskPrompt } from "../../apps/server/src/mcp/OrchestratorMcpService.ts";+import { taskPrompt } from "../../apps/server/src/mcp/delegatedTaskModes.ts";import * as McpInvocationContext from "../../apps/server/src/mcp/McpInvocationContext.ts";import { advertisedJsonSchema } from "../../apps/server/src/mcp/advertisedJsonSchema.ts";import { ORCHESTRATOR_MCP_RUNNING_TASK_NEXT } from "@t3tools/contracts";diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.tsindex 9dc72dc4930..ac40471a853 100644--- a/packages/client-runtime/src/state/models.ts+++ b/packages/client-runtime/src/state/models.ts@@ -148,6 +148,8 @@ export interface EnvironmentThreadShell {readonly lineage: OrchestrationV2ThreadShell["lineage"];readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"];readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null;+ /** The thread in a linked environment that delegated this one, if one did. */+ readonly delegatedFrom: OrchestrationV2ThreadShell["delegatedFrom"] | null;readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"];readonly latestRun: ThreadRunSummary | null;readonly runtime: ThreadRuntimeSummary | null;@@ -300,6 +302,7 @@ export function presentThreadShell(lineage: thread.lineage,forkedFrom: thread.forkedFrom,linkOrigin: thread.linkOrigin ?? null,+ delegatedFrom: thread.delegatedFrom ?? null,activeProviderThreadId: thread.activeProviderThreadId,latestRun,runtime,diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.tsindex 2dcc3233db3..ec40d5f679e 100644--- a/packages/client-runtime/src/state/threadShell.test.ts+++ b/packages/client-runtime/src/state/threadShell.test.ts@@ -215,6 +215,152 @@ describe("v2 thread shell lists", () => {registry.dispose();});+ it("lists a task a linked environment runs for a listed thread under that thread", () => {+ const { registry, threads, snapshotAtom, catalogValueAtom } = makeHarness([+ environmentId,+ remoteEnvironmentId,+ ]);+ const parent = v2ThreadShell;+ const task = {+ ...v2ThreadShell,+ id: ThreadId.make("remote-task"),+ creationSource: "mcp" as const,+ status: "running" as const,+ activityRunStatus: "running" as const,+ delegatedFrom: { environmentId, threadId: parent.id, title: parent.title },+ };+ const helper = {+ ...task,+ id: ThreadId.make("remote-helper"),+ delegatedFrom: undefined,+ lineage: {+ ...task.lineage,+ parentThreadId: task.id,+ relationshipToParent: "subagent" as const,+ },+ };+ const approval = {+ id: RuntimeRequestId.make("cat-file"),+ kind: "command" as const,+ createdAt: v2Now,+ };+ registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [parent] });+ registry.set(snapshotAtom(remoteEnvironmentId), {+ ...v2ShellSnapshot,+ threads: [task, helper],+ });+ const parentRef = { environmentId, threadId: parent.id };+ const inputs = threads.childThreadInputsAtom(parentRef);+ const disposeNavigation = registry.mount(threads.navigationThreadShellsAtom);+ const disposeParent = registry.mount(threads.threadShellAtom(parentRef));+ const disposeInputs = registry.mount(inputs);+ const listed = () =>+ registry+ .get(threads.navigationThreadShellsAtom)+ .map((thread) => `${thread.environmentId}/${thread.id}`);+ expect(listed()).toEqual([`${environmentId}/${parent.id}`]);++ // The helper the task started there asks for approval: the parent here hears of it.+ registry.set(snapshotAtom(remoteEnvironmentId), {+ ...v2ShellSnapshot,+ threads: [task, { ...helper, pendingRuntimeRequest: approval }],+ });+ expect(registry.get(threads.threadShellAtom(parentRef))?.pendingSubagentRequest).toBe(+ "approval",+ );+ expect(registry.get(inputs).map((thread) => `${thread.environmentId}/${thread.id}`)).toEqual([+ `${remoteEnvironmentId}/${helper.id}`,+ ]);++ // A task whose parent is gone there is listed on its own, as is one whose+ // parent's environment is switched off.+ registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [] });+ expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);+ // Archiving the parent here leaves the task there unarchived, so it is listed on its own.+ registry.set(snapshotAtom(environmentId), {+ ...v2ShellSnapshot,+ threads: [{ ...parent, archivedAt: v2Now }],+ });+ expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);+ registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [parent] });+ expect(listed()).toEqual([`${environmentId}/${parent.id}`]);+ const catalog = registry.get(catalogValueAtom);+ const entries = new Map(catalog.entries);+ entries.set(environmentId, { ...entries.get(environmentId)!, enabled: false });+ registry.set(catalogValueAtom, { ...catalog, entries });+ expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);+ disposeInputs();+ disposeParent();+ disposeNavigation();+ registry.dispose();+ });++ it("brings an approval up a chain of tasks across three environments to its root", () => {+ const thirdEnvironmentId = EnvironmentId.make("third-environment-v2");+ const { registry, threads, snapshotAtom } = makeHarness([+ environmentId,+ remoteEnvironmentId,+ thirdEnvironmentId,+ ]);+ const root = v2ThreadShell;+ const running = {+ creationSource: "mcp" as const,+ status: "running" as const,+ activityRunStatus: "running" as const,+ };+ const task = {+ ...v2ThreadShell,+ ...running,+ id: ThreadId.make("remote-task"),+ delegatedFrom: { environmentId, threadId: root.id, title: root.title },+ };+ const nestedTask = {+ ...v2ThreadShell,+ ...running,+ id: ThreadId.make("third-task"),+ delegatedFrom: { environmentId: remoteEnvironmentId, threadId: task.id, title: task.title },+ };+ // A task the middle one delegates back to the root's own environment.+ const returningTask = {+ ...nestedTask,+ id: ThreadId.make("returning-task"),+ };+ const approval = {+ id: RuntimeRequestId.make("cat-file"),+ kind: "command" as const,+ createdAt: v2Now,+ };+ registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root] });+ registry.set(snapshotAtom(remoteEnvironmentId), { ...v2ShellSnapshot, threads: [task] });+ registry.set(snapshotAtom(thirdEnvironmentId), {+ ...v2ShellSnapshot,+ threads: [{ ...nestedTask, pendingRuntimeRequest: approval }],+ });+ const rootRef = { environmentId, threadId: root.id };+ const taskRef = { environmentId: remoteEnvironmentId, threadId: task.id };+ const disposeRoot = registry.mount(threads.threadShellAtom(rootRef));+ const disposeTask = registry.mount(threads.threadShellAtom(taskRef));+ expect(registry.get(threads.threadShellAtom(taskRef))?.pendingSubagentRequest).toBe("approval");+ expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBe("approval");++ // Once it is answered, neither stays flagged.+ registry.set(snapshotAtom(thirdEnvironmentId), {+ ...v2ShellSnapshot,+ threads: [nestedTask],+ });+ expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBeNull();++ // Environments that delegate to each other still settle on the root's flag.+ registry.set(snapshotAtom(environmentId), {+ ...v2ShellSnapshot,+ threads: [root, { ...returningTask, pendingRuntimeRequest: approval }],+ });+ expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBe("approval");+ disposeTask();+ disposeRoot();+ registry.dispose();+ });+it.each([{ reason: "switched-off", state: { enabled: false } },{diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.tsindex 8d61ff6ac56..69df72418c2 100644--- a/packages/client-runtime/src/state/threadShell.ts+++ b/packages/client-runtime/src/state/threadShell.ts@@ -45,6 +45,20 @@ const isChildRunLive = (thread.status === "running" ||thread.status === "waiting";+/**+ * Whether a thread shows under its parent rather than in thread lists: a+ * subagent, or a task a linked environment delegated here whose parent the+ * client lists (`delegatedUnderParent`, by thread key). A task whose parent+ * the client cannot list stays in the lists, so its work is never out of reach.+ */+export function isShownUnderParent(+ ref: ScopedThreadRef,+ lineage: OrchestrationV2ThreadShell["lineage"],+ delegatedUnderParent: ReadonlySet<string>,+): boolean {+ return lineage.relationshipToParent === "subagent" || delegatedUnderParent.has(threadKey(ref));+}+/** Provider-nativesubagents ask on their parent, so they are skipped. */function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentRequest | null {@@ -52,7 +66,7 @@ function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReqif (kind === undefined ||kind === "auth_refresh" ||- thread.lineage.relationshipToParent !== "subagent" ||+ (thread.lineage.relationshipToParent !== "subagent" && thread.delegatedFrom === undefined) ||isProviderNativeSubagentThread(thread) ||!isChildRunLive(thread)) {@@ -61,28 +75,51 @@ function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReqreturn kind === "user_input" ? "user_input" : "approval";}-export function pendingSubagentRequestsByThread(+/**+ * The threads to flag for a subagent's live question or approval, up its+ * subagent chain. `delegated` are tasks this environment's threads delegated+ * to linked environments, with what each one, or its own subagents, asks.+ */+function pendingSubagentRequestsByThread(threads: ReadonlyArray<OrchestrationV2ThreadShell>,+ delegated: ReadonlyArray<{+ readonly parentThreadId: ThreadId;+ readonly request: PendingSubagentRequest;+ }> = [],): ReadonlyMap<ThreadId, PendingSubagentRequest> {const requests = new Map<ThreadId, PendingSubagentRequest>();let byId: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell> | undefined;- for (const child of threads) {- const request = subagentRequest(child);- if (request === null) continue;+ const flag = (+ firstParentId: ThreadId | null,+ request: PendingSubagentRequest,+ seen: Set<ThreadId>,+ ) => {byId ??= new Map(threads.map((thread) => [thread.id, thread] as const));- const seen = new Set<ThreadId>([child.id]);- let current: OrchestrationV2ThreadShell | undefined = child;- while (current?.lineage.relationshipToParent === "subagent") {- const parentId: ThreadId | null = current.lineage.parentThreadId;- if (parentId === null || seen.has(parentId)) break;+ let parentId = firstParentId;+ while (parentId !== null && !seen.has(parentId)) {seen.add(parentId);if (requests.get(parentId) !== "approval") requests.set(parentId, request);- current = byId.get(parentId);+ const parent = byId.get(parentId);+ parentId =+ parent?.lineage.relationshipToParent === "subagent" ? parent.lineage.parentThreadId : null;}+ };+ for (const child of threads) {+ if (child.lineage.relationshipToParent !== "subagent") continue;+ const request = subagentRequest(child);+ if (request !== null) flag(child.lineage.parentThreadId, request, new Set([child.id]));}+ for (const task of delegated) flag(task.parentThreadId, task.request, new Set());return requests.size === 0 ? EMPTY_SUBAGENT_REQUESTS : requests;}+const sameRequests = (+ left: ReadonlyMap<ThreadId, PendingSubagentRequest>,+ right: ReadonlyMap<ThreadId, PendingSubagentRequest>,+) =>+ left.size === right.size &&+ [...right].every(([threadId, request]) => left.get(threadId) === request);+export function childThreadInputsTitle(children: ReadonlyArray<Pick<EnvironmentThreadShell, "hasPendingApprovals">>,): string {@@ -177,16 +214,75 @@ export function createEnvironmentThreadShellAtoms(input: {}).pipe(Atom.withLabel(`environment-thread-index:${environmentId}`)),);- const pendingSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => {+ // What an environment's own subagents ask. Kept apart from the tasks other+ // environments run for it, so two environments delegating to each other+ // never read each other's totals.+ const localSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => {let previous = EMPTY_SUBAGENT_REQUESTS;return Atom.make((get) => {const next = pendingSubagentRequestsByThread(get(environmentThreadsAtom(environmentId)));- if (- next.size === previous.size &&- [...next].every(([threadId, request]) => previous.get(threadId) === request)- ) {- return previous;+ if (sameRequests(previous, next)) return previous;+ previous = next;+ return next;+ }).pipe(Atom.withLabel(`environment-local-subagent-requests:${environmentId}`));+ });++ // Flags for environments whose threads delegated tasks, counting what each task+ // or anything it delegated on asks. Each pass settles one more hop of a chain;+ // flags only grow, so environments delegating to each other settle too.+ const delegatedSubagentRequestsAtom = Atom.make((get) => {+ const tasksByDelegator = new Map<+ EnvironmentId,+ Array<{+ readonly runsIn: EnvironmentId;+ readonly thread: OrchestrationV2ThreadShell;+ readonly parentThreadId: ThreadId;+ }>+ >();+ for (const runsIn of enabledEnvironmentIds(get(input.catalogValueAtom))) {+ for (const thread of get(environmentThreadsAtom(runsIn))) {+ const from = thread.delegatedFrom;+ if (from === undefined || from.environmentId === runsIn) continue;+ const task = { runsIn, thread, parentThreadId: from.threadId };+ const tasks = tasksByDelegator.get(from.environmentId);+ if (tasks === undefined) tasksByDelegator.set(from.environmentId, [task]);+ else tasks.push(task);}+ }+ let flags = new Map<EnvironmentId, ReadonlyMap<ThreadId, PendingSubagentRequest>>();+ const requestsOf = (environmentId: EnvironmentId) =>+ flags.get(environmentId) ?? get(localSubagentRequestsAtom(environmentId));+ for (let changed = tasksByDelegator.size > 0; changed;) {+ changed = false;+ const next = new Map(flags);+ for (const [environmentId, tasks] of tasksByDelegator) {+ const delegated = tasks.flatMap(({ runsIn, thread, parentThreadId }) => {+ const own = subagentRequest(thread);+ const nested = requestsOf(runsIn).get(thread.id);+ const request = own === "approval" ? own : (nested ?? own);+ return request === null ? [] : [{ parentThreadId, request }];+ });+ if (delegated.length === 0) continue;+ const requests = pendingSubagentRequestsByThread(+ get(environmentThreadsAtom(environmentId)),+ delegated,+ );+ if (sameRequests(requestsOf(environmentId), requests)) continue;+ next.set(environmentId, requests);+ changed = true;+ }+ flags = next;+ }+ return flags;+ }).pipe(Atom.withLabel("environment-delegated-subagent-requests"));++ const pendingSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => {+ let previous = EMPTY_SUBAGENT_REQUESTS;+ return Atom.make((get) => {+ const next =+ get(delegatedSubagentRequestsAtom).get(environmentId) ??+ get(localSubagentRequestsAtom(environmentId));+ if (sameRequests(previous, next)) return previous;previous = next;return next;}).pipe(Atom.withLabel(`environment-pending-subagent-requests:${environmentId}`));@@ -280,30 +376,47 @@ export function createEnvironmentThreadShellAtoms(input: {});// Child approvals and questions are hidden with their sidebar rows. Read their- // shell summaries, without subscribing to every child transcript.+ // shell summaries, without subscribing to every child transcript. A task+ // delegated to a linked environment is a child too, with its own subagents.const childThreadInputsAtomFamily = Atom.family((key: string) => {- const ref = parseThreadKey(key);let previous: ReadonlyArray<EnvironmentThreadShell> = [];return Atom.make((get) => {- const children = new Map<ThreadId, OrchestrationV2ThreadShell[]>();- for (const thread of get(environmentThreadsAtom(ref.environmentId))) {- const parent = thread.lineage.parentThreadId;- if (parent === null || thread.lineage.relationshipToParent !== "subagent") continue;- const siblings = children.get(parent);- if (siblings) siblings.push(thread);- else children.set(parent, [thread]);+ const children = new Map<+ string,+ Array<{ environmentId: EnvironmentId; thread: OrchestrationV2ThreadShell }>+ >();+ const addChild = (+ parent: ScopedThreadRef,+ environmentId: EnvironmentId,+ thread: OrchestrationV2ThreadShell,+ ) => {+ const siblings = children.get(threadKey(parent));+ if (siblings) siblings.push({ environmentId, thread });+ else children.set(threadKey(parent), [{ environmentId, thread }]);+ };+ for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {+ for (const thread of get(environmentThreadsAtom(environmentId))) {+ const parent = thread.lineage.parentThreadId;+ if (parent !== null && thread.lineage.relationshipToParent === "subagent") {+ addChild({ environmentId, threadId: parent }, environmentId, thread);+ } else if (thread.delegatedFrom !== undefined) {+ addChild(thread.delegatedFrom, environmentId, thread);+ }+ }}- const subagentRequests = get(pendingSubagentRequestsAtom(ref.environmentId));- const seen = new Set<ThreadId>([ref.threadId]);- const pending = [ref.threadId];+ const seen = new Set<string>([key]);+ const pending = [key];const next: EnvironmentThreadShell[] = [];for (const parent of pending) {- for (const child of children.get(parent) ?? []) {- if (seen.has(child.id)) continue;- seen.add(child.id);- pending.push(child.id);- if (subagentRequest(child) !== null) {- next.push(scopedThread(ref.environmentId, child, subagentRequests));+ for (const { environmentId, thread } of children.get(parent) ?? []) {+ const childKey = threadKey({ environmentId, threadId: thread.id });+ if (seen.has(childKey)) continue;+ seen.add(childKey);+ pending.push(childKey);+ if (subagentRequest(thread) !== null) {+ next.push(+ scopedThread(environmentId, thread, get(pendingSubagentRequestsAtom(environmentId))),+ );}}}@@ -313,6 +426,7 @@ export function createEnvironmentThreadShellAtoms(input: {previous.length === next.length &&previous.every((thread, index) =>+ thread.environmentId === next[index]?.environmentId &&thread.id === next[index]?.id &&thread.title === next[index]?.title &&thread.hasPendingApprovals === next[index]?.hasPendingApprovals,@@ -402,14 +516,47 @@ export function createEnvironmentThreadShellAtoms(input: {return next;}).pipe(Atom.withLabel("environment-quiet-thread-shell-list"));+ let previousDelegatedUnderParent: ReadonlySet<string> = new Set();+ const delegatedUnderParentAtom = Atom.make((get) => {+ const environmentIds = new Set(enabledEnvironmentIds(get(input.catalogValueAtom)));+ const next = new Set<string>();+ for (const environmentId of environmentIds) {+ for (const thread of get(environmentThreadsAtom(environmentId))) {+ const parent = thread.delegatedFrom;+ if (+ parent !== undefined &&+ environmentIds.has(parent.environmentId) &&+ // An archived parent leaves navigation; its task there stays listed on its own.+ get(environmentThreadIndexAtom(parent.environmentId)).get(parent.threadId)?.archivedAt ===+ null+ ) {+ next.add(threadKey({ environmentId, threadId: thread.id }));+ }+ }+ }+ if (+ next.size === previousDelegatedUnderParent.size &&+ [...next].every((key) => previousDelegatedUnderParent.has(key))+ ) {+ return previousDelegatedUnderParent;+ }+ previousDelegatedUnderParent = next;+ return next;+ }).pipe(Atom.withLabel("environment-delegated-under-parent"));+let previousNavigationShells: ReadonlyArray<EnvironmentThreadShell> = [];const navigationThreadShellsAtom = Atom.make((get) => {const next: EnvironmentThreadShell[] = [];+ const underParent = get(delegatedUnderParentAtom);for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {const subagentRequests = get(pendingSubagentRequestsAtom(environmentId));for (const thread of get(environmentThreadsAtom(environmentId))) {- if (thread.archivedAt !== null || thread.lineage.relationshipToParent === "subagent")+ if (+ thread.archivedAt !== null ||+ isShownUnderParent({ environmentId, threadId: thread.id }, thread.lineage, underParent)+ ) {continue;+ }next.push(scopedThread(environmentId, thread, subagentRequests));}}@@ -427,6 +574,8 @@ export function createEnvironmentThreadShellAtoms(input: {threadShellsAtom,quietThreadShellsAtom,navigationThreadShellsAtom,+ delegatedUnderParentAtom,+ pendingSubagentRequestsAtom,threadShellsForProjectRefsAtom: (refs: ReadonlyArray<ScopedProjectRef>) =>threadShellsForProjectRefsAtomFamily(projectRefCollectionKey(refs)),threadShellAtom: (ref: ScopedThreadRef) => threadShellAtomFamily(threadKey(ref)),diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex 8ce02f8b650..2ee6f3d3bd0 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -19,6 +19,7 @@ import {GuestShareId,IsoDateTime,MessageId,+ EnvironmentId,NodeId,ForwardCompatibleUnion,ForwardCompatibleUnionArray,@@ -126,6 +127,17 @@ export type OrchestrationV2LinkOrigin = typeof OrchestrationV2LinkOrigin.Type;export const linkOriginIsFenced = (origin: OrchestrationV2LinkOrigin) =>origin.access !== "full-access";+/**+ * The thread in a linked environment that delegated this one, when it did:+ * this thread is that parent's subagent, run here instead of there.+ */+export const OrchestrationV2DelegatedFrom = Schema.Struct({+ environmentId: EnvironmentId,+ threadId: ThreadId,+ title: Schema.String,+});+export type OrchestrationV2DelegatedFrom = typeof OrchestrationV2DelegatedFrom.Type;+export const OrchestrationV2NativeRefStrength = Schema.Literals(["strong", "weak", "none"]);export type OrchestrationV2NativeRefStrength = typeof OrchestrationV2NativeRefStrength.Type;@@ -438,6 +450,7 @@ export const OrchestrationV2AppThread = Schema.Struct({activeProviderThreadId: Schema.NullOr(ProviderThreadId),historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),+ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),lineage: OrchestrationV2AppThreadLineage,forkedFrom: Schema.NullOr(Schema.Union([@@ -812,6 +825,32 @@ export type OrchestrationV2SubagentWorkflow = typeof OrchestrationV2SubagentWork*/const DedupedBodyMarker = Schema.optionalKey(Schema.Literal(true));+/**+ * Where an app-owned task runs when it runs in a linked environment instead+ * of in a child thread here: that environment and the ordinary thread it runs+ * as there. Such a task has no `childThreadId`.+ */+export const OrchestrationV2RemoteTaskChild = Schema.Struct({+ environmentId: EnvironmentId,+ threadId: ThreadId,+ label: Schema.String,+ /** The run there that carries the task; absent on tasks recorded before it was kept. */+ runId: Schema.optional(RunId),+ /**+ * Nothing is left to stop there: a stop reached it, was refused for good, or the thread+ * or link is gone. A run ending there by itself sets it too, unless the task here was+ * cancelled or stopped and still owes a stop, which its follower keeps sending across+ * restarts. `false`: a Stop here owes one to a task that already had its result.+ */+ stoppedThere: Schema.optional(Schema.Boolean),+ /**+ * Stops asked for here once the task had its result. The count names the+ * one owed, so each reaches the thread there once however often it is sent.+ */+ stopCount: Schema.optional(NonNegativeInt),+});+export type OrchestrationV2RemoteTaskChild = typeof OrchestrationV2RemoteTaskChild.Type;+export const OrchestrationV2Subagent = Schema.Struct({id: NodeId,threadId: ThreadId,@@ -823,6 +862,7 @@ export const OrchestrationV2Subagent = Schema.Struct({providerInstanceId: ProviderInstanceId,providerThreadId: Schema.NullOr(ProviderThreadId),childThreadId: Schema.NullOr(ThreadId),+ remoteChild: Schema.optional(OrchestrationV2RemoteTaskChild),nativeTaskRef: Schema.NullOr(OrchestrationV2ProviderRef),prompt: Schema.String,title: Schema.NullOr(Schema.String),@@ -1663,6 +1703,7 @@ export const OrchestrationV2TurnItem = Schema.Union([driver: ProviderDriverKind,providerInstanceId: ProviderInstanceId,childThreadId: Schema.NullOr(ThreadId),+ remoteChild: Schema.optional(OrchestrationV2RemoteTaskChild),prompt: Schema.String,progress: Schema.optional(Schema.String),result: Schema.NullOr(Schema.String),@@ -1967,6 +2008,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({activeProviderThreadId: Schema.NullOr(ProviderThreadId),historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),+ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),latestRunId: Schema.NullOr(RunId),latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),@@ -2496,6 +2538,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([driver: ProviderDriverKind,providerInstanceId: ProviderInstanceId,childThreadId: Schema.NullOr(ThreadId),+ remoteChild: Schema.optional(OrchestrationV2RemoteTaskChild),prompt: Schema.String,progress: Schema.optional(Schema.String),result: Schema.NullOr(Schema.String),@@ -2801,6 +2844,8 @@ export const OrchestrationV2Command = Schema.Union([worktreePath: Schema.NullOr(TrimmedNonEmptyString),/** Only the server sets this; a client's thread.create never carries one. */linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),+ /** Only the server sets this, with `linkOrigin`, for a linked environment's delegated task. */+ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),importedNativeThread: Schema.optional(Schema.Struct({ref: Schema.Struct({@@ -3287,6 +3332,59 @@ const OrchestrationV2InternalCommand = Schema.Union([}),),}),+ /**+ * Records a delegated task that runs in a linked environment: the task, its+ * node and its turn item on the parent, as `delegated_task.request` does,+ * without a child thread here. `remoteChild` is the thread already launched+ * there. The ids derive from `commandId`, so a retry records nothing new.+ */+ Schema.Struct({+ type: Schema.Literal("delegated_task.remote.request"),+ commandId: CommandId,+ parentThreadId: ThreadId,+ parentRunId: RunId,+ parentNodeId: NodeId,+ task: TrimmedNonEmptyString,+ title: Schema.optional(TrimmedNonEmptyString),+ driver: ProviderDriverKind,+ modelSelection: ModelSelection,+ remoteChild: OrchestrationV2RemoteTaskChild,+ completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])),+ }),+ /**+ * Completes a delegated task that ran in a linked environment, with what its+ * thread there ended as. The parent wakes exactly as for a child here. A+ * task that already has a result keeps it; `stoppedThere` is still recorded,+ * and without it (a Stop or cancel here) the task owes a stop there instead.+ */+ Schema.Struct({+ type: Schema.Literal("delegated_task.remote.complete"),+ commandId: CommandId,+ parentThreadId: ThreadId,+ taskId: NodeId,+ status: Schema.Literals(["completed", "failed", "cancelled", "interrupted"]),+ result: Schema.String,+ /**+ * `ran-out`: the run there ended by itself; `stopped`: a stop from here reached it. Either+ * sets `remoteChild.stoppedThere` on a task this report completes. On a task already+ * cancelled or stopped here only `stopped` does, since a run that ended by itself leaves+ * the stop owed for whatever follows it.+ */+ stoppedThere: Schema.optional(Schema.Literals(["ran-out", "stopped"])),+ /** The stop generation this report acknowledges; absent for the original unnumbered stop. */+ stopCount: Schema.optional(NonNegativeInt),+ }),+ /**+ * Owes a stop to the thread there of a remote task that already has its result, as Stop on+ * a parent stops a finished child here. The task keeps its status, result and completion+ * delivery; its follower sends the stop and reports it with `delegated_task.remote.complete`.+ */+ Schema.Struct({+ type: Schema.Literal("delegated_task.remote.stop"),+ commandId: CommandId,+ parentThreadId: ThreadId,+ taskId: NodeId,+ }),Schema.Struct({type: Schema.Literal("checkpoint.rollback.fail"),commandId: CommandId,diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.tsindex db76b53e01f..97911133f4d 100644--- a/packages/contracts/src/orchestratorMcp.ts+++ b/packages/contracts/src/orchestratorMcp.ts@@ -111,6 +111,18 @@ export const OrchestratorMcpTarget = Schema.Struct({"Options from `orchestrator_capabilities`, such as {effort:'max'}. Given values override inherited. [] or {} clears.",}),),+ environmentId: Schema.optional(+ EnvironmentId.annotate({+ description:+ "Linked environment to run in. Provider and model default to yours; others come from `orchestrator_capabilities` with this `environmentId`.",+ }),+ ),+ projectId: Schema.optional(+ ProjectId.annotate({+ description:+ "With `environmentId`: its project to run in. Default: the one with this project's repository.",+ }),+ ),});export type OrchestratorMcpTarget = typeof OrchestratorMcpTarget.Type;@@ -191,7 +203,12 @@ const OrchestratorMcpRunningTaskNext = Schema.Literal(ORCHESTRATOR_MCP_RUNNING_Texport const OrchestratorMcpDelegateTaskResult = Schema.Struct({taskId: NodeId,- childThreadId: ThreadId,+ /** Null for a task that runs in a linked environment; see `remoteChild`. */+ childThreadId: Schema.NullOr(ThreadId),+ /** The linked environment and thread a remote task runs as. */+ remoteChild: Schema.optional(+ Schema.Struct({ environmentId: EnvironmentId, threadId: ThreadId, label: Schema.String }),+ ),link: Schema.optional(Schema.String),childRunId: Schema.NullOr(RunId),childNodeId: NodeId,@@ -503,6 +520,12 @@ export const OrchestratorMcpThreadWaitInput = Schema.Struct({threadId: ThreadId,runId: Schema.optional(RunId),timeoutMs: Schema.optional(Schema.Finite),+ untilDelegatedWorkSettled: Schema.optional(+ Schema.Boolean.annotate({+ description:+ "Also wait for its delegated and background tasks and their completions to settle. `resultRun` then names the run with its final answer.",+ }),+ ),});export type OrchestratorMcpThreadWaitInput = typeof OrchestratorMcpThreadWaitInput.Type;@@ -512,6 +535,8 @@ export const OrchestratorMcpThreadWaitResult = Schema.Struct({status: OrchestratorMcpThreadStatus,timedOut: Schema.Boolean,next: Schema.optional(OrchestratorMcpRunningTaskNext),+ /** With untilDelegatedWorkSettled, once settled: the run whose reply is the thread's result. */+ resultRun: Schema.optional(Schema.Struct({ runId: RunId, status: OrchestrationV2RunStatus })),});export type OrchestratorMcpThreadWaitResult = typeof OrchestratorMcpThreadWaitResult.Type;