Skip to content

Commit 9dce111

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 b707eeb commit 9dce111

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
@@ -881,6 +881,192 @@ describe("OpenCode2 adapter", () => {
881881
}).pipe(Effect.scoped),
882882
);
883883

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

‎packages/provider-opencode/src/server/v2/adapter.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;
@@ -1489,6 +1491,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
14891491
// ran (each one's native id is its own), its grants and rules, and the
14901492
// background work an earlier call left running, which Stop must reach.
14911493
const previous = threads.get(childId);
1494+
// Called again while it runs, the subagent takes the prompt as a steer
1495+
// and OpenCode reports that run once, for every call that joined it.
1496+
if (previous?.active !== undefined) {
1497+
call.joined = [...call.state.calls.values()].findLast(
1498+
(candidate) =>
1499+
candidate !== call && candidate.child === previous && candidate.joined === undefined,
1500+
);
1501+
}
14921502
const subagent = {
14931503
call,
14941504
appThread,
@@ -2175,6 +2185,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
21752185
agent: undefined,
21762186
model: null,
21772187
background: false,
2188+
joined: undefined,
21782189
child: undefined,
21792190
status: "running",
21802191
result: null,
@@ -2240,8 +2251,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
22402251
if (call !== undefined) {
22412252
const childId = stringField(event.data.metadata, "sessionID");
22422253
if (childId !== undefined) yield* attachChild(call, childId);
2243-
// A background call returns at launch; its report settles it.
2244-
if (event.data.metadata?.["status"] === "running") return;
2254+
// A background call returns at launch, and so does one that joined a
2255+
// background run; the report settles it.
2256+
if (event.data.metadata?.["status"] === "running") {
2257+
if (call.background) return;
2258+
call.background = true;
2259+
return yield* emitSubagent(call);
2260+
}
22452261
return yield* settleCall(call, "completed", subagentOutput(textOf(event.data.content)));
22462262
}
22472263
const output = textOf(event.data.content);
@@ -2379,6 +2395,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
23792395
const call = [...state.calls.values()].find(
23802396
(candidate) => candidate.child?.sessionId === childId,
23812397
);
2398+
const calls = [...state.calls.values()].filter(
2399+
(candidate) => candidate === call || (call !== undefined && candidate.joined === call),
2400+
);
23822401
const outcome = reportOutcome(stringField(payload.metadata, "state"));
23832402
state.reports.set(inboxId, {
23842403
inboxId,
@@ -2391,18 +2410,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
23912410
outcome,
23922411
},
23932412
});
2394-
if (call === undefined) return;
2395-
yield* settleCall(
2396-
call,
2397-
state.stoppedChildren.has(childId)
2398-
? "interrupted"
2399-
: outcome === "failed"
2400-
? "failed"
2401-
: outcome === "cancelled"
2402-
? "cancelled"
2403-
: "completed",
2404-
subagentOutput(payload.text),
2405-
);
2413+
const status = state.stoppedChildren.has(childId)
2414+
? "interrupted"
2415+
: outcome === "failed"
2416+
? "failed"
2417+
: outcome === "cancelled"
2418+
? "cancelled"
2419+
: "completed";
2420+
for (const each of calls) yield* settleCall(each, status, subagentOutput(payload.text));
24062421
});
24072422

24082423
/**

0 commit comments

Comments
 (0)