Skip to content

Commit 5b100b4

Browse files
committed
fix(server): settle every OpenCode subagent call one report answers
Calling a running OpenCode subagent again joins its run, which OpenCode reports once. Settle the calls that joined it with that report, and treat a call that returned while the subagent runs on as background.
1 parent 0647c48 commit 5b100b4

2 files changed

Lines changed: 215 additions & 14 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts‎

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -878,6 +878,192 @@ describe("OpenCode2 adapter", () => {
878878
}).pipe(Effect.scoped),
879879
);
880880

881+
/** A `subagent` call's result while its subagent runs on (`session.tool.success` is at version 2). */
882+
const returnedRunning = (id: string): ProviderReplayEntry => ({
883+
type: "emit_inbound",
884+
frame: {
885+
type: "sdk.event",
886+
event: {
887+
id: `evt_toolsuccess_${id}`,
888+
created: 1,
889+
type: "session.tool.success",
890+
data: {
891+
sessionID: SESSION,
892+
assistantMessageID: "msg_assistant",
893+
id,
894+
content: [{ type: "text", text: "The subagent is working in the background." }],
895+
metadata: { sessionID: CHILD, status: "running" },
896+
executed: true,
897+
},
898+
durable: { aggregateID: SESSION, seq: 1, version: 2 },
899+
},
900+
},
901+
});
902+
/** The model calls the subagent again by its session; the tool returns while it runs on. */
903+
const callAgain = (input: Record<string, unknown>): ReadonlyArray<ProviderReplayEntry> => {
904+
const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-again" };
905+
return [
906+
event("session.tool.input.started", { ...tool, name: "subagent" }),
907+
event("session.tool.called", {
908+
...tool,
909+
name: "subagent",
910+
input: { description: "Again", prompt: "also this", sessionID: CHILD, ...input },
911+
executed: false,
912+
}),
913+
event("session.tool.progress", {
914+
...tool,
915+
metadata: { sessionID: CHILD, status: "running" },
916+
}),
917+
// A session called again gets the thread's rules.
918+
out("session.update", { sessionID: CHILD, permissions: "<any>" }),
919+
reply("session.update", null),
920+
returnedRunning(tool.id),
921+
];
922+
};
923+
const childReport = (inboxID: string, text: string) =>
924+
event("session.inbox.enqueued", {
925+
inboxID,
926+
sessionID: SESSION,
927+
item: {
928+
type: "synthetic",
929+
payload: {
930+
text: `<subagent sessionID="${CHILD}" state="completed" description="Sleep">\n${text}\n</subagent>`,
931+
description: "Sleep",
932+
metadata: { source: "subagent", childID: CHILD, agent: "General", state: "completed" },
933+
},
934+
delivery: "steer",
935+
},
936+
});
937+
/** The subagent rows by title, the thread's background roster and the child's turns, as emitted. */
938+
const watchCalls = (
939+
runtime: ProviderAdapterV2SessionRuntime,
940+
thread: OrchestrationV2ProviderThread,
941+
) =>
942+
Effect.gen(function* () {
943+
const calls = new Map<string, { status: string; result: string | null }>();
944+
const childTurns = new Map<string, string>();
945+
const state: { roster: ReadonlyArray<unknown> | undefined } = { roster: undefined };
946+
let wake = yield* Deferred.make<void>();
947+
yield* runtime.events.pipe(
948+
Stream.tap((event) =>
949+
Effect.gen(function* () {
950+
if (event.type === "subagent.updated" && event.subagent.title !== null) {
951+
calls.set(event.subagent.title, {
952+
status: event.subagent.status,
953+
result: event.subagent.result,
954+
});
955+
}
956+
if (event.type === "provider_thread.updated" && event.providerThread.id === thread.id) {
957+
state.roster = event.providerThread.pendingBackgroundTasks;
958+
}
959+
const id =
960+
event.type === "provider_turn.updated"
961+
? event.providerTurn.nativeTurnRef?.nativeId
962+
: undefined;
963+
if (
964+
event.type === "provider_turn.updated" &&
965+
id?.startsWith(`${CHILD}:turn:`) === true
966+
) {
967+
childTurns.set(id, event.providerTurn.status);
968+
}
969+
yield* Deferred.succeed(wake, undefined);
970+
}),
971+
),
972+
Stream.runDrain,
973+
Effect.forkScoped,
974+
);
975+
const until = (check: () => boolean): Effect.Effect<void> =>
976+
Effect.suspend(() => {
977+
if (check()) return Effect.void;
978+
return Effect.gen(function* () {
979+
wake = yield* Deferred.make<void>();
980+
if (check()) return;
981+
yield* Deferred.await(wake);
982+
yield* until(check);
983+
});
984+
});
985+
return { calls, childTurns, state, until };
986+
});
987+
const launchedAndRunning = [
988+
...backgroundLaunch(CHILD),
989+
returnedRunning("call-background"),
990+
event("session.execution.started", { sessionID: CHILD }),
991+
];
992+
993+
it.effect("settles every call that joined a running subagent with its one report", () =>
994+
Effect.gen(function* () {
995+
const { runtime, thread } = yield* resumed([
996+
...launchedAndRunning,
997+
// OpenCode steers the running subagent and joins its run: one report answers both calls.
998+
...callAgain({ background: true }),
999+
event("session.execution.succeeded", { sessionID: SESSION }),
1000+
event("session.execution.succeeded", { sessionID: CHILD }),
1001+
childReport("msg_report", "CHILD_OK"),
1002+
]);
1003+
const watch = yield* watchCalls(runtime, thread);
1004+
yield* runtime.startTurn(withLineage(thread));
1005+
yield* watch.until(
1006+
() =>
1007+
watch.calls.get("Again")?.status === "completed" &&
1008+
watch.calls.get("Sleep")?.status === "completed" &&
1009+
watch.state.roster?.length === 0,
1010+
);
1011+
assert.deepEqual(Object.fromEntries(watch.calls), {
1012+
Sleep: { status: "completed", result: "CHILD_OK" },
1013+
Again: { status: "completed", result: "CHILD_OK" },
1014+
});
1015+
}).pipe(Effect.scoped),
1016+
);
1017+
1018+
it.effect("keeps a foreground call that joined a background run for that run's report", () =>
1019+
Effect.gen(function* () {
1020+
const { runtime, thread } = yield* resumed([
1021+
...launchedAndRunning,
1022+
// Without `background`, the call joins the run in the background all the same.
1023+
...callAgain({}),
1024+
event("session.execution.succeeded", { sessionID: SESSION }),
1025+
event("session.execution.succeeded", { sessionID: CHILD }),
1026+
childReport("msg_report", "CHILD_OK"),
1027+
]);
1028+
const watch = yield* watchCalls(runtime, thread);
1029+
yield* runtime.startTurn(withLineage(thread));
1030+
yield* watch.until(
1031+
() =>
1032+
watch.calls.get("Again")?.status === "completed" &&
1033+
watch.calls.get("Sleep")?.status === "completed" &&
1034+
watch.state.roster?.length === 0,
1035+
);
1036+
// Not settled empty when the turn that made it ended.
1037+
assert.deepEqual(watch.calls.get("Again"), { status: "completed", result: "CHILD_OK" });
1038+
}).pipe(Effect.scoped),
1039+
);
1040+
1041+
it.effect("keeps a call to a finished subagent for its own run's report", () =>
1042+
Effect.gen(function* () {
1043+
const { runtime, thread } = yield* resumed([
1044+
...launchedAndRunning,
1045+
event("session.execution.succeeded", { sessionID: CHILD }),
1046+
// Called again after it ended but before its report: the call starts a new run.
1047+
...callAgain({ background: true }),
1048+
childReport("msg_report_1", "FIRST_OK"),
1049+
event("session.execution.started", { sessionID: CHILD }),
1050+
event("session.execution.succeeded", { sessionID: CHILD }),
1051+
event("session.execution.succeeded", { sessionID: SESSION }),
1052+
childReport("msg_report_2", "SECOND_OK"),
1053+
]);
1054+
const watch = yield* watchCalls(runtime, thread);
1055+
yield* runtime.startTurn(withLineage(thread));
1056+
// The new run's turn starts after the first report was handled.
1057+
yield* watch.until(() => watch.childTurns.has(`${CHILD}:turn:2`));
1058+
assert.deepEqual(Object.fromEntries(watch.calls), {
1059+
Sleep: { status: "completed", result: "FIRST_OK" },
1060+
Again: { status: "running", result: null },
1061+
});
1062+
yield* watch.until(() => watch.calls.get("Again")?.status === "completed");
1063+
assert.deepEqual(watch.calls.get("Again"), { status: "completed", result: "SECOND_OK" });
1064+
}).pipe(Effect.scoped),
1065+
);
1066+
8811067
it.effect("leaves no background work pending once a reconnect finds its subagent gone", () =>
8821068
Effect.gen(function* () {
8831069
// The subagent ends while the stream is down: its end, its report and

‎apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts‎

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,8 @@ interface SubagentCall {
291291
model: string | null;
292292
/** The tool returned while the subagent runs on; the report OpenCode gives its parent settles it. */
293293
background: boolean;
294+
/** The running call whose subagent run this call joined, so that run's one report settles both. */
295+
joined: SubagentCall | undefined;
294296
child: ThreadState | undefined;
295297
status: OrchestrationV2Subagent["status"];
296298
result: string | null;
@@ -1486,6 +1488,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
14861488
// ran (each one's native id is its own), its grants and rules, and the
14871489
// background work an earlier call left running, which Stop must reach.
14881490
const previous = threads.get(childId);
1491+
// Called again while it runs, the subagent takes the prompt as a steer
1492+
// and OpenCode reports that run once, for every call that joined it.
1493+
if (previous?.active !== undefined) {
1494+
call.joined = [...call.state.calls.values()].findLast(
1495+
(candidate) =>
1496+
candidate !== call && candidate.child === previous && candidate.joined === undefined,
1497+
);
1498+
}
14891499
const subagent = {
14901500
call,
14911501
appThread,
@@ -2172,6 +2182,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
21722182
agent: undefined,
21732183
model: null,
21742184
background: false,
2185+
joined: undefined,
21752186
child: undefined,
21762187
status: "running",
21772188
result: null,
@@ -2237,8 +2248,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
22372248
if (call !== undefined) {
22382249
const childId = stringField(event.data.metadata, "sessionID");
22392250
if (childId !== undefined) yield* attachChild(call, childId);
2240-
// A background call returns at launch; its report settles it.
2241-
if (event.data.metadata?.["status"] === "running") return;
2251+
// A background call returns at launch, and so does one that joined a
2252+
// background run; the report settles it.
2253+
if (event.data.metadata?.["status"] === "running") {
2254+
if (call.background) return;
2255+
call.background = true;
2256+
return yield* emitSubagent(call);
2257+
}
22422258
return yield* settleCall(call, "completed", subagentOutput(textOf(event.data.content)));
22432259
}
22442260
const output = textOf(event.data.content);
@@ -2376,6 +2392,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
23762392
const call = [...state.calls.values()].find(
23772393
(candidate) => candidate.child?.sessionId === childId,
23782394
);
2395+
const calls = [...state.calls.values()].filter(
2396+
(candidate) => candidate === call || (call !== undefined && candidate.joined === call),
2397+
);
23792398
const outcome = reportOutcome(stringField(payload.metadata, "state"));
23802399
state.reports.set(inboxId, {
23812400
inboxId,
@@ -2388,18 +2407,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
23882407
outcome,
23892408
},
23902409
});
2391-
if (call === undefined) return;
2392-
yield* settleCall(
2393-
call,
2394-
state.stoppedChildren.has(childId)
2395-
? "interrupted"
2396-
: outcome === "failed"
2397-
? "failed"
2398-
: outcome === "cancelled"
2399-
? "cancelled"
2400-
: "completed",
2401-
subagentOutput(payload.text),
2402-
);
2410+
const status = state.stoppedChildren.has(childId)
2411+
? "interrupted"
2412+
: outcome === "failed"
2413+
? "failed"
2414+
: outcome === "cancelled"
2415+
? "cancelled"
2416+
: "completed";
2417+
for (const each of calls) yield* settleCall(each, status, subagentOutput(payload.text));
24032418
});
24042419

24052420
/**

0 commit comments

Comments
 (0)