fix(server): OpenCode 2 continuations replay only their own background reply (#14752)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
cb7d073938
commit
ae5fd18428
5 files changed
+861
-64
No files matched your search
@@ -715,6 +715,28 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
|
||||
lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
|
||||
} as OrchestrationV2AppThread,
|
||||
});
|
||||
/**
|
||||
* The continuation turn the orchestrator starts for an offered wake: its
|
||||
* message is the one the offer named, as `ProviderContinuationService` dispatches it.
|
||||
*/
|
||||
const continuationTurn = (
|
||||
thread: OrchestrationV2ProviderThread,
|
||||
offer: ProviderContinuationRequests.ProviderContinuationRequest,
|
||||
suffix = "wake",
|
||||
) => ({
|
||||
...withLineage(thread),
|
||||
runId: RunId.make(`run:opencode2-adapter:${suffix}`),
|
||||
runOrdinal: 2,
|
||||
providerTurnOrdinal: 2,
|
||||
attemptId: RunAttemptId.make(`attempt:opencode2-adapter:${suffix}`),
|
||||
message: {
|
||||
...turnInput(thread).message,
|
||||
messageId: offer.messageId!,
|
||||
text: offer.detail ?? "",
|
||||
createdBy: "agent" as const,
|
||||
creationSource: "provider" as const,
|
||||
},
|
||||
});
|
||||
const CHILD = "ses_f1485c529ffea4URrYruwEg0Ja";
|
||||
/**
|
||||
* The single reader of the runtime's events: resolves `attached` once the
|
||||
@@ -1865,7 +1887,8 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
|
||||
|
||||
it.effect("ends a background reply's continuation after a lost stream took a Stop's end", () =>
|
||||
Effect.gen(function* () {
|
||||
const offered = yield* Deferred.make<void>();
|
||||
const offered =
|
||||
yield* Deferred.make<ProviderContinuationRequests.ProviderContinuationRequest>();
|
||||
const gate = makeProviderReplayGate(["drop", "reply"]);
|
||||
const { runtime, thread } = yield* resumed(
|
||||
[
|
||||
@@ -1926,7 +1949,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
|
||||
{ replayGate: gate },
|
||||
).pipe(
|
||||
Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
|
||||
offer: () => Deferred.succeed(offered, undefined).pipe(Effect.asVoid),
|
||||
offer: (request) => Deferred.succeed(offered, request).pipe(Effect.asVoid),
|
||||
take: Effect.never,
|
||||
}),
|
||||
);
|
||||
@@ -1955,26 +1978,133 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
|
||||
yield* Fiber.join(interrupt);
|
||||
yield* runtime.startTurn({ ...secondTurn(thread), appThread: withLineage(thread).appThread });
|
||||
gate.release("drop");
|
||||
yield* Deferred.await(offered);
|
||||
yield* runtime.startTurn({
|
||||
...withLineage(thread),
|
||||
runId: RunId.make("run:opencode2-adapter:wake"),
|
||||
...continuationTurn(thread, yield* Deferred.await(offered)),
|
||||
runOrdinal: 3,
|
||||
providerTurnOrdinal: 3,
|
||||
attemptId: RunAttemptId.make("attempt:opencode2-adapter:wake"),
|
||||
message: {
|
||||
...turnInput(thread).message,
|
||||
messageId: MessageId.make("message:opencode2-adapter:wake"),
|
||||
createdBy: "agent" as const,
|
||||
creationSource: "provider" as const,
|
||||
},
|
||||
});
|
||||
gate.release("reply");
|
||||
// The reply's own end finishes its continuation: the lost Stop's end does not take it.
|
||||
const events = [...(yield* Fiber.join(collected))];
|
||||
assert.deepEqual(
|
||||
[...(yield* Fiber.join(collected))].flatMap((event) =>
|
||||
event.type === "turn.terminal" ? [event.status] : [],
|
||||
events.flatMap((event) => (event.type === "turn.terminal" ? [event.status] : [])),
|
||||
["interrupted", "failed", "completed"],
|
||||
);
|
||||
// The continuation replayed the reply.
|
||||
assert.include(
|
||||
events.flatMap((event) =>
|
||||
event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
|
||||
? [event.turnItem.text]
|
||||
: [],
|
||||
),
|
||||
"CHILD_OK",
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("lets a prompt join a background reply after a lost stream took a Stop's end", () =>
|
||||
Effect.gen(function* () {
|
||||
const offered = yield* Deferred.make<void>();
|
||||
const gate = makeProviderReplayGate(["drop"]);
|
||||
const { runtime, thread } = yield* resumed(
|
||||
[
|
||||
...backgroundLaunch(CHILD),
|
||||
// Restarting the turn stops only the parent, and the server never answers.
|
||||
out("session.interrupt", { sessionID: SESSION }),
|
||||
reply("session.interrupt", "<hang>"),
|
||||
// The restarted turn finds the parent still stopping and fails.
|
||||
out("session.active"),
|
||||
replyData("session.active", { [SESSION]: { type: "running" } }),
|
||||
out("session.interrupt", { sessionID: SESSION }),
|
||||
reply("session.interrupt", { interrupted: true }),
|
||||
// The stream drops before the parent's end; the reconnect finds it idle.
|
||||
event("session.usage.updated", { sessionID: SESSION }, "drop"),
|
||||
{ type: "runtime_exit", status: "success" } as const,
|
||||
out("event.subscribe"),
|
||||
out("session.active"),
|
||||
replyData("session.active", { [CHILD]: { type: "running" } }),
|
||||
out("permission.list", { sessionID: CHILD }),
|
||||
replyData("permission.list", []),
|
||||
out("session.form.list", { sessionID: CHILD }),
|
||||
replyData("session.form.list", []),
|
||||
// The subagent ends and OpenCode answers its report on its own.
|
||||
event("session.execution.succeeded", { sessionID: CHILD }),
|
||||
event("session.inbox.enqueued", {
|
||||
inboxID: "msg_report",
|
||||
sessionID: SESSION,
|
||||
item: {
|
||||
type: "synthetic",
|
||||
payload: {
|
||||
text: `<subagent sessionID="${CHILD}" state="completed" description="Sleep">\nCHILD_OK\n</subagent>`,
|
||||
description: "Sleep",
|
||||
metadata: {
|
||||
source: "subagent",
|
||||
childID: CHILD,
|
||||
agent: "General",
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
delivery: "steer",
|
||||
},
|
||||
}),
|
||||
event("session.execution.started", { sessionID: SESSION }),
|
||||
// A prompt sent while that reply runs joins it, with no check first.
|
||||
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
|
||||
promptAccepted,
|
||||
event("session.text.ended", {
|
||||
sessionID: SESSION,
|
||||
assistantMessageID: "msg_followup",
|
||||
ordinal: 0,
|
||||
text: "CHILD_OK",
|
||||
}),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
],
|
||||
{ replayGate: gate },
|
||||
).pipe(
|
||||
Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
|
||||
offer: () => Deferred.succeed(offered, undefined).pipe(Effect.asVoid),
|
||||
take: Effect.never,
|
||||
}),
|
||||
);
|
||||
// The single reader of the runtime's events.
|
||||
const attached = yield* Deferred.make<void>();
|
||||
const ended = yield* runtime.events.pipe(
|
||||
Stream.tap((event) =>
|
||||
event.type === "subagent.updated" && event.subagent.childThreadId !== null
|
||||
? Deferred.succeed(attached, undefined)
|
||||
: Effect.void,
|
||||
),
|
||||
Stream.filter(
|
||||
(
|
||||
event,
|
||||
): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
|
||||
event.type === "turn.terminal",
|
||||
),
|
||||
Stream.take(3),
|
||||
Stream.runCollect,
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* runtime.startTurn(withLineage(thread));
|
||||
yield* Deferred.await(attached);
|
||||
const interrupt = yield* runtime
|
||||
.interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId })
|
||||
.pipe(Effect.forkScoped);
|
||||
yield* TestClock.adjust("11 seconds");
|
||||
yield* Fiber.join(interrupt);
|
||||
yield* runtime.startTurn({ ...secondTurn(thread), appThread: withLineage(thread).appThread });
|
||||
gate.release("drop");
|
||||
// The reply has started.
|
||||
yield* Deferred.await(offered);
|
||||
yield* runtime.startTurn({
|
||||
...withLineage(thread),
|
||||
runId: RunId.make("run:opencode2-adapter:3"),
|
||||
runOrdinal: 3,
|
||||
providerTurnOrdinal: 3,
|
||||
attemptId: RunAttemptId.make("attempt:opencode2-adapter:3"),
|
||||
});
|
||||
// The reply's start cleared the Stop's mark, so its end finishes the joined turn.
|
||||
assert.deepEqual(
|
||||
[...(yield* Fiber.join(ended))].map((terminal) => terminal.status),
|
||||
["interrupted", "failed", "completed"],
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
|
||||
@@ -1987,7 +2117,8 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
|
||||
*/
|
||||
const replyAfterUnclearFailure = (endedFirst: boolean) =>
|
||||
Effect.gen(function* () {
|
||||
const offered = yield* Deferred.make<void>();
|
||||
const offered =
|
||||
yield* Deferred.make<ProviderContinuationRequests.ProviderContinuationRequest>();
|
||||
const gate = makeProviderReplayGate(endedFirst ? ["wake"] : ["wake", "reply"]);
|
||||
const { runtime, thread } = yield* resumed(
|
||||
[
|
||||
@@ -2038,7 +2169,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
|
||||
{ replayGate: gate },
|
||||
).pipe(
|
||||
Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
|
||||
offer: () => Deferred.succeed(offered, undefined).pipe(Effect.asVoid),
|
||||
offer: (request) => Deferred.succeed(offered, request).pipe(Effect.asVoid),
|
||||
take: Effect.never,
|
||||
}),
|
||||
);
|
||||
@@ -2073,21 +2204,12 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
|
||||
.startTurn({ ...secondTurn(thread), appThread: withLineage(thread).appThread })
|
||||
.pipe(Effect.ignore);
|
||||
gate.release("wake");
|
||||
yield* Deferred.await(offered);
|
||||
// Everything up to the subagent's next run has been read: the reply ended.
|
||||
if (endedFirst) yield* Deferred.await(childRan);
|
||||
yield* runtime.startTurn({
|
||||
...withLineage(thread),
|
||||
runId: RunId.make("run:opencode2-adapter:wake"),
|
||||
...continuationTurn(thread, yield* Deferred.await(offered)),
|
||||
runOrdinal: 3,
|
||||
providerTurnOrdinal: 3,
|
||||
attemptId: RunAttemptId.make("attempt:opencode2-adapter:wake"),
|
||||
message: {
|
||||
...turnInput(thread).message,
|
||||
messageId: MessageId.make("message:opencode2-adapter:wake"),
|
||||
createdBy: "agent" as const,
|
||||
creationSource: "provider" as const,
|
||||
},
|
||||
});
|
||||
if (!endedFirst) gate.release("reply");
|
||||
// The reply's own end finishes its continuation: the failed prompt's mark does not take it.
|
||||
@@ -4378,19 +4500,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
|
||||
yield* Effect.gen(function* () {
|
||||
while (offers.length === 0) yield* Effect.yieldNow;
|
||||
}).pipe(Effect.timeout("2 seconds"), Effect.orDie);
|
||||
yield* runtime.startTurn({
|
||||
...withLineage(thread),
|
||||
runId: RunId.make("run:opencode2-adapter:wake"),
|
||||
runOrdinal: 2,
|
||||
providerTurnOrdinal: 2,
|
||||
attemptId: RunAttemptId.make("attempt:opencode2-adapter:wake"),
|
||||
message: {
|
||||
...turnInput(thread).message,
|
||||
messageId: MessageId.make("message:opencode2-adapter:wake"),
|
||||
createdBy: "agent" as const,
|
||||
creationSource: "provider" as const,
|
||||
},
|
||||
});
|
||||
yield* runtime.startTurn(continuationTurn(thread, offers[0]!));
|
||||
yield* Deferred.await(bothEnded);
|
||||
const [first, second] = turns;
|
||||
return { runtime, thread, first: first!, second: second! };
|
||||
@@ -4457,6 +4567,556 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("keeps a subagent a stopped background reply started off the next turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const CHILD_B = "ses_f1485c529ffeBBBBBBBBBBBBBB";
|
||||
const SPAWNED = "ses_f1485c529ffeDDDDDDDDDDDDDD";
|
||||
const NESTED = "ses_f1485c529ffeNNNNNNNNNNNNNN";
|
||||
const toolB = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-b" };
|
||||
const spawn = { sessionID: SESSION, assistantMessageID: "msg_reply", id: "call-spawn" };
|
||||
const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
|
||||
const gate = makeProviderReplayGate(["settled"]);
|
||||
const { runtime, thread } = yield* resumed(
|
||||
[
|
||||
...backgroundLaunch(CHILD),
|
||||
// The same turn starts a second background subagent, which runs on.
|
||||
event("session.tool.input.started", { ...toolB, name: "subagent" }),
|
||||
event("session.tool.called", {
|
||||
...toolB,
|
||||
name: "subagent",
|
||||
input: { description: "Sleep", prompt: "sleep", background: true },
|
||||
executed: false,
|
||||
}),
|
||||
event("session.created", { ...childCreated(CHILD_B), sessionID: CHILD_B }),
|
||||
event("session.tool.progress", {
|
||||
...toolB,
|
||||
metadata: { sessionID: CHILD_B, status: "running" },
|
||||
}),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
event("session.execution.started", { sessionID: CHILD_B }),
|
||||
// The first subagent's report wakes the parent into a reply T3 holds
|
||||
// for its continuation.
|
||||
event("session.execution.succeeded", { sessionID: CHILD }),
|
||||
event("session.inbox.enqueued", {
|
||||
inboxID: "msg_report",
|
||||
sessionID: SESSION,
|
||||
item: {
|
||||
type: "synthetic",
|
||||
payload: {
|
||||
text: `<subagent sessionID="${CHILD}" state="completed" description="Sleep">\nCHILD_OK\n</subagent>`,
|
||||
description: "Sleep",
|
||||
metadata: {
|
||||
source: "subagent",
|
||||
childID: CHILD,
|
||||
agent: "General",
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
delivery: "steer",
|
||||
},
|
||||
}),
|
||||
event("session.execution.started", { sessionID: SESSION }),
|
||||
// The reply starts a background subagent of its own, named only by
|
||||
// the reply's held events.
|
||||
event("session.tool.input.started", { ...spawn, name: "subagent" }),
|
||||
event("session.tool.called", {
|
||||
...spawn,
|
||||
name: "subagent",
|
||||
input: { description: "Sleep", prompt: "sleep", background: true },
|
||||
executed: false,
|
||||
}),
|
||||
event("session.created", { ...childCreated(SPAWNED), sessionID: SPAWNED }),
|
||||
event("session.tool.progress", {
|
||||
...spawn,
|
||||
metadata: { sessionID: SPAWNED, status: "running" },
|
||||
}),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
// The second subagent's text, shown live, marks that the reply has ended.
|
||||
event("session.text.ended", {
|
||||
sessionID: CHILD_B,
|
||||
assistantMessageID: "msg_child_b",
|
||||
ordinal: 0,
|
||||
text: "B_WORKING",
|
||||
}),
|
||||
// The user's Stop stops the second subagent and drops the held reply.
|
||||
out("session.interrupt", { sessionID: CHILD_B }),
|
||||
reply("session.interrupt", { interrupted: true }),
|
||||
event("session.execution.interrupted", { sessionID: CHILD_B }),
|
||||
// The subagent only the dropped reply named is stopped too; that Stop
|
||||
// fails, so it runs on.
|
||||
out("session.interrupt", { sessionID: SPAWNED }),
|
||||
reply("session.interrupt", {
|
||||
status: 500,
|
||||
body: { _tag: "UnknownError", message: "interrupt failed" },
|
||||
}),
|
||||
// An unrelated prompt runs while that subagent, and a subagent it
|
||||
// starts, ask for permissions, which no turn shows: they are refused.
|
||||
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
|
||||
promptAccepted,
|
||||
event("session.execution.started", { sessionID: SESSION }),
|
||||
event("permission.asked", { ...shellAsk.data, id: "per_spawned", sessionID: SPAWNED }),
|
||||
out("permission.reply", {
|
||||
sessionID: SPAWNED,
|
||||
requestID: "per_spawned",
|
||||
decision: "reject",
|
||||
}),
|
||||
reply("permission.reply", null),
|
||||
event("session.created", {
|
||||
...childCreated(NESTED),
|
||||
sessionID: NESTED,
|
||||
parentID: SPAWNED,
|
||||
}),
|
||||
event("permission.asked", { ...shellAsk.data, id: "per_nested", sessionID: NESTED }),
|
||||
out("permission.reply", {
|
||||
sessionID: NESTED,
|
||||
requestID: "per_nested",
|
||||
decision: "reject",
|
||||
}),
|
||||
reply("permission.reply", null),
|
||||
event("session.text.ended", {
|
||||
sessionID: SESSION,
|
||||
assistantMessageID: "msg_unrelated",
|
||||
ordinal: 0,
|
||||
text: "UNRELATED",
|
||||
}),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
// The next Stop tries the subagent again, and the one it started, and reaches both.
|
||||
out("session.interrupt", { sessionID: SPAWNED }),
|
||||
reply("session.interrupt", { interrupted: true }),
|
||||
out("session.interrupt", { sessionID: NESTED }),
|
||||
reply("session.interrupt", { interrupted: true }),
|
||||
// OpenCode reports the stopped subagent to the thread's session and
|
||||
// wakes it; that execution answers no turn, so it is stopped and no
|
||||
// continuation is offered for it.
|
||||
event("session.execution.interrupted", { sessionID: SPAWNED }),
|
||||
event("session.inbox.enqueued", {
|
||||
inboxID: "msg_report_spawned",
|
||||
sessionID: SESSION,
|
||||
item: {
|
||||
type: "synthetic",
|
||||
payload: {
|
||||
text: `<subagent sessionID="${SPAWNED}" state="cancelled" description="Sleep">\n</subagent>`,
|
||||
description: "Sleep",
|
||||
metadata: {
|
||||
source: "subagent",
|
||||
childID: SPAWNED,
|
||||
agent: "General",
|
||||
state: "cancelled",
|
||||
},
|
||||
},
|
||||
delivery: "steer",
|
||||
},
|
||||
}),
|
||||
event("session.execution.started", { sessionID: SESSION }),
|
||||
out("session.interrupt", { sessionID: SESSION }),
|
||||
reply("session.interrupt", { interrupted: true }),
|
||||
event("session.execution.interrupted", { sessionID: SESSION }, "settled"),
|
||||
],
|
||||
{ replayGate: gate },
|
||||
).pipe(
|
||||
Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
|
||||
offer: (request) => Effect.sync(() => void offers.push(request)),
|
||||
take: Effect.never,
|
||||
}),
|
||||
);
|
||||
const collected: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
|
||||
const replyEnded = yield* Deferred.make<void>();
|
||||
const bothEnded = yield* Deferred.make<void>();
|
||||
yield* runtime.events.pipe(
|
||||
Stream.tap((event) =>
|
||||
Effect.gen(function* () {
|
||||
collected.push(event);
|
||||
if (event.type === "turn_item.updated" && event.turnItem.type === "assistant_message") {
|
||||
if (event.turnItem.text === "B_WORKING")
|
||||
yield* Deferred.succeed(replyEnded, undefined);
|
||||
}
|
||||
if (collected.filter((entry) => entry.type === "turn.terminal").length === 2) {
|
||||
yield* Deferred.succeed(bothEnded, undefined);
|
||||
}
|
||||
}),
|
||||
),
|
||||
Stream.runDrain,
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* runtime.startTurn(withLineage(thread));
|
||||
yield* Deferred.await(replyEnded);
|
||||
assert.lengthOf(offers, 1);
|
||||
// The user stops the thread before the reply's continuation runs.
|
||||
yield* runtime.interruptTurn({
|
||||
providerThread: thread,
|
||||
providerTurnId: yield* providerTurnId,
|
||||
requestRuntimeRestart: true,
|
||||
});
|
||||
yield* runtime.startTurn({ ...secondTurn(thread), appThread: withLineage(thread).appThread });
|
||||
yield* Deferred.await(bothEnded);
|
||||
// A later Stop reaches both subagents; once stopped they are not tried
|
||||
// again (the replay fails on any further request).
|
||||
for (let stops = 0; stops < 2; stops++) {
|
||||
yield* runtime.interruptTurn({
|
||||
providerThread: thread,
|
||||
providerTurnId: yield* providerTurnId,
|
||||
requestRuntimeRestart: true,
|
||||
});
|
||||
}
|
||||
// The stopped subagent's report wakes nothing T3 runs.
|
||||
yield* Effect.promise(() => gate.waitForReached("settled"));
|
||||
gate.release("settled");
|
||||
assert.lengthOf(offers, 1);
|
||||
// The unrelated turn shows no request it never made.
|
||||
assert.deepEqual(
|
||||
collected.flatMap((event) =>
|
||||
event.type === "runtime_request.updated"
|
||||
? [`${event.runtimeRequest.nativeRequestRef?.nativeId}:${event.runtimeRequest.status}`]
|
||||
: [],
|
||||
),
|
||||
[],
|
||||
);
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"keeps every subagent a stopped background reply's subagent started off the next turn",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const CHILD_B = "ses_f1485c529ffeBBBBBBBBBBBBBB";
|
||||
const SPAWNED = "ses_f1485c529ffeDDDDDDDDDDDDDD";
|
||||
const NESTED = "ses_f1485c529ffeNNNNNNNNNNNNNN";
|
||||
const DEEP = "ses_f1485c529ffeEEEEEEEEEEEEEE";
|
||||
const toolB = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-b" };
|
||||
const spawn = { sessionID: SESSION, assistantMessageID: "msg_reply", id: "call-spawn" };
|
||||
const { runtime, thread } = yield* resumed([
|
||||
...backgroundLaunch(CHILD),
|
||||
// The same turn starts a second background subagent, which runs on.
|
||||
event("session.tool.input.started", { ...toolB, name: "subagent" }),
|
||||
event("session.tool.called", {
|
||||
...toolB,
|
||||
name: "subagent",
|
||||
input: { description: "Sleep", prompt: "sleep", background: true },
|
||||
executed: false,
|
||||
}),
|
||||
event("session.created", { ...childCreated(CHILD_B), sessionID: CHILD_B }),
|
||||
event("session.tool.progress", {
|
||||
...toolB,
|
||||
metadata: { sessionID: CHILD_B, status: "running" },
|
||||
}),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
event("session.execution.started", { sessionID: CHILD_B }),
|
||||
// The first subagent's report wakes the parent into a reply T3 holds.
|
||||
event("session.execution.succeeded", { sessionID: CHILD }),
|
||||
event("session.inbox.enqueued", {
|
||||
inboxID: "msg_report",
|
||||
sessionID: SESSION,
|
||||
item: {
|
||||
type: "synthetic",
|
||||
payload: {
|
||||
text: `<subagent sessionID="${CHILD}" state="completed" description="Sleep">\nCHILD_OK\n</subagent>`,
|
||||
description: "Sleep",
|
||||
metadata: {
|
||||
source: "subagent",
|
||||
childID: CHILD,
|
||||
agent: "General",
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
delivery: "steer",
|
||||
},
|
||||
}),
|
||||
event("session.execution.started", { sessionID: SESSION }),
|
||||
// The held reply starts a subagent, which starts one, which starts another.
|
||||
event("session.tool.input.started", { ...spawn, name: "subagent" }),
|
||||
event("session.tool.called", {
|
||||
...spawn,
|
||||
name: "subagent",
|
||||
input: { description: "Sleep", prompt: "sleep", background: true },
|
||||
executed: false,
|
||||
}),
|
||||
event("session.created", { ...childCreated(SPAWNED), sessionID: SPAWNED }),
|
||||
event("session.tool.progress", {
|
||||
...spawn,
|
||||
metadata: { sessionID: SPAWNED, status: "running" },
|
||||
}),
|
||||
event("session.created", {
|
||||
...childCreated(NESTED),
|
||||
sessionID: NESTED,
|
||||
parentID: SPAWNED,
|
||||
}),
|
||||
event("session.created", { ...childCreated(DEEP), sessionID: DEEP, parentID: NESTED }),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
// The second subagent's text, shown live, marks that the reply has ended.
|
||||
event("session.text.ended", {
|
||||
sessionID: CHILD_B,
|
||||
assistantMessageID: "msg_child_b",
|
||||
ordinal: 0,
|
||||
text: "B_WORKING",
|
||||
}),
|
||||
// The user's Stop stops the second subagent and drops the held reply,
|
||||
// then each subagent under the reply, the deepest of which runs on.
|
||||
out("session.interrupt", { sessionID: CHILD_B }),
|
||||
reply("session.interrupt", { interrupted: true }),
|
||||
event("session.execution.interrupted", { sessionID: CHILD_B }),
|
||||
out("session.interrupt", { sessionID: SPAWNED }),
|
||||
reply("session.interrupt", { interrupted: true }),
|
||||
out("session.interrupt", { sessionID: NESTED }),
|
||||
reply("session.interrupt", { interrupted: true }),
|
||||
out("session.interrupt", { sessionID: DEEP }),
|
||||
reply("session.interrupt", {
|
||||
status: 500,
|
||||
body: { _tag: "UnknownError", message: "interrupt failed" },
|
||||
}),
|
||||
// An unrelated prompt runs while the deepest asks for a permission,
|
||||
// which no turn shows: it is refused.
|
||||
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
|
||||
promptAccepted,
|
||||
event("session.execution.started", { sessionID: SESSION }),
|
||||
event("permission.asked", { ...shellAsk.data, id: "per_deep", sessionID: DEEP }),
|
||||
out("permission.reply", { sessionID: DEEP, requestID: "per_deep", decision: "reject" }),
|
||||
reply("permission.reply", null),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
]);
|
||||
const collected: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
|
||||
const replyEnded = yield* Deferred.make<void>();
|
||||
const bothEnded = yield* Deferred.make<void>();
|
||||
yield* runtime.events.pipe(
|
||||
Stream.tap((event) =>
|
||||
Effect.gen(function* () {
|
||||
collected.push(event);
|
||||
if (
|
||||
event.type === "turn_item.updated" &&
|
||||
event.turnItem.type === "assistant_message" &&
|
||||
event.turnItem.text === "B_WORKING"
|
||||
) {
|
||||
yield* Deferred.succeed(replyEnded, undefined);
|
||||
}
|
||||
if (collected.filter((entry) => entry.type === "turn.terminal").length === 2) {
|
||||
yield* Deferred.succeed(bothEnded, undefined);
|
||||
}
|
||||
}),
|
||||
),
|
||||
Stream.runDrain,
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* runtime.startTurn(withLineage(thread));
|
||||
yield* Deferred.await(replyEnded);
|
||||
yield* runtime.interruptTurn({
|
||||
providerThread: thread,
|
||||
providerTurnId: yield* providerTurnId,
|
||||
requestRuntimeRestart: true,
|
||||
});
|
||||
yield* runtime.startTurn({
|
||||
...secondTurn(thread),
|
||||
appThread: withLineage(thread).appThread,
|
||||
});
|
||||
yield* Deferred.await(bothEnded);
|
||||
// The unrelated turn shows no request it never made.
|
||||
assert.deepEqual(
|
||||
collected.flatMap((event) =>
|
||||
event.type === "runtime_request.updated"
|
||||
? [
|
||||
`${event.runtimeRequest.nativeRequestRef?.nativeId}:${event.runtimeRequest.status}`,
|
||||
]
|
||||
: [],
|
||||
),
|
||||
[],
|
||||
);
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("ends a continuation while a skipped reply's subagent does not answer its Stop", () =>
|
||||
Effect.gen(function* () {
|
||||
const CHILD_B = "ses_f1485c529ffeBBBBBBBBBBBBBB";
|
||||
const SPAWNED = "ses_f1485c529ffeDDDDDDDDDDDDDD";
|
||||
const toolB = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-b" };
|
||||
const spawn = { sessionID: SESSION, assistantMessageID: "msg_reply_a", id: "call-spawn" };
|
||||
const report = (inboxID: string, child: string) =>
|
||||
event("session.inbox.enqueued", {
|
||||
inboxID,
|
||||
sessionID: SESSION,
|
||||
item: {
|
||||
type: "synthetic",
|
||||
payload: {
|
||||
text: `<subagent sessionID="${child}" state="completed" description="Sleep">\nOK\n</subagent>`,
|
||||
description: "Sleep",
|
||||
metadata: {
|
||||
source: "subagent",
|
||||
childID: child,
|
||||
agent: "General",
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
delivery: "steer",
|
||||
},
|
||||
});
|
||||
const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
|
||||
const bothOffered = yield* Deferred.make<void>();
|
||||
const { runtime, thread } = yield* resumed([
|
||||
...backgroundLaunch(CHILD),
|
||||
event("session.tool.input.started", { ...toolB, name: "subagent" }),
|
||||
event("session.tool.called", {
|
||||
...toolB,
|
||||
name: "subagent",
|
||||
input: { description: "Sleep", prompt: "sleep", background: true },
|
||||
executed: false,
|
||||
}),
|
||||
event("session.created", { ...childCreated(CHILD_B), sessionID: CHILD_B }),
|
||||
event("session.tool.progress", {
|
||||
...toolB,
|
||||
metadata: { sessionID: CHILD_B, status: "running" },
|
||||
}),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
// Reply A starts a subagent of its own, named only by its held events.
|
||||
event("session.execution.succeeded", { sessionID: CHILD }),
|
||||
report("msg_report_a", CHILD),
|
||||
event("session.execution.started", { sessionID: SESSION }),
|
||||
event("session.tool.input.started", { ...spawn, name: "subagent" }),
|
||||
event("session.tool.called", {
|
||||
...spawn,
|
||||
name: "subagent",
|
||||
input: { description: "Sleep", prompt: "sleep", background: true },
|
||||
executed: false,
|
||||
}),
|
||||
event("session.created", { ...childCreated(SPAWNED), sessionID: SPAWNED }),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
event("session.execution.succeeded", { sessionID: CHILD_B }),
|
||||
report("msg_report_b", CHILD_B),
|
||||
event("session.execution.started", { sessionID: SESSION }),
|
||||
event("session.text.ended", {
|
||||
sessionID: SESSION,
|
||||
assistantMessageID: "msg_reply_b",
|
||||
ordinal: 0,
|
||||
text: "REPLY_B",
|
||||
}),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
// B's continuation skips reply A and stops its subagent, which never answers.
|
||||
out("session.interrupt", { sessionID: SPAWNED }),
|
||||
reply("session.interrupt", "<hang>"),
|
||||
]).pipe(
|
||||
Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
|
||||
offer: (request) =>
|
||||
Effect.suspend(() =>
|
||||
offers.push(request) === 2
|
||||
? Deferred.succeed(bothOffered, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
),
|
||||
take: Effect.never,
|
||||
}),
|
||||
);
|
||||
const ended = yield* terminals(runtime, 2);
|
||||
yield* runtime.startTurn(withLineage(thread));
|
||||
yield* Deferred.await(bothOffered);
|
||||
yield* runtime.startTurn(continuationTurn(thread, offers[1]!, "wake-b"));
|
||||
// B's reply replays and ends its turn while that Stop still waits.
|
||||
assert.deepEqual(
|
||||
[...(yield* Fiber.join(ended))].map((terminal) => terminal.status),
|
||||
["completed", "completed"],
|
||||
);
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("replays only its own background reply into a continuation turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const CHILD_B = "ses_f1485c529ffeBBBBBBBBBBBBBB";
|
||||
const toolB = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-b" };
|
||||
const report = (inboxID: string, child: string, text: string) =>
|
||||
event("session.inbox.enqueued", {
|
||||
inboxID,
|
||||
sessionID: SESSION,
|
||||
item: {
|
||||
type: "synthetic",
|
||||
payload: {
|
||||
text: `<subagent sessionID="${child}" state="completed" description="Sleep">\n${text}\n</subagent>`,
|
||||
description: "Sleep",
|
||||
metadata: {
|
||||
source: "subagent",
|
||||
childID: child,
|
||||
agent: "General",
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
delivery: "steer",
|
||||
},
|
||||
});
|
||||
const reply = (assistantMessageID: string, text: string) =>
|
||||
event("session.text.ended", { sessionID: SESSION, assistantMessageID, ordinal: 0, text });
|
||||
const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
|
||||
const bothOffered = yield* Deferred.make<void>();
|
||||
const { runtime, thread } = yield* resumed([
|
||||
...backgroundLaunch(CHILD),
|
||||
// The same turn starts a second background subagent.
|
||||
event("session.tool.input.started", { ...toolB, name: "subagent" }),
|
||||
event("session.tool.called", {
|
||||
...toolB,
|
||||
name: "subagent",
|
||||
input: { description: "Sleep", prompt: "sleep", background: true },
|
||||
executed: false,
|
||||
}),
|
||||
event("session.created", { ...childCreated(CHILD_B), sessionID: CHILD_B }),
|
||||
event("session.tool.progress", {
|
||||
...toolB,
|
||||
metadata: { sessionID: CHILD_B, status: "running" },
|
||||
}),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
// Each subagent's report wakes the parent into a reply OpenCode runs on its own.
|
||||
event("session.execution.succeeded", { sessionID: CHILD }),
|
||||
report("msg_report_a", CHILD, "A_OK"),
|
||||
event("session.execution.started", { sessionID: SESSION }),
|
||||
event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_report_a" }),
|
||||
reply("msg_reply_a", "REPLY_A"),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
event("session.execution.succeeded", { sessionID: CHILD_B }),
|
||||
report("msg_report_b", CHILD_B, "B_OK"),
|
||||
event("session.execution.started", { sessionID: SESSION }),
|
||||
event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_report_b" }),
|
||||
reply("msg_reply_b", "REPLY_B"),
|
||||
event("session.execution.succeeded", { sessionID: SESSION }),
|
||||
]).pipe(
|
||||
Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
|
||||
offer: (request) =>
|
||||
Effect.suspend(() =>
|
||||
offers.push(request) === 2
|
||||
? Deferred.succeed(bothOffered, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
),
|
||||
take: Effect.never,
|
||||
}),
|
||||
);
|
||||
const collected: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
|
||||
const ended = yield* Deferred.make<void>();
|
||||
yield* runtime.events.pipe(
|
||||
Stream.tap((event) =>
|
||||
Effect.gen(function* () {
|
||||
collected.push(event);
|
||||
if (collected.filter((entry) => entry.type === "turn.terminal").length === 2) {
|
||||
yield* Deferred.succeed(ended, undefined);
|
||||
}
|
||||
}),
|
||||
),
|
||||
Stream.runDrain,
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* runtime.startTurn(withLineage(thread));
|
||||
yield* Deferred.await(bothOffered);
|
||||
// A's continuation was cancelled before it started; B's runs.
|
||||
yield* runtime.startTurn(continuationTurn(thread, offers[1]!, "wake-b"));
|
||||
yield* Deferred.await(ended);
|
||||
const continuationId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
|
||||
driver: OPENCODE_PROVIDER,
|
||||
nativeTurnId: `${SESSION}:attempt:attempt:opencode2-adapter:wake-b`,
|
||||
});
|
||||
assert.deepEqual(
|
||||
collected.flatMap((event) =>
|
||||
event.type === "turn_item.updated" &&
|
||||
event.turnItem.type === "assistant_message" &&
|
||||
event.turnItem.providerTurnId === continuationId
|
||||
? [event.turnItem.text]
|
||||
: [],
|
||||
),
|
||||
["REPLY_B"],
|
||||
);
|
||||
// Nothing is left held for a continuation that will never run.
|
||||
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
|
||||
}).pipe(Effect.scoped, Effect.provide(IdAllocator.layer)),
|
||||
);
|
||||
|
||||
it.effect("ends a follow-up turn a steer joined exactly once", () =>
|
||||
Effect.gen(function* () {
|
||||
const reportText = `<subagent sessionID="${CHILD}" state="completed" description="Sleep">\nCHILD_OK\n</subagent>`;
|
||||
@@ -4534,19 +5194,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
|
||||
yield* Effect.gen(function* () {
|
||||
while (offers.length === 0) yield* Effect.yieldNow;
|
||||
}).pipe(Effect.timeout("2 seconds"), Effect.orDie);
|
||||
const followUp = {
|
||||
...withLineage(thread),
|
||||
runId: RunId.make("run:opencode2-adapter:wake"),
|
||||
runOrdinal: 2,
|
||||
providerTurnOrdinal: 2,
|
||||
attemptId: RunAttemptId.make("attempt:opencode2-adapter:wake"),
|
||||
message: {
|
||||
...turnInput(thread).message,
|
||||
messageId: MessageId.make("message:opencode2-adapter:wake"),
|
||||
createdBy: "agent" as const,
|
||||
creationSource: "provider" as const,
|
||||
},
|
||||
};
|
||||
const followUp = continuationTurn(thread, offers[0]!);
|
||||
yield* runtime.startTurn(followUp);
|
||||
const followUpTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
|
||||
driver: OPENCODE_PROVIDER,
|
||||
|
||||
@@ -180,6 +180,25 @@ describe("ProviderContinuationService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("dispatches a wake under the message its adapter named", () => {
|
||||
return Effect.gen(function* () {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
const messageId = MessageId.make("message-provider-continuation-adapter-named");
|
||||
yield* Effect.gen(function* () {
|
||||
const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
|
||||
yield* requests.offer({ ...request(), messageId });
|
||||
const command = (yield* Queue.take(dispatched)) as { readonly messageId: MessageId };
|
||||
// The adapter matches the continuation run's message to the wake it holds.
|
||||
assert.equal(command.messageId, messageId);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("delivers a message_text wake as a real prompt, not a buffered wake", () => {
|
||||
return Effect.gen(function* () {
|
||||
const dispatched = yield* Queue.unbounded<unknown>();
|
||||
|
||||
@@ -147,10 +147,12 @@ export const layer = Layer.effectDiscard(
|
||||
}
|
||||
// The ordinal is display metadata only: allocate.message appends a
|
||||
// random UUID, so a stale projection read here cannot collide ids.
|
||||
const messageId = yield* ids.allocate.message({
|
||||
threadId: request.threadId,
|
||||
ordinal: projection.messages.length + 1,
|
||||
});
|
||||
const messageId =
|
||||
request.messageId ??
|
||||
(yield* ids.allocate.message({
|
||||
threadId: request.threadId,
|
||||
ordinal: projection.messages.length + 1,
|
||||
}));
|
||||
const commandId = CommandId.make(`provider-continuation:${messageId}`);
|
||||
const dispatch = threads.dispatch({
|
||||
type: "message.dispatch",
|
||||
|
||||
@@ -41,6 +41,12 @@ export interface ProviderContinuationRequest {
|
||||
* reach the provider as a real prompt.
|
||||
*/
|
||||
readonly delivery?: "adapter_buffered" | "message_text";
|
||||
/**
|
||||
* The message the continuation run starts from, when the adapter picks it:
|
||||
* its turn input carries this id, so the adapter can tell which of its held
|
||||
* wakes a run was dispatched for. Otherwise the service allocates one.
|
||||
*/
|
||||
readonly messageId?: MessageId;
|
||||
readonly dispatchIfCurrent?: <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
) => Effect.Effect<Option.Option<A>, E, R>;
|
||||
|
||||
@@ -49,6 +49,7 @@ import {
|
||||
type OrchestrationV2Subagent,
|
||||
type OrchestrationV2TurnItem,
|
||||
type OrchestrationV2UserInputQuestion,
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderInstanceId,
|
||||
@@ -305,6 +306,8 @@ interface SubagentCall {
|
||||
* the continuation turn T3 opens for it takes them.
|
||||
*/
|
||||
interface Wake {
|
||||
/** The message its continuation run starts from, which names the wake in that turn's input. */
|
||||
readonly messageId: MessageId | undefined;
|
||||
readonly events: Array<OpenCode2Client.OpenCode2StreamEvent>;
|
||||
running: boolean;
|
||||
/** The background subagents whose end it answers, as its turn's notification names them. */
|
||||
@@ -317,6 +320,11 @@ interface Wake {
|
||||
readonly after: string | undefined;
|
||||
/** The first report it delivered, where fork and rollback cut before its turn. */
|
||||
readonly first: string | undefined;
|
||||
/**
|
||||
* Subagent sessions OpenCode announced while it was held: their calls are
|
||||
* in its events, so only its replay names them.
|
||||
*/
|
||||
readonly children: Set<string>;
|
||||
}
|
||||
|
||||
interface OpenBlock {
|
||||
@@ -907,6 +915,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
const childOwners = new Map<string, ThreadState>();
|
||||
// What OpenCode announced about a subagent's session, until its call names it.
|
||||
const announced = new Map<string, EventOf<"session.created">["data"]>();
|
||||
// Subagent sessions a dropped held execution started, and the subagents
|
||||
// they start, by the session the first of them was called from. Nothing
|
||||
// names them, so they no longer route to its thread; they stay here until
|
||||
// a Stop of that thread stops them or they are gone.
|
||||
const strays = new Map<string, ThreadState>();
|
||||
// Sessions of these threads with an execution running, seen on the stream.
|
||||
const busy = new Set<string>();
|
||||
const pending = new Map<RuntimeRequestId, PendingRequest>();
|
||||
@@ -1687,13 +1700,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
*/
|
||||
const offerWake = Effect.fnUntraced(function* (state: ThreadState, wake: Wake) {
|
||||
const route = state.providerThread.appThreadId;
|
||||
if (route === null) return;
|
||||
if (route === null || wake.messageId === undefined) return;
|
||||
const notification = backgroundWorkNotification(wake.reports);
|
||||
yield* continuationRequests.offer({
|
||||
threadId: route,
|
||||
providerThreadId: state.providerThread.id,
|
||||
driver,
|
||||
detail: wake.detail,
|
||||
messageId: wake.messageId,
|
||||
...(notification === null ? {} : { notification }),
|
||||
dispatchIfCurrent: (dispatch) =>
|
||||
wake.dropped ? Effect.succeed(Option.none()) : Effect.map(dispatch, Option.some),
|
||||
@@ -2153,6 +2167,15 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
| { readonly type: "form"; readonly form: NativeForm },
|
||||
) {
|
||||
const asking = asked.type === "permission" ? asked.request.sessionID : asked.form.sessionID;
|
||||
// A stray belongs to no turn: its request is refused, which ends its run.
|
||||
if (strays.has(asking)) {
|
||||
return yield* stopStaleRequest(
|
||||
asking,
|
||||
asked.type === "permission"
|
||||
? { type: "permission", id: asked.request.id }
|
||||
: { type: "form", id: asked.form.id },
|
||||
);
|
||||
}
|
||||
const state = ownerOf(asking);
|
||||
if (state === undefined) return;
|
||||
const target = requestTurn(asking);
|
||||
@@ -2381,7 +2404,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
const onWake = Effect.fnUntraced(function* (state: ThreadState) {
|
||||
const { delivered, stopped } = yield* takeReports(state);
|
||||
if (stopped) return;
|
||||
const route = state.providerThread.appThreadId;
|
||||
const wake: Wake = {
|
||||
// Only a thread's wake is offered a continuation; the ordinal is display metadata.
|
||||
messageId:
|
||||
route === null
|
||||
? undefined
|
||||
: yield* idAllocator.allocate.message({ threadId: route, ordinal: 0 }),
|
||||
events: [],
|
||||
running: true,
|
||||
reports: delivered.map((entry) => entry.report),
|
||||
@@ -2389,6 +2418,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
dropped: false,
|
||||
after: delivered.at(-1)?.inboxId,
|
||||
first: delivered[0]?.inboxId,
|
||||
children: new Set(),
|
||||
};
|
||||
state.wakes.push(wake);
|
||||
yield* Effect.logInfo("OpenCode started a turn on its own; asking for a continuation.", {
|
||||
@@ -2408,6 +2438,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
) {
|
||||
const childId = stringField(payload.metadata, "childID");
|
||||
if (stringField(payload.metadata, "source") !== "subagent" || childId === undefined) return;
|
||||
// A stray that reports has ended: no Stop needs to reach it.
|
||||
strays.delete(childId);
|
||||
const call = [...state.calls.values()].find(
|
||||
(candidate) => candidate.child?.sessionId === childId,
|
||||
);
|
||||
@@ -2513,10 +2545,17 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
}
|
||||
// A subagent's session: named on its parent's `subagent` call just after.
|
||||
if (event.type === "session.created" && event.data.parentID !== undefined) {
|
||||
// A stray's subagent is a stray too: no call of the thread's names it.
|
||||
const strayCaller = strays.get(event.data.parentID);
|
||||
if (strayCaller !== undefined) {
|
||||
strays.set(event.data.sessionID, strayCaller);
|
||||
return;
|
||||
}
|
||||
const owner = ownerOf(event.data.parentID);
|
||||
if (owner !== undefined) {
|
||||
childOwners.set(event.data.sessionID, owner);
|
||||
announced.set(event.data.sessionID, event.data);
|
||||
holderOf(event.data.parentID)?.wakes.at(-1)?.children.add(event.data.sessionID);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -2806,7 +2845,15 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
(state) => state.subagent === undefined && hasBackground(state),
|
||||
);
|
||||
const marked = [...threads.values()].some((state) => state.unsettled);
|
||||
if (running.length === 0 && background.length === 0 && busy.size === 0 && !marked) return;
|
||||
if (
|
||||
running.length === 0 &&
|
||||
background.length === 0 &&
|
||||
busy.size === 0 &&
|
||||
!marked &&
|
||||
strays.size === 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const active = yield* client.session.active();
|
||||
// An execution that ended while the stream was down never said so.
|
||||
for (const sessionId of busy) if (!(sessionId in active)) busy.delete(sessionId);
|
||||
@@ -2817,6 +2864,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
for (const state of threads.values()) {
|
||||
if (state.unsettled && !(state.sessionId in active)) state.unsettledStarted = true;
|
||||
}
|
||||
// A stray that stopped meanwhile runs nothing to stop.
|
||||
for (const childId of strays.keys()) if (!(childId in active)) strays.delete(childId);
|
||||
for (const [sessionId, state] of running) {
|
||||
const turn = state.active;
|
||||
if (turn === undefined) continue;
|
||||
@@ -2848,10 +2897,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
}
|
||||
// A subagent's session holds reports of its own background subagents.
|
||||
for (const session of sessionsOf(state)) {
|
||||
for (const wake of session.wakes.splice(0)) wake.dropped = true;
|
||||
discardWakes(session, session.wakes.splice(0));
|
||||
session.reports.clear();
|
||||
}
|
||||
}
|
||||
// Stopped off the lock this reconcile holds; one still running waits for a Stop.
|
||||
for (const thread of new Set([...strays.values()].map(rootOf))) {
|
||||
yield* Effect.forkIn(stopStrays(thread), sessionScope);
|
||||
}
|
||||
// A request asked while the stream was down was never shown, and the
|
||||
// run waits on it; one T3 shows that OpenCode no longer lists was
|
||||
// answered elsewhere or dropped with its execution. A session that
|
||||
@@ -3442,6 +3495,62 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
for (const event of wake.events) yield* route(event, sessionOfEvent(event), true);
|
||||
});
|
||||
|
||||
/**
|
||||
* Drops held executions no turn will take. The subagents one started are
|
||||
* named only by its replay, so they stop routing to the thread at once and
|
||||
* become strays for {@link stopStrays}. A subagent that registered its own
|
||||
* call outside the held execution is the thread's, and is left alone.
|
||||
*/
|
||||
const discardWakes = (caller: ThreadState, wakes: ReadonlyArray<Wake>) => {
|
||||
const retired = new Set<string>();
|
||||
const retire = (childId: string) => {
|
||||
const info = announced.get(childId);
|
||||
if (info === undefined) return;
|
||||
announced.delete(childId);
|
||||
childOwners.delete(childId);
|
||||
strays.set(childId, caller);
|
||||
retired.add(childId);
|
||||
// OpenCode reports its end to the session that called it; that
|
||||
// report answers no turn, so the execution it wakes is stopped. A
|
||||
// deeper one reports to a stray, which T3 does not track.
|
||||
threads.get(info.parentID ?? "")?.stoppedChildren.add(childId);
|
||||
};
|
||||
for (const wake of wakes) {
|
||||
wake.dropped = true;
|
||||
for (const childId of wake.children) retire(childId);
|
||||
}
|
||||
// Their own subagents, at any depth, were announced live but no call
|
||||
// of the thread's names them either.
|
||||
for (let grew = retired.size > 0; grew;) {
|
||||
grew = false;
|
||||
for (const [childId, info] of announced) {
|
||||
if (info.parentID === undefined || !retired.has(info.parentID)) continue;
|
||||
retire(childId);
|
||||
grew = true;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Stops a thread's strays one by one, as a Stop stops background
|
||||
* subagents, and never under `lock`: one that does not answer would
|
||||
* otherwise hold up every event. A stray is forgotten once stopped or
|
||||
* gone; one still running waits for the next Stop.
|
||||
*/
|
||||
const stopStrays = (thread: ThreadState) =>
|
||||
Effect.forEach(
|
||||
[...strays].flatMap(([childId, caller]) => (rootOf(caller) === thread ? [childId] : [])),
|
||||
(childId) =>
|
||||
client.session.interrupt({ sessionID: Session.ID.make(childId) }).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.catchTags({ SessionNotFoundError: () => Effect.void }),
|
||||
Effect.timeout(INTERRUPT_TIMEOUT),
|
||||
Effect.tap(() => Effect.sync(() => strays.delete(childId))),
|
||||
Effect.ignore({ log: true }),
|
||||
),
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
/**
|
||||
* A user turn that starts while OpenCode runs an execution on its own: the
|
||||
* prompt joins that execution, so the turn takes it, and its continuation
|
||||
@@ -3456,8 +3565,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
|
||||
/**
|
||||
* The continuation turn for an execution OpenCode started on its own: it
|
||||
* takes the oldest one held and ends with it. One already taken (a user
|
||||
* turn joined it) leaves nothing to run, so the turn ends at once.
|
||||
* takes the wake it was dispatched for, named by its message, and ends
|
||||
* with it. Wakes held before that one had their continuation cancelled or
|
||||
* dropped before it started, so nothing will replay them: they are
|
||||
* dropped. One already taken (a user turn joined it) leaves nothing to
|
||||
* run, so the turn ends at once.
|
||||
*/
|
||||
const runWake = Effect.fnUntraced(function* (
|
||||
state: ThreadState,
|
||||
@@ -3466,8 +3578,16 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
yield* beginTurn(state, turnInput, false);
|
||||
yield* lock.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const wake = state.wakes.shift();
|
||||
if (wake === undefined) return yield* finishTurn(state, { status: "completed" });
|
||||
const index = state.wakes.findIndex(
|
||||
(held) => held.messageId === turnInput.message.messageId,
|
||||
);
|
||||
if (index < 0) return yield* finishTurn(state, { status: "completed" });
|
||||
// Queued continuations can't be reordered (they carry a notification),
|
||||
// so an earlier wake here lost its continuation to a cancel or a failed
|
||||
// dispatch. Dropping it keeps that wake from pinning the session.
|
||||
discardWakes(state, state.wakes.splice(0, index));
|
||||
yield* Effect.forkIn(stopStrays(state), sessionScope);
|
||||
const wake = state.wakes.shift()!;
|
||||
const turn = state.active;
|
||||
if (turn !== undefined && wake.after !== undefined) turn.before = wake.after;
|
||||
// Its first report is where its history begins, so fork and rollback cut there.
|
||||
@@ -3557,7 +3677,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
}
|
||||
// A held wake no turn will take: its execution is stopped, not replayed.
|
||||
const running = state.wakes.some((wake) => wake.running);
|
||||
for (const wake of state.wakes.splice(0)) wake.dropped = true;
|
||||
discardWakes(state, state.wakes.splice(0));
|
||||
if (running) {
|
||||
markUnsettled(state);
|
||||
yield* client.session
|
||||
@@ -3566,6 +3686,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
|
||||
}
|
||||
}),
|
||||
);
|
||||
// Subagents of held executions this or an earlier Stop dropped.
|
||||
yield* stopStrays(state);
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user