Skip to content
Merged
40 changes: 40 additions & 0 deletions apps/server/src/mcp/toolkits/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1262,6 +1262,46 @@ it.effect.each(["t3_thread_interrupt", "t3_workflow_stop"])(
),
);

it.effect(
"t3_background_wait marks work from a turn Claude started before T3 started its run",
() =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const result = yield* server
.callTool({ name: "t3_background_wait", arguments: { taskIds: ["checks"] } })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(result.structuredContent).toEqual({ matched: ["checks"], unmatched: [] });
}).pipe(
Effect.provide(
layerOrchestratorToolkit.pipe(
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provide(NodeCrypto.layer),
Layer.provide(
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: (id) =>
Effect.succeed(McpToolAccessTestkit.liveThreadShell(id, { activeRunId: null })),
awaitBackgroundTasks: ({ taskIds }) =>
Effect.succeed({ matched: taskIds, unmatched: [] }),
}),
),
Layer.provide(ServerSettings.layerTest()),
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(RemoteDelegation.RemoteDelegation)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
),
),
),
);

it.effect("discovers workflow stop targets and requires orchestration capability", () => {
const threadId = ThreadId.make("workflow-parent");
const shell = McpToolAccessTestkit.liveThreadShell(threadId);
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/mcp/toolkits/orchestrator/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ const handlers = {
);
}),
),
t3_background_wait: McpToolAccess.actsAsCaller((input) =>
// Claude can start a turn by itself before T3 starts its run, so a live-run check would refuse the mark.
t3_background_wait: McpToolAccess.readsAsCaller((input) =>
Comment thread
Bil0000 marked this conversation as resolved.
Resolved
Effect.gen(function* () {
const { scope, threads } = yield* readCaller();
const caller = yield* McpInvocationContext.requireThreadScope(scope, "t3_background_wait");
Expand Down
145 changes: 145 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2294,6 +2294,151 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}),
);

it.effect.each(["running", "exited", "timeout", "held", "sync"] as const)(
"marks a shell OpenCode started on its own before T3 runs the wake, shell %s",
(shell) =>
Effect.gen(function* () {
const shellID = "sh_wake";
const tool = { sessionID: SESSION, assistantMessageID: "msg_wake", id: "call-wake-shell" };
const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
const shellReport = (state: string, extra: Record<string, unknown> = {}) =>
event("session.inbox.enqueued", {
inboxID: "msg_shell_report",
sessionID: SESSION,
item: {
type: "synthetic",
payload: {
text: `<shell id="${shellID}" state="${state}">done</shell>`,
description: "vp test",
metadata: { source: "shell", shellID, state, ...extra },
},
delivery: "steer",
},
});
const { runtime, thread } = yield* resumed([
...backgroundLaunch(CHILD),
event("session.execution.succeeded", { sessionID: SESSION }),
event("session.execution.succeeded", { sessionID: CHILD }),
childReport("msg_report", "CHILD_OK"),
event("session.execution.started", { sessionID: SESSION }),
event("session.tool.input.started", { ...tool, name: "shell" }),
event("session.tool.called", {
...tool,
name: "shell",
input: { command: "vp test", background: true },
executed: false,
}),
event(
"session.tool.success",
{
...tool,
content: [{ type: "text", text: "Launched" }],
// A foreground shell's result already carries its exit.
metadata: shell === "sync" ? { shellID, exit: 0 } : { shellID },
executed: false,
},
undefined,
2,
),
event("shell.created", {
info: {
id: shellID,
status: "running",
command: "vp test",
cwd: WORK,
shell: "bash",
file: "/tmp/sh_wake.log",
metadata: { sessionID: SESSION },
time: { started: 1 },
},
}),
...(shell === "held" ? [shellReport("completed")] : []),
event("session.execution.succeeded", { sessionID: SESSION }),
...(shell === "exited"
? [
event("shell.exited", { id: shellID, exit: 7, status: "exited" }),
shellReport("error"),
]
: []),
...(shell === "timeout"
? [
event("shell.exited", { id: shellID, status: "timeout" }),
shellReport("completed", { timeout: true }),
]
: []),
// Routed once the held execution ended, so its update proves the launch reached the adapter.
event("session.model.selected", {
sessionID: SESSION,
model: { providerID: "opencode", id: "big-pickle", variant: "thinking" },
}),
...Array.from({ length: shell === "held" ? 2 : shell === "sync" ? 0 : 1 }, () => [
out("shell.output", "<any>"),
reply("shell.output", {
location: { directory: WORK },
data: { output: "", cursor: 0, size: 0, truncated: false },
}),
]).flat(),
]).pipe(
Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
offer: (request) =>
Effect.sync(() => {
offers.push(request);
}),
take: Effect.never,
}),
);
// One reader: the runtime's event queue hands each event to only one taker.
const launchSeen = yield* Deferred.make<void>();
const marked = yield* Deferred.make<boolean | undefined>();
const settled =
yield* Deferred.make<import("@t3tools/contracts").OrchestrationV2TurnItem>();
yield* runtime.events.pipe(
Stream.tap((e) =>
e.type === "turn_item.updated" &&
e.turnItem.type === "command_execution" &&
e.turnItem.status !== "running"
? Deferred.succeed(settled, e.turnItem)
: e.type !== "provider_thread.updated"
? Effect.void
: Effect.gen(function* () {
const variant =
e.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value;
if (variant === "thinking") yield* Deferred.succeed(launchSeen, undefined);
const listed = e.providerThread.pendingBackgroundTasks?.find(
(task) => task.taskId === shellID,
);
// The first roster that lists the shell must hold the thread already.
if (listed !== undefined) yield* Deferred.succeed(marked, listed.awaited);
}),
),
Stream.runDrain,
Effect.forkScoped,
);
yield* runtime.startTurn(withLineage(thread));
yield* Deferred.await(launchSeen);
assert.deepEqual(
yield* runtime.awaitBackgroundTasks!({
providerThread: thread,
taskIds: [shellID],
awaited: true,
}),
{ matched: shell === "running" ? [shellID] : [] },
);
if (shell === "sync") return;
yield* runtime.startTurn(continuationTurn(thread, offers[0]!));
if (shell === "running") return assert.isTrue(yield* Deferred.await(marked));
// A shell that ended before the wake ran never holds the thread.
assert.deepInclude(
yield* Deferred.await(settled),
shell === "exited"
? { status: "failed", exitCode: 7 }
: { status: shell === "timeout" ? "failed" : "completed" },
);
const listed = yield* Deferred.poll(marked);
if (Option.isSome(listed)) assert.notStrictEqual(yield* listed.value, true);
}),
);

it.effect("clears the caller's pending work when a called session's held wake runs", () =>
Effect.gen(function* () {
const OTHER = "ses_other00000000000000000000";
Expand Down
101 changes: 89 additions & 12 deletions packages/provider-opencode/src/server/v2/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,12 @@ interface Wake {
readonly after: string | undefined;
readonly first: string | undefined;
readonly children: Set<string>;
readonly awaited: Set<string>;
/** Held shell launches whose end report arrived first; the report already cleared their status. */
readonly ended: Map<
string,
{ readonly status: "completed" | "failed" | "interrupted"; readonly exit?: number }
>;
}

interface OpenBlock {
Expand Down Expand Up @@ -997,6 +1003,38 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
}
>();

// A held wake routes its shell launches only when T3 starts its run, so marks wait on the wake.
const heldLaunch = (state: ThreadState, taskId: string) =>
sessionsOf(state)
.flatMap((session) => session.wakes)
.find((wake) =>
wake.events.some(
(event) =>
event.type === "session.tool.success" &&
stringField(event.data.metadata, "shellID") === taskId &&
event.data.metadata?.["exit"] === undefined &&
event.data.metadata?.["signal"] === undefined &&
event.data.metadata?.["timeout"] !== true,
),
);
const wakeLaunchingShell = (state: ThreadState, taskId: string) => {
const wake = heldLaunch(state, taskId);
return wake === undefined ||
wake.ended.has(taskId) ||
(shellInfo.get(taskId)?.status ?? "running") !== "running" ||
// An end report held with the launch replays after it.
wake.events.some(
(event) =>
event.type === "session.inbox.enqueued" &&
event.data.item.type === "synthetic" &&
stringField(event.data.item.payload.metadata, "source") === "shell" &&
stringField(event.data.item.payload.metadata, "shellID") === taskId,
)
? undefined
: wake;
};
let replaying: Wake | undefined;

const owesWork = (state: ThreadState) =>
[...shells.values()].some((shell) => shell.state === state && shell.running) ||
[...state.imageJobs.values()].some((job) => job.status === "running") ||
Expand Down Expand Up @@ -1942,7 +1980,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
awaited:
state.providerThread.pendingBackgroundTasks?.some(
(task) => task.taskId === info.id && task.awaited === true,
) === true,
) === true || wakeLaunchingShell(state, info.id)?.awaited.has(info.id) === true,
running: true,
output: "",
cursor: 0,
Expand Down Expand Up @@ -2839,25 +2877,30 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
toolId: event.data.id,
tool,
command: stringField(tool.input, "command") ?? "Shell command",
...(replaying?.awaited.has(shellId) === true ? { awaited: true } : {}),
running: true,
output: "",
cursor: 0,
});
yield* readShellOutput(shellId).pipe(Effect.ignore({ log: true }));
const known = shellInfo.get(shellId);
const ended = replaying?.ended.get(shellId);
const tracked = shells.get(shellId)!;
tracked.running = known === undefined || known.status === "running";
tracked.running =
ended === undefined && (known === undefined || known.status === "running");
yield* readShellOutput(shellId, !tracked.running).pipe(Effect.ignore({ log: true }));
yield* emitShell(
shellId,
tracked.running
? "running"
: known?.status === "killed"
? "interrupted"
: known?.exit === 0
? "completed"
: "failed",
known?.exit,
: (ended?.status ??
(known?.status === "killed"
? "interrupted"
: known?.exit === 0
? "completed"
: "failed")),
ended?.exit ?? known?.exit,
);
if (ended !== undefined) shells.delete(shellId);
yield* syncRosterAncestors(state);
return;
}
Expand Down Expand Up @@ -2985,6 +3028,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
after: delivered.at(-1)?.inboxId,
first: leading ?? delivered[0]?.inboxId,
children: new Set(),
awaited: new Set(),
ended: new Map(),
};
state.wakes.push(wake);
yield* Effect.logInfo("OpenCode started a turn on its own; asking for a continuation.", {
Expand Down Expand Up @@ -3095,6 +3140,27 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
outcome: reportOutcome(stringField(payload.metadata, "state")),
},
});
if (id !== undefined && shell === undefined) {
const outcome = reportOutcome(stringField(payload.metadata, "state"));
const known = shellInfo.get(id);
const exit = known?.exit;
// A known exit outranks the report, which says "completed" for a timeout.
heldLaunch(state, id)?.ended.set(id, {
status:
known !== undefined && known.status !== "running"
? known.status === "killed"
? "interrupted"
: exit === 0
? "completed"
: "failed"
: outcome === "failed"
? "failed"
: outcome === "cancelled"
? "interrupted"
: "completed",
...(exit === undefined ? {} : { exit }),
});
}
Comment thread
Bil0000 marked this conversation as resolved.
Resolved
if (id !== undefined && shell?.stopping !== true) {
if (shell?.running === true && shell.state === state) {
yield* readShellOutput(id, true).pipe(Effect.ignore({ log: true }));
Expand Down Expand Up @@ -4405,7 +4471,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr

const replay = Effect.fnUntraced(function* (wake: Wake) {
wake.dropped = true;
for (const event of wake.events) yield* route(event, sessionOfEvent(event), true);
replaying = wake;
yield* Effect.forEach(wake.events, (event) => route(event, sessionOfEvent(event), true), {
discard: true,
}).pipe(Effect.ensuring(Effect.sync(() => (replaying = undefined))));
});

const discardWakes = (caller: ThreadState, wakes: ReadonlyArray<Wake>) => {
Expand Down Expand Up @@ -5134,11 +5203,19 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
const sessions = sessionsOf(state);
const matched = [...new Set(taskIds)].filter((taskId) => {
const shell = shells.get(taskId);
return shell !== undefined && shell.running && sessions.includes(shell.state);
return shell === undefined
? wakeLaunchingShell(state, taskId) !== undefined
: shell.running && sessions.includes(shell.state);
});
if (matched.length === 0) return { matched };
for (const taskId of matched) {
const shell = shells.get(taskId)!;
const shell = shells.get(taskId);
if (shell === undefined) {
const held = wakeLaunchingShell(state, taskId)!.awaited;
if (awaited) held.add(taskId);
else held.delete(taskId);
Comment thread
Bil0000 marked this conversation as resolved.
Resolved
continue;
}
shell.awaited = awaited;
yield* syncRosterAncestors(shell.state);
}
Expand Down
Loading