Skip to content

Commit ed57b9b

Browse files
fix(server): a follow-up to a finished remote task is a new task that wakes the parent (pingdotgg#26776)
1 parent e5b5da3 commit ed57b9b

8 files changed

Lines changed: 516 additions & 30 deletions

File tree

‎apps/server/src/mcp/McpToolAccess.ts‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ const refuseOutsideConstruction = (token: symbol) => {
4646
let declare: <P, A, E, R>(
4747
handle: (params: P) => Effect.Effect<A, E, R>,
4848
remote: RemoteCheck<P> | undefined,
49+
forwarded?: Forwarded<P, A, E, R>,
4950
) => Declaration<(params: P) => Effect.Effect<A, E, R>>;
5051

5152
/**
@@ -58,6 +59,16 @@ type RemoteCheck<P> = (
5859
) => Effect.Effect<unknown, OrchestratorMcpFailure, Effect.Services<typeof writingCaller>>;
5960
let remoteCheckOf: <Handler>(declaration: Declaration<Handler>) => RemoteCheck<never> | undefined;
6061

62+
/** What a call answered in a linked environment does here before it returns. */
63+
type Forwarded<P, A, E, R> = (
64+
params: P,
65+
environmentId: EnvironmentId,
66+
result: A,
67+
) => Effect.Effect<A, E, R>;
68+
let forwardedOf: <Handler>(
69+
declaration: Declaration<Handler>,
70+
) => Forwarded<never, unknown, unknown, unknown> | undefined;
71+
6172
type CheckedHandlerOf<D> = D extends Declaration<infer Handler> ? Handler : never;
6273

6374
interface CheckedHandler extends Struct.Lambda {
@@ -74,19 +85,29 @@ let handlersLayer: <Tools extends Record<string, Tool.Any>, EX, RX>(
7485
export class Declaration<out Handler> {
7586
readonly #handle: Handler;
7687
readonly #remote: RemoteCheck<never> | undefined;
88+
readonly #forwarded: Forwarded<never, unknown, unknown, unknown> | undefined;
7789
private constructor(
7890
token: typeof builtHere,
7991
handle: Handler,
8092
remote: RemoteCheck<never> | undefined,
93+
forwarded: Forwarded<never, unknown, unknown, unknown> | undefined,
8194
) {
8295
refuseOutsideConstruction(token);
8396
this.#handle = handle;
8497
this.#remote = remote;
98+
this.#forwarded = forwarded;
8599
}
86100
static {
87-
declare = (handle, remote) => new Declaration(builtHere, handle, remote);
101+
declare = (handle, remote, forwarded) =>
102+
new Declaration(
103+
builtHere,
104+
handle,
105+
remote,
106+
forwarded as Forwarded<never, unknown, unknown, unknown> | undefined,
107+
);
88108
checkedHandler = Struct.lambda<CheckedHandler>((declaration) => declaration.#handle);
89109
remoteCheckOf = (declaration) => declaration.#remote;
110+
forwardedOf = (declaration) => declaration.#forwarded;
90111
}
91112
}
92113

@@ -281,6 +302,20 @@ export const either = <P, A, E, R, A2, E2, R2>(
281302
);
282303
};
283304

305+
/**
306+
* `declaration`, whose result from a linked environment then goes through
307+
* `forwarded` here, for what this environment records about the call.
308+
*/
309+
export const afterForwarding = <P, A, E, R, E2, R2>(
310+
declaration: Declaration<(params: P) => Effect.Effect<A, E, R>>,
311+
forwarded: Forwarded<P, A, E2, R2>,
312+
) =>
313+
declare(
314+
checkedHandler(declaration) as (params: P) => Effect.Effect<A, E | E2, R | R2>,
315+
remoteCheckOf(declaration) as RemoteCheck<P> | undefined,
316+
forwarded,
317+
);
318+
284319
const fullAccessRequired =
285320
"Changing projects or environment settings needs a live full-access/default calling thread or a full-access client.";
286321

@@ -387,6 +422,9 @@ const routed = Effect.fn("McpToolAccess.routed")(function* <Tools extends Record
387422
const tool = toolkit.tools[name];
388423
if (tool === undefined || !takesLinkedEnvironment(tool)) continue;
389424
const remote = remoteCheckOf(declaration);
425+
const forwarded = forwardedOf(declaration) as
426+
| Forwarded<object, unknown, Tool.Failure<Tools[keyof Tools]>, never>
427+
| undefined;
390428
if (remote === undefined)
391429
return yield* Effect.die(
392430
`${name} takes a linked environment, but it acts as its calling thread, which is here.`,
@@ -402,7 +440,11 @@ const routed = Effect.fn("McpToolAccess.routed")(function* <Tools extends Record
402440
if (scope.linkedEnvironments === false) return yield* PeerForwarding.linkedEnvironmentsOff;
403441
yield* (remote as RemoteCheck<typeof params>)(params);
404442
if (Option.isNone(forwarding)) return yield* linksUnavailable;
405-
return yield* forwarding.value.call(scope, tool, target, { ...params, environmentId });
443+
const result = yield* forwarding.value.call(scope, tool, target, {
444+
...params,
445+
environmentId,
446+
});
447+
return forwarded === undefined ? result : yield* forwarded(params, target, result);
406448
});
407449
}
408450
return handlers as Toolkit.HandlersFrom<Tools>;

‎apps/server/src/mcp/toolkits/orchestrator/handlers.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
55
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
66
import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts";
77
import * as PeerLinks from "../../../peer/PeerLinks.ts";
8+
import * as RemoteDelegation from "../../../peer/RemoteDelegation.ts";
89
import { readCaller } from "../../threadAccess.ts";
910
import * as McpInvocationContext from "../../McpInvocationContext.ts";
1011
import * as McpToolAccess from "../../McpToolAccess.ts";
@@ -168,13 +169,22 @@ const handlers = {
168169
return yield* service.update(scope, input);
169170
}),
170171
),
171-
t3_thread_send: McpToolAccess.writesThreads(
172-
(input) => [input.threadId],
173-
(input) =>
172+
t3_thread_send: McpToolAccess.afterForwarding(
173+
McpToolAccess.writesThreads(
174+
(input) => [input.threadId],
175+
(input) =>
176+
Effect.gen(function* () {
177+
const scope = yield* McpInvocationContext.McpInvocationContext;
178+
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
179+
return yield* service.sendToThread(scope, input);
180+
}),
181+
),
182+
// There the thread's parent is here, so only this side can make a follow-up a task.
183+
(input, environmentId, sent) =>
174184
Effect.gen(function* () {
175185
const scope = yield* McpInvocationContext.McpInvocationContext;
176-
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
177-
return yield* service.sendToThread(scope, input);
186+
const remote = yield* RemoteDelegation.RemoteDelegation;
187+
return yield* remote.followUp(scope, environmentId, input, sent);
178188
}),
179189
),
180190
t3_thread_wait: McpToolAccess.reads((input) =>

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import * as ThreadManagementService from "../../../orchestration-v2/ThreadManage
4646
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
4747
import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts";
4848
import * as PeerLinks from "../../../peer/PeerLinks.ts";
49+
import * as RemoteDelegation from "../../../peer/RemoteDelegation.ts";
4950
import * as McpInvocationContext from "../../McpInvocationContext.ts";
5051
import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts";
5152
import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts";
@@ -63,6 +64,8 @@ const linkingDependencies = [
6364
PeerLinkRequests.PeerLinkRequests,
6465
PeerLinks.PeerLinks,
6566
];
67+
/** A send there may record a follow-up to a remote task. */
68+
const sendDependencies = [...dependencies, RemoteDelegation.RemoteDelegation];
6669
const threadMetadataDependencies = [
6770
McpInvocationContext.McpInvocationContext,
6871
ThreadManagementService.ThreadManagementService,
@@ -279,7 +282,7 @@ const ThreadSendTool = Tool.make("t3_thread_send", {
279282
success: OrchestratorMcpThreadSendResult,
280283
failure: OrchestratorMcpFailure,
281284
failureMode: "return",
282-
dependencies,
285+
dependencies: sendDependencies,
283286
})
284287
.annotate(Tool.Title, "Send to a T3 thread")
285288
.annotate(Tool.Destructive, true)

‎apps/server/src/orchestration-v2/CommandPolicy.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
ProviderInstanceId,
1111
ThreadId,
1212
} from "@t3tools/contracts";
13+
import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError";
1314
import * as Context from "effect/Context";
1415
import * as Effect from "effect/Effect";
1516
import * as Layer from "effect/Layer";
@@ -125,6 +126,15 @@ export function isActiveRun(run: OrchestrationV2Run): boolean {
125126
);
126127
}
127128

129+
/** The run a follow-up to a finished child binds to: the latest active one, else the last that ran. */
130+
export function followUpOwnerRun(
131+
runs: ReadonlyArray<OrchestrationV2Run>,
132+
): OrchestrationV2Run | null {
133+
return (
134+
runs.filter(isActiveRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ?? latestExecutedRun(runs)
135+
);
136+
}
137+
128138
function providerTurnCapabilities(
129139
projection: OrchestrationV2ThreadProjection,
130140
run: OrchestrationV2Run,

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ import {
107107
import { CheckpointServiceV2 } from "./CheckpointService.ts";
108108
import {
109109
CommandPolicyV2,
110+
followUpOwnerRun,
110111
goalCommandStopsActiveRun,
111112
isActiveRun,
112113
isNativeMaintenanceCommand,
@@ -8952,9 +8953,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
89528953
task.id === (child.forkedFrom?.type === "node" ? child.forkedFrom.nodeId : undefined),
89538954
);
89548955
if (original === undefined || original.result === null) return;
8955-
const owner =
8956-
parent.runs.filter(isActiveRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ??
8957-
latestExecutedRun(parent.runs);
8956+
const owner = followUpOwnerRun(parent.runs);
89588957
if (owner === null || owner.rootNodeId === null) return;
89598958
const now = message.createdAt;
89608959
const adapter = yield* providerAdapters.get(run.providerInstanceId);
@@ -9072,7 +9071,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
90729071
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
90739072
) {
90749073
const parentProjection = yield* projectionStore
9075-
.getThreadRecords(command.parentThreadId, ["runs", "providerTurns", "attempts"])
9074+
.getThreadRecords(command.parentThreadId, ["runs", "providerTurns", "attempts", "subagents"])
90769075
.pipe(
90779076
Effect.mapError(
90789077
(cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }),
@@ -9081,7 +9080,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
90819080
const parentRun = parentProjection.runs.find(
90829081
(candidate) => candidate.id === command.parentRunId,
90839082
);
9084-
if (parentRun === undefined || !isActiveRun(parentRun) || parentRun.rootNodeId === null) {
9083+
// A follow-up to a finished task there binds as one to a child here does.
9084+
const followsUp = parentProjection.subagents.some(
9085+
(task) =>
9086+
task.result !== null &&
9087+
task.remoteChild?.environmentId === command.remoteChild.environmentId &&
9088+
task.remoteChild.threadId === command.remoteChild.threadId,
9089+
);
9090+
if (
9091+
parentRun === undefined ||
9092+
(followsUp
9093+
? parentRun.id !== followUpOwnerRun(parentProjection.runs)?.id
9094+
: !isActiveRun(parentRun)) ||
9095+
parentRun.rootNodeId === null
9096+
) {
90859097
return yield* new OrchestratorDispatchError({
90869098
commandId: command.commandId,
90879099
commandType: command.type,

‎apps/server/src/peer/PeerForwarding.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,10 @@ const makeLaptop = Effect.gen(function* () {
314314
Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({}),
315315
Layer.mock(SecretRequests.SecretRequests)({}),
316316
ServerSettings.layerTest(),
317-
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
317+
// No thread here delegated to the box, so a send there is no follow-up.
318+
Layer.mock(RemoteDelegation.RemoteDelegation)({
319+
followUp: (_scope, _environmentId, _request, sent) => Effect.succeed(sent),
320+
}),
318321
Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
319322
),
320323
),

0 commit comments

Comments
 (0)