@devries-cameron20 / t3code-1 / commits / ed52af3a47
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(opencode): track native shell jobs across turns

## Problem OpenCode shell tools can return when a background command launches. T3 now keeps that command in its existing background activity UI until it exits or is stopped, retains captured output, and preserves native completion notifications and continuation turns. ## Change The adapter scopes tracking and Stop to the owning session and its descendants. Recovery uses the experimental shell-job inventory on OpenCode 2.2.6+, with shell-list fallback on supported older servers. After a cold resume, recovered output, terminal state, and idle roster snapshots persist through the existing session event pump before another turn starts. New session-scoped activity is restricted to attached threads and uses the persisted run identity when available so it stays in the current timeline. Polling reads run outside the adapter lock, with stale results discarded after Stop, exit, or another read. Recovery and Stop retain bounded I/O. Final reads retain the output tail, including diagnostics beyond the first four pages. The SDK remains pinned to 2.0.28, and main's native goals, todo checklists, and image jobs are preserved. ## Scope and approval Maintainer-directed implementation of native OpenCode background shell tracking from the T3 Code handoff. Scope covers shell lifecycle, output retention, recovery, ownership, and Stop using existing background activity services and rendering. The session event pump extension is needed to persist recovered activity while no turn is active. No SDK upgrade, new UI, or provider-wide infrastructure is included. The author, Yash-Singh1, is explicitly listed in the repository's [contribution-triage exemptions](https://github.com/pingdotgg/t3code/blob/main/.github/TRIAGE_EXEMPTIONS.td), verified against upstream main. ## Verification Validation: `vp run check:changed` passes. Focused regressions cover output paging, exit codes, idle recovery, persisted run anchors, ownership, cancellation failures, and a stalled poll that must not block turn completion or Stop. Real OpenCode UI turns used MiniMax M3.1 Flash Free against isolated development state and covered launch, Details and retained output, natural completion, continuation, and explicit Stop. Cold-idle persistence and remote-server paths use protocol fixtures; native mobile was not exercised. GPT 6.1 Sol through the Codex harness.

Yash Singh committed Nov 10, 2026 at 22:39 UTC ed52af3a478652c55aeaaf5a64bbf6584dd6a0b4
7 files changed +1313 -124
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+587 -23
@@ -142,6 +142,11 @@ const promptAccepted = replyData("session.prompt", {
142 delivery: "steer",
143 });
144
145 +const emptyShellInventory: ReadonlyArray<ProviderReplayEntry> = [
146 + out("shell.list", "<any>"),
147 + reply("shell.list", { location: { directory: WORK }, data: [] }),
148 +];
149 +
150 const noOpenRequests: ReadonlyArray<ProviderReplayEntry> = [
151 out("permission.list", { sessionID: SESSION }),
152 replyData("permission.list", []),
@@ -317,7 +322,9 @@ const colorForm = {
322 const resumed = (
323 entries: ReadonlyArray<ProviderReplayEntry>,
324 options?: {
320 - readonly version?: "2.2.5" | "2.2.6";
325 + readonly version?: "2.2.1" | "2.2.5" | "2.2.6";
326 + readonly shellRecovery?: ReadonlyArray<ProviderReplayEntry>;
327 + readonly lastRunOrdinal?: number;
328 readonly goal?: OrchestrationV2ProviderThread["goal"];
329 readonly external?: boolean;
330 readonly supervised?: boolean;
@@ -336,9 +343,17 @@ const resumed = (
343 out("session.get", { sessionID: SESSION }),
344 replyData("session.get", sessionInfo()),
345 ...noOpenRequests,
339 - ...(options?.version !== undefined
346 + ...(options?.version === "2.2.5" || options?.version === "2.2.6"
347 ? [out("rpc.call", "<any>"), reply("rpc.call", { output: null })]
348 : []),
349 + ...(options?.shellRecovery ??
350 + (options?.version === undefined
351 + ? []
352 + : [
353 + ...(options.version === "2.2.6"
354 + ? [out("job.list", { kind: "shell" }), reply("job.list", { data: [] })]
355 + : emptyShellInventory),
356 + ])),
357 ...withInstructions([
358 ...(options?.supervised === true
359 ? [
@@ -369,6 +384,9 @@ const resumed = (
384 const thread = yield* runtime.resumeThread({
385 providerThread: {
386 ...providerThread(yield* DateTime.now),
387 + ...(options?.lastRunOrdinal === undefined
388 + ? {}
389 + : { lastRunOrdinal: options.lastRunOrdinal }),
390 ...(options?.goal === undefined ? {} : { goal: options.goal }),
391 },
392 threadId,
@@ -886,6 +904,448 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
904 );
905 return { attached: Deferred.await(attached), terminal: Fiber.join(terminal) };
906 });
907 + it.effect.each([false, true, "thread", "failed", "burst", "poll"] as const)(
908 + "tracks native background shells through launch, retained output, stop=%s",
909 + (stop) =>
910 + Effect.gen(function* () {
911 + const stopped = stop === true || stop === "thread" || stop === "poll";
912 + const exitCode = stop === "failed" ? 7 : 0;
913 + const shellID = "sh_background";
914 + const tool = {
915 + sessionID: SESSION,
916 + assistantMessageID: "msg_assistant",
917 + id: "call-shell",
918 + };
919 + const gate = makeProviderReplayGate(["shell-exit"]);
920 + const { runtime, thread } = yield* resumed(
921 + [
922 + out("session.prompt", { sessionID: SESSION, text: "<any>" }),
923 + promptAccepted,
924 + event("session.execution.started", { sessionID: SESSION }),
925 + event("session.tool.input.started", { ...tool, name: "shell" }),
926 + event("session.tool.called", {
927 + ...tool,
928 + name: "shell",
929 + input: { command: "echo retained", background: true },
930 + executed: false,
931 + }),
932 + event(
933 + "session.tool.success",
934 + {
935 + ...tool,
936 + content: [{ type: "text", text: "Launched" }],
937 + metadata: { shellID },
938 + executed: false,
939 + },
940 + undefined,
941 + 2,
942 + ),
943 + out("shell.output", "<any>"),
944 + reply("shell.output", {
945 + location: { directory: WORK },
946 + data: { output: "retained\n", cursor: 9, size: 9, truncated: false },
947 + }),
948 + ...(stop === "poll"
949 + ? [out("shell.output", "<any>"), reply("shell.output", "<hang>")]
950 + : []),
951 + event("session.execution.succeeded", { sessionID: SESSION }),
952 + ...(stopped
953 + ? []
954 + : [
955 + event(
956 + "shell.exited",
957 + { id: shellID, exit: exitCode, status: "exited" },
958 + "shell-exit",
959 + ),
960 + ]),
961 + ...(stop === "burst"
962 + ? Array.from({ length: 5 }, (_, page) => [
963 + out("shell.output", { cursor: String(9 + page * 65536) }),
964 + reply("shell.output", {
965 + location: { directory: WORK },
966 + data: {
967 + output:
968 + page === 4 ? "x".repeat(65519) + "FINAL DIAGNOSTIC\n" : "x".repeat(65536),
969 + cursor: 9 + (page + 1) * 65536,
970 + size: 9 + 5 * 65536,
971 + truncated: false,
972 + },
973 + }),
974 + ]).flat()
975 + : [
976 + out("shell.output", "<any>"),
977 + reply("shell.output", {
978 + location: { directory: WORK },
979 + data: { output: "", cursor: 9, size: 9, truncated: false },
980 + }),
981 + ]),
982 + ...(stopped
983 + ? [
984 + out("shell.remove", { id: shellID, "location[directory]": WORK }),
985 + event("shell.exited", { id: shellID, exit: 143, status: "exited" }),
986 + reply("shell.remove", null),
987 + ]
988 + : []),
989 + ],
990 + { replayGate: gate },
991 + );
992 + const items: Array<import("@t3tools/contracts").OrchestrationV2TurnItem> = [];
993 + const shellStarted = yield* Deferred.make<void>();
994 + const terminal = yield* runtime.events.pipe(
995 + Stream.tap((e) =>
996 + Effect.gen(function* () {
997 + if (e.type !== "turn_item.updated") return;
998 + items.push(e.turnItem);
999 + if (e.turnItem.type === "command_execution" && e.turnItem.output === "retained\n")
1000 + yield* Deferred.succeed(shellStarted, undefined);
1001 + }),
1002 + ),
1003 + Stream.filter((e) => e.type === "turn.terminal"),
1004 + Stream.runHead,
1005 + Effect.forkScoped,
1006 + );
1007 + yield* runtime.startTurn(withLineage(thread));
1008 + if (stop === "poll") {
1009 + yield* Deferred.await(shellStarted);
1010 + yield* TestClock.adjust("2 seconds");
1011 + }
1012 + yield* Fiber.join(terminal);
1013 + assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1014 + const settled = yield* runtime.events.pipe(
1015 + Stream.tap((e) =>
1016 + Effect.sync(() => {
1017 + if (e.type === "turn_item.updated") items.push(e.turnItem);
1018 + }),
1019 + ),
1020 + Stream.filter(
1021 + (e) =>
1022 + e.type === "provider_thread.updated" &&
1023 + e.providerThread.pendingBackgroundTasks?.length === 0,
1024 + ),
1025 + Stream.runHead,
1026 + Effect.forkScoped,
1027 + );
1028 + if (stop === "thread")
1029 + yield* runtime.interruptTurn({
1030 + providerThread: thread,
1031 + providerTurnId: yield* providerTurnId,
1032 + requestRuntimeRestart: true,
1033 + });
1034 + else if (stopped) yield* runtime.stopTask!({ providerThread: thread, taskId: shellID });
1035 + else gate.release("shell-exit");
1036 + yield* Fiber.join(settled);
1037 + assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1038 + assert.deepInclude(items.filter((i) => i.type === "command_execution").at(-1), {
1039 + type: "command_execution",
1040 + status: stopped ? "interrupted" : stop === "failed" ? "failed" : "completed",
1041 + ...(stop === "failed" ? { exitCode: 7 } : {}),
1042 + output: stop === "burst" ? "x".repeat(262127) + "FINAL DIAGNOSTIC\n" : "retained\n",
1043 + });
1044 + assert.isFalse(items.some((i) => i.type === "subagent"));
1045 + }).pipe(Effect.scoped),
1046 + );
1047 +
1048 + it.effect.each([
1049 + "shell",
1050 + "job",
1051 + "fallback",
1052 + "descendant",
1053 + "settled",
1054 + "exited",
1055 + "anchored",
1056 + ] as const)("recovers only owned native shells using %s inventory", (discovery) =>
1057 + Effect.gen(function* () {
1058 + const idAllocator = yield* IdAllocator.IdAllocatorV2.pipe(Effect.provide(IdAllocator.layer));
1059 + const id = "sh_recovered";
1060 + const info = {
1061 + id,
1062 + command: "sleep 600",
1063 + status: discovery === "settled" ? "exited" : "running",
1064 + ...(discovery === "settled" ? { exit: 0 } : {}),
1065 + cwd: WORK,
1066 + shell: "/bin/sh",
1067 + file: "/remote/output",
1068 + metadata: { sessionID: SESSION },
1069 + time: { started: 1 },
1070 + };
1071 + const response = (data: unknown) => ({ location: { directory: WORK }, data });
1072 + const inventory: Array<ProviderReplayEntry> =
1073 + discovery === "shell"
1074 + ? []
1075 + : [
1076 + out("job.list", { sessionID: SESSION, kind: "shell", descendants: "true" }),
1077 + reply(
1078 + "job.list",
1079 + discovery === "fallback"
1080 + ? { status: 404, body: {} }
1081 + : {
1082 + data: [
1083 + {
1084 + kind: "shell",
1085 + shellID: id,
1086 + sessionID: discovery === "descendant" ? "ses_descendant" : SESSION,
1087 + command: info.command,
1088 + status: discovery === "settled" ? "completed" : "running",
1089 + },
1090 + ],
1091 + },
1092 + ),
1093 + ];
1094 + if (discovery === "shell" || discovery === "fallback")
1095 + inventory.push(
1096 + out("shell.list", "<any>"),
1097 + reply(
1098 + "shell.list",
1099 + response([info, { ...info, id: "sh_other", metadata: { sessionID: "ses_other" } }]),
1100 + ),
1101 + );
1102 + inventory.push(
1103 + out("shell.get", { id }),
1104 + reply("shell.get", response(info)),
1105 + out("shell.output", { id, cursor: "0" }),
1106 + reply(
1107 + "shell.output",
1108 + response({ output: "retained", cursor: 8, size: 8, truncated: false }),
1109 + ),
1110 + );
1111 + const gate = makeProviderReplayGate(["recovered-exit"]);
1112 + const { runtime, thread } = yield* resumed(
1113 + discovery === "settled"
1114 + ? []
1115 + : [
1116 + ...(discovery === "exited"
1117 + ? [event("shell.exited", { id, exit: 0, status: "exited" }, "recovered-exit")]
1118 + : []),
1119 + out("shell.output", { id, cursor: "8" }),
1120 + reply(
1121 + "shell.output",
1122 + response({
1123 + output: discovery === "exited" ? " finished" : "",
1124 + cursor: discovery === "exited" ? 17 : 8,
1125 + size: discovery === "exited" ? 17 : 8,
1126 + truncated: false,
1127 + }),
1128 + ),
1129 + ...(discovery === "exited"
1130 + ? []
1131 + : [out("shell.remove", { id }), reply("shell.remove", null)]),
1132 + ],
1133 + {
1134 + version: discovery === "shell" ? "2.2.1" : "2.2.6",
1135 + shellRecovery: inventory,
1136 + external: true,
1137 + ...(discovery === "anchored" ? { lastRunOrdinal: 7 } : {}),
1138 + replayGate: gate,
1139 + },
1140 + );
1141 + const items: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
1142 + const shellEnded = yield* Deferred.make<void>();
1143 + const rosterEnded = yield* Deferred.make<void>();
1144 + yield* runtime.events.pipe(
1145 + Stream.runForEach((event) =>
1146 + Effect.gen(function* () {
1147 + if (
1148 + event.type === "provider_thread.updated" &&
1149 + event.sessionScoped === true &&
1150 + event.providerThread.pendingBackgroundTasks?.length === 0
1151 + )
1152 + yield* Deferred.succeed(rosterEnded, undefined);
1153 + if (event.type !== "turn_item.updated" || event.turnItem.type !== "command_execution")
1154 + return;
1155 + items.push(event);
1156 + if (event.turnItem.status !== "running") yield* Deferred.succeed(shellEnded, undefined);
1157 + }),
1158 + ),
1159 + Effect.forkScoped,
1160 + );
1161 + assert.deepEqual(
1162 + thread.pendingBackgroundTasks ?? [],
1163 + discovery === "settled" ? [] : [{ taskId: id, kind: "command", description: info.command }],
1164 + );
1165 + assert.equal(
1166 + yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1167 + discovery !== "settled",
1168 + );
1169 + yield* runtime.stopTask!({ providerThread: thread, taskId: "sh_other" });
1170 + assert.equal(
1171 + yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1172 + discovery !== "settled",
1173 + );
1174 + if (discovery === "exited") gate.release("recovered-exit");
1175 + else yield* runtime.stopTask!({ providerThread: thread, taskId: id });
1176 + yield* Deferred.await(shellEnded);
1177 + yield* Deferred.await(rosterEnded);
1178 + assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1179 + const item = items;
1180 + const projected = item.at(0);
1181 + const stopped = item.at(-1);
1182 + if (stopped?.type === "turn_item.updated" && stopped.turnItem.type === "command_execution") {
1183 + assert.equal(
1184 + stopped.turnItem.status,
1185 + discovery === "settled" || discovery === "exited" ? "completed" : "interrupted",
1186 + );
1187 + assert.equal(
1188 + stopped.turnItem.output,
1189 + discovery === "exited" ? "retained finished" : "retained",
1190 + );
1191 + assert.equal(
1192 + stopped.turnItem.id,
1193 + projected?.type === "turn_item.updated" ? projected.turnItem.id : undefined,
1194 + );
1195 + }
1196 + assert.equal(projected?.type, "turn_item.updated");
1197 + if (projected?.type === "turn_item.updated") {
1198 + assert.isTrue(
1199 + item.every(
1200 + (event) =>
1201 + event.type === "turn_item.updated" &&
1202 + event.turnItem.runId ===
1203 + (discovery === "anchored"
1204 + ? idAllocator.derive.run({ threadId, ordinal: 7 })
1205 + : null),
1206 + ),
1207 + );
1208 + assert.deepInclude(projected.turnItem, {
1209 + type: "command_execution",
1210 + input: info.command,
1211 + output: "retained",
1212 + });
1213 + }
1214 + }).pipe(Effect.scoped),
1215 + );
1216 +
1217 + it.effect.each(["remove", "lookup", "output", "timeout"] as const)(
1218 + "continues recovering and stopping native work when shell %s fails",
1219 + (failure) =>
1220 + Effect.gen(function* () {
1221 + const ids = ["sh_unreachable", "sh_stoppable"];
1222 + const info = (id: string) => ({
1223 + id,
1224 + command: "sleep 600",
1225 + status: "running",
1226 + cwd: WORK,
1227 + shell: "/bin/sh",
1228 + file: "/remote/output",
1229 + metadata: { sessionID: SESSION },
1230 + time: { started: 1 },
1231 + });
1232 + const response = (data: unknown) => ({ location: { directory: WORK }, data });
1233 + const output = (id: string) => [
1234 + out("shell.output", { id }),
1235 + reply("shell.output", response({ output: "", cursor: 0, size: 0, truncated: false })),
1236 + ];
1237 + const gate = makeProviderReplayGate(["recovery-pending", "polled"]);
1238 + const recovery = yield* resumed(
1239 + [
1240 + ...backgroundLaunch(CHILD),
1241 + ...output(ids[0]!),
1242 + out("shell.remove", { id: ids[0] }),
1243 + reply("shell.remove", failure === "remove" ? { status: 500, body: {} } : null),
1244 + ...output(ids[1]!),
1245 + out("shell.remove", { id: ids[1] }),
1246 + reply("shell.remove", null),
1247 + out("session.interrupt", { sessionID: CHILD }),
1248 + reply("session.interrupt", { interrupted: true }),
1249 + out("session.interrupt", { sessionID: SESSION }),
1250 + reply("session.interrupt", { interrupted: true }),
1251 + event("session.execution.interrupted", { sessionID: SESSION }),
1252 + ...(failure === "remove"
1253 + ? [
1254 + ...output(ids[0]!),
1255 + out("shell.remove", { id: ids[0] }),
1256 + reply("shell.remove", null),
1257 + ]
1258 + : []),
1259 + ],
1260 + {
1261 + version: "2.2.1",
1262 + replayGate: gate,
1263 + shellRecovery: [
1264 + out("shell.list", "<any>"),
1265 + reply("shell.list", response(ids.map(info))),
1266 + ...(failure === "timeout"
1267 + ? [
1268 + out("shell.get", { id: ids[0] }),
1269 + reply("shell.get", "<hang>"),
1270 + event(
1271 + "session.execution.succeeded",
1272 + { sessionID: "ses_unrelated" },
1273 + "recovery-pending",
1274 + ),
1275 + ...ids.map((id) => out("shell.output", { id })),
1276 + ...ids.map(() =>
1277 + reply(
1278 + "shell.output",
1279 + response({ output: "", cursor: 0, size: 0, truncated: false }),
1280 + ),
1281 + ),
1282 + event("session.execution.succeeded", { sessionID: "ses_unrelated" }, "polled"),
1283 + ]
1284 + : ids.flatMap((id) => [
1285 + out("shell.get", { id }),
1286 + reply(
1287 + "shell.get",
1288 + id === ids[0] && failure === "lookup"
1289 + ? { status: 500, body: {} }
1290 + : response(info(id)),
1291 + ),
1292 + ...(id === ids[0] && failure === "lookup"
1293 + ? []
1294 + : id === ids[0] && failure === "output"
1295 + ? [
1296 + out("shell.output", { id }),
1297 + reply("shell.output", { status: 500, body: {} }),
1298 + ]
1299 + : output(id)),
1300 + ])),
1301 + ],
1302 + },
1303 + ).pipe(Effect.forkScoped);
1304 + if (failure === "timeout") {
1305 + yield* Effect.promise(() => gate.waitForReached("recovery-pending"));
1306 + yield* TestClock.adjust("5 seconds");
1307 + }
1308 + const { runtime, thread } = yield* Fiber.join(recovery);
1309 + const recovered = yield* runtime.events.pipe(
1310 + Stream.takeUntil(
1311 + (event) =>
1312 + event.type === "provider_thread.updated" &&
1313 + event.providerThread.pendingBackgroundTasks?.length === 2,
1314 + ),
1315 + Stream.runCollect,
1316 + );
1317 + assert.sameMembers(
1318 + recovered.flatMap((event) =>
1319 + event.type === "turn_item.updated" && event.turnItem.type === "command_execution"
1320 + ? [event.turnItem.nativeItemRef?.nativeId]
1321 + : [],
1322 + ),
1323 + ids,
1324 + );
1325 + if (failure === "timeout") {
1326 + gate.release("recovery-pending");
1327 + yield* Effect.promise(() => gate.waitForReached("polled"));
1328 + gate.release("polled");
1329 + }
1330 + const watch = yield* watchBackgroundTurn(runtime);
1331 + yield* runtime.startTurn(withLineage(thread));
1332 + yield* watch.attached;
1333 + yield* runtime.interruptTurn({
1334 + providerThread: thread,
1335 + providerTurnId: yield* providerTurnId,
1336 + requestRuntimeRestart: true,
1337 + });
1338 + assert.equal((yield* watch.terminal)?.status, "interrupted");
1339 + assert.equal(
1340 + yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1341 + failure === "remove",
1342 + );
1343 + if (failure === "remove")
1344 + yield* runtime.stopTask!({ providerThread: thread, taskId: ids[0]! });
1345 + assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1346 + }).pipe(Effect.scoped),
1347 + );
1348 +
1349 it.effect("keeps background subagents running when a turn is interrupted to restart it", () =>
1350 Effect.gen(function* () {
1351 const { runtime, thread } = yield* resumed([
@@ -1173,26 +1633,119 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1633 event("session.execution.started", { sessionID: CHILD }),
1634 ];
1635
1176 - it.effect("settles a background subagent that fails, so no work is left pending", () =>
1177 - Effect.gen(function* () {
1178 - const { runtime, thread } = yield* resumed([
1179 - ...launchedAndRunning,
1180 - // The parent turn ends, and the background child fails: it reports
1181 - // nothing back, so its call has to end with the failure.
1182 - event("session.execution.succeeded", { sessionID: SESSION }),
1183 - event("session.execution.failed", {
1184 - sessionID: CHILD,
1185 - error: { type: "provider.quota", message: "Rate limit exceeded." },
1186 - }),
1187 - ]);
1188 - const watch = yield* watchCalls(runtime, thread);
1189 - yield* runtime.startTurn(withLineage(thread));
1190 - yield* watch.until(
1191 - () => watch.calls.get("Sleep")?.status === "failed" && watch.state.roster?.length === 0,
1192 - );
1193 - assert.deepEqual(watch.state.roster, []);
1194 - assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1195 - }).pipe(Effect.scoped),
1636 + it.effect.each([false, true])(
1637 + "settles a failed background subagent with recovered child=%s",
1638 + (recoveredChild) =>
1639 + Effect.gen(function* () {
1640 + const ids = yield* IdAllocator.IdAllocatorV2.pipe(Effect.provide(IdAllocator.layer));
1641 + const childThreadId = ids.derive.threadFromProviderThread({
1642 + driver: OPENCODE_PROVIDER,
1643 + nativeThreadId: CHILD,
1644 + providerInstanceId: instanceId,
1645 + });
1646 + const childProviderThread = {
1647 + ...providerThread(yield* DateTime.now),
1648 + id: ids.derive.providerThread({
1649 + driver: OPENCODE_PROVIDER,
1650 + nativeThreadId: CHILD,
1651 + providerInstanceId: instanceId,
1652 + }),
1653 + appThreadId: childThreadId,
1654 + nativeThreadRef: {
1655 + driver: OPENCODE_PROVIDER,
1656 + nativeId: CHILD,
1657 + strength: "strong" as const,
1658 + },
1659 + };
1660 + const shell = {
1661 + id: "sh_old_child",
1662 + command: "echo done",
1663 + status: "exited",
1664 + exit: 0,
1665 + cwd: WORK,
1666 + shell: "/bin/sh",
1667 + file: "/remote/output",
1668 + metadata: { sessionID: CHILD },
1669 + time: { started: 1, completed: 2 },
1670 + };
1671 + const response = (data: unknown) => ({ location: { directory: WORK }, data });
1672 + const { runtime, thread } = yield* resumed(
1673 + [
1674 + ...(recoveredChild
1675 + ? [
1676 + out("session.get", { sessionID: CHILD }),
1677 + replyData("session.get", sessionInfo({ id: CHILD })),
1678 + out("permission.list", { sessionID: CHILD }),
1679 + replyData("permission.list", []),
1680 + out("session.form.list", { sessionID: CHILD }),
1681 + replyData("session.form.list", []),
1682 + out("shell.list", "<any>"),
1683 + reply("shell.list", response([shell])),
1684 + out("shell.get", { id: shell.id }),
1685 + reply("shell.get", response(shell)),
1686 + out("shell.output", { id: shell.id }),
1687 + reply(
1688 + "shell.output",
1689 + response({ output: "done", cursor: 4, size: 4, truncated: false }),
1690 + ),
1691 + out("session.update", { sessionID: CHILD, permissions: "<any>" }),
1692 + reply("session.update", null),
1693 + ]
1694 + : []),
1695 + ...launchedAndRunning,
1696 + // The parent turn ends, and the background child fails: it reports
1697 + // nothing back, so its call has to end with the failure.
1698 + event("session.execution.succeeded", { sessionID: SESSION }),
1699 + event("session.execution.failed", {
1700 + sessionID: CHILD,
1701 + error: { type: "provider.quota", message: "Rate limit exceeded." },
1702 + }),
1703 + ],
1704 + recoveredChild ? { version: "2.2.1" } : undefined,
1705 + );
1706 + if (recoveredChild)
1707 + yield* runtime.resumeThread({
1708 + providerThread: childProviderThread,
1709 + threadId: childThreadId,
1710 + modelSelection: bigPickle,
1711 + runtimePolicy: policy(),
1712 + });
1713 + const childUpdates: Array<
1714 + Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "provider_thread.updated" }>
1715 + > = [];
1716 + const watch = yield* watchCalls(
1717 + {
1718 + ...runtime,
1719 + events: runtime.events.pipe(
1720 + Stream.tap((event) =>
1721 + Effect.sync(() => {
1722 + if (
1723 + event.type === "provider_thread.updated" &&
1724 + event.providerThread.id === childProviderThread.id &&
1725 + event.providerThread.ownerNodeId !== null
1726 + )
1727 + childUpdates.push(event);
1728 + }),
1729 + ),
1730 + ),
1731 + },
1732 + thread,
1733 + );
1734 + yield* runtime.startTurn(withLineage(thread));
1735 + yield* watch.until(
1736 + () => watch.calls.get("Sleep")?.status === "failed" && watch.state.roster?.length === 0,
1737 + );
1738 + assert.includeMembers(
1739 + childUpdates.map((event) => event.providerThread.status),
1740 + ["active", "idle"],
1741 + );
1742 + assert.isFalse(
1743 + childUpdates.some((event) => event.sessionScoped === true),
1744 + "reattached child status must route through the parent run",
1745 + );
1746 + assert.deepEqual(watch.state.roster, []);
1747 + assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1748 + }).pipe(Effect.scoped),
1749 );
1750
1751 // regression: #21979 a failed background subagent pinned its thread as busy
@@ -2424,6 +2977,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2977 ...(delivery === "pending"
2978 ? [out("rpc.call", "<any>"), reply("rpc.call", { output: { unreadable: true } })]
2979 : []),
2980 + ...(delivery === "pending" ? emptyShellInventory : []),
2981 ...reconnect.slice(2),
2982 ...(delivery === "pending"
2983 ? [
@@ -3029,7 +3583,14 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3583 ],
3584 });
3585 if (source !== "history")
3032 - frames.splice(2, 0, out("rpc.call", "<any>"), reply("rpc.call", { output: null }));
3586 + frames.splice(
3587 + 2,
3588 + 0,
3589 + out("rpc.call", "<any>"),
3590 + reply("rpc.call", { output: null }),
3591 + out("job.list", { kind: "shell" }),
3592 + reply("job.list", { data: [] }),
3593 + );
3594 return frames;
3595 })(),
3596 out("message.list", { sessionID: SESSION, type: "synthetic", limit: "100" }),
@@ -5898,6 +6459,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6459 input: { sessionID: SESSION },
6460 }),
6461 reply("rpc.call", { output: nativeGoal("paused") }),
6462 + ...emptyShellInventory,
6463 ],
6464 { version: "2.2.5" },
6465 );
@@ -5942,6 +6504,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6504 ...recovered.slice(0, 2),
6505 out("rpc.call", "<any>"),
6506 reply("rpc.call", { output: nativeGoal("active") }),
6507 + ...emptyShellInventory,
6508 ...recovered.slice(2),
6509 ...noOpenRequests,
6510 ]
@@ -6073,6 +6636,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6636 ),
6637 ]
6638 : []),
6639 + ...emptyShellInventory,
6640 ...reconnect.slice(2),
6641 ],
6642 { version: "2.2.5", replayGate: gate },
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts
+11 -1
@@ -54,7 +54,7 @@ const operationOf = (
54 query: Record<string, unknown>,
55 body: unknown,
56 ) => {
57 - if (method === "GET" && path === "/api/experimental/job")
57 + if (method === "GET" && path === "/api/experimental/job" && query.kind === "image")
58 return { type: "imageJobs", input: query };
59 if (method === "GET" && path.startsWith("/api/fs/read/"))
60 return { type: "image.read", input: { path, ...query } };
@@ -64,6 +64,16 @@ const operationOf = (
64 type: "rpc.call",
65 input: { rpcID: rpc[1], method: rpc[2], ...query, ...(body as object) },
66 };
67 + if (method === "GET" && path === "/api/experimental/job")
68 + return { type: "job.list", input: query };
69 + const shell = /^\/api\/shell(?:\/([^/]+)(\/output)?)?$/.exec(path);
70 + if (shell !== null) {
71 + const input = { ...(shell[1] === undefined ? {} : { id: shell[1] }), ...query };
72 + return {
73 + type: `shell.${method === "DELETE" ? "remove" : shell[2] ? "output" : shell[1] ? "get" : "list"}`,
74 + input,
75 + };
76 + }
77 const session = /^\/api\/session\/([^/]+)(\/.*)?$/.exec(path);
78 if (method === "GET" && path === "/api/event") return { type: "event.subscribe" };
79 if (method === "GET" && path === "/api/model") return { type: "model.list", input: query };
apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+196 -80
@@ -3660,89 +3660,205 @@ it.effect(
3660 }),
3661 );
3662
3663 -it.effect("ProviderSessionManagerV2 persists session-scoped runtime requests without a run", () =>
3664 - Effect.gen(function* () {
3665 - const state = yield* Ref.make(emptyState);
3666 - const effect = Effect.gen(function* () {
3667 - const eventSink = yield* EventSink.EventSinkV2;
3668 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
3669 - const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
3670 - const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
3671 - const now = yield* DateTime.now;
3672 - const projectId = yield* idAllocator.allocate.project({
3673 - fixtureName: "provider-session-manager-session-request",
3674 - });
3675 - const threadId = yield* idAllocator.allocate.thread({
3676 - fixtureName: "provider-session-manager-session-request",
3677 - projectId,
3678 - });
3679 - const providerSessionId = yield* idAllocator.allocate.providerSession({
3680 - providerInstanceId: modelSelection.instanceId,
3681 - threadId,
3682 - });
3683 - const providerThread = makeProviderThread({
3684 - idAllocator,
3685 - threadId,
3686 - providerSessionId,
3687 - now,
3688 - });
3663 +it.effect(
3664 + "ProviderSessionManagerV2 persists session-scoped requests and recovered commands without a run",
3665 + () =>
3666 + Effect.gen(function* () {
3667 + const state = yield* Ref.make(emptyState);
3668 + const effect = Effect.gen(function* () {
3669 + const eventSink = yield* EventSink.EventSinkV2;
3670 + const idAllocator = yield* IdAllocator.IdAllocatorV2;
3671 + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
3672 + const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
3673 + const now = yield* DateTime.now;
3674 + const projectId = yield* idAllocator.allocate.project({
3675 + fixtureName: "provider-session-manager-session-request",
3676 + });
3677 + const threadId = yield* idAllocator.allocate.thread({
3678 + fixtureName: "provider-session-manager-session-request",
3679 + projectId,
3680 + });
3681 + const providerSessionId = yield* idAllocator.allocate.providerSession({
3682 + providerInstanceId: modelSelection.instanceId,
3683 + threadId,
3684 + });
3685 + const providerThread = makeProviderThread({
3686 + idAllocator,
3687 + threadId,
3688 + providerSessionId,
3689 + now,
3690 + });
3691
3690 - yield* eventSink.write({
3691 - events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
3692 - });
3693 - yield* manager.open({
3694 - threadId,
3695 - providerSessionId,
3696 - modelSelection,
3697 - runtimePolicy,
3698 - });
3699 - const pendingRequest = yield* makePendingRuntimeRequestEvents({
3700 - idAllocator,
3701 - threadId,
3702 - providerSessionId,
3703 - providerThread,
3704 - now,
3705 - });
3706 - const afterSequence = yield* eventSink.latestSequence({ threadId });
3707 - const persistedFiber = yield* eventSink.stream({ threadId, afterSequence }).pipe(
3708 - Stream.filter(
3709 - (stored) =>
3710 - stored.event.type === "runtime-request.updated" ||
3711 - stored.event.type === "node.updated" ||
3712 - stored.event.type === "turn-item.updated",
3713 - ),
3714 - Stream.take(3),
3715 - Stream.runCollect,
3716 - Effect.forkScoped,
3717 - );
3718 - const adapterEvents = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId));
3719 - assert.isDefined(adapterEvents);
3720 - yield* Queue.offerAll(adapterEvents!, pendingRequest.providerEvents);
3721 - const persisted = Array.from(yield* Fiber.join(persistedFiber));
3692 + const otherThreadId = yield* idAllocator.allocate.thread({
3693 + fixtureName: "unattached-shell-owner",
3694 + projectId,
3695 + });
3696 + yield* eventSink.write({
3697 + events: [
3698 + yield* makeThreadCreatedEvent({ idAllocator, threadId, now }),
3699 + yield* makeThreadCreatedEvent({ idAllocator, threadId: otherThreadId, now }),
3700 + ],
3701 + });
3702 + yield* manager.open({
3703 + threadId,
3704 + providerSessionId,
3705 + modelSelection,
3706 + runtimePolicy,
3707 + });
3708 + const pendingRequest = yield* makePendingRuntimeRequestEvents({
3709 + idAllocator,
3710 + threadId,
3711 + providerSessionId,
3712 + providerThread,
3713 + now,
3714 + });
3715 + const shellId = "sh_recovered";
3716 + const command = {
3717 + id: idAllocator.derive.turnItemFromProviderItem({
3718 + driver: CODEX_DRIVER,
3719 + nativeItemId: shellId,
3720 + }),
3721 + threadId,
3722 + runId: null,
3723 + nodeId: null,
3724 + providerThreadId: providerThread.id,
3725 + providerTurnId: null,
3726 + nativeItemRef: { driver: CODEX_DRIVER, nativeId: shellId, strength: "strong" as const },
3727 + parentItemId: null,
3728 + ordinal: 0,
3729 + status: "running" as const,
3730 + title: null,
3731 + startedAt: now,
3732 + completedAt: null,
3733 + updatedAt: now,
3734 + type: "command_execution" as const,
3735 + input: "echo retained",
3736 + output: "retained",
3737 + };
3738 + const anchored = {
3739 + ...command,
3740 + id: idAllocator.derive.turnItemFromProviderItem({
3741 + driver: CODEX_DRIVER,
3742 + nativeItemId: "sh_anchored",
3743 + }),
3744 + runId: idAllocator.derive.run({ threadId, ordinal: 1 }),
3745 + };
3746 + const commandEvents = [
3747 + {
3748 + type: "turn_item.updated" as const,
3749 + driver: CODEX_DRIVER,
3750 + turnItem: anchored,
3751 + sessionScoped: true,
3752 + },
3753 + {
3754 + type: "turn_item.updated" as const,
3755 + driver: CODEX_DRIVER,
3756 + turnItem: command,
3757 + sessionScoped: true,
3758 + },
3759 + {
3760 + type: "provider_thread.updated" as const,
3761 + driver: CODEX_DRIVER,
3762 + providerThread: {
3763 + ...providerThread,
3764 + pendingBackgroundTasks: [{ taskId: shellId, kind: "command" as const }],
3765 + },
3766 + sessionScoped: true,
3767 + },
3768 + {
3769 + type: "turn_item.updated" as const,
3770 + driver: CODEX_DRIVER,
3771 + sessionScoped: true,
3772 + turnItem: {
3773 + ...command,
3774 + status: "completed" as const,
3775 + output: "retained\nfinished",
3776 + completedAt: now,
3777 + },
3778 + },
3779 + {
3780 + type: "provider_thread.updated" as const,
3781 + driver: CODEX_DRIVER,
3782 + providerThread: { ...providerThread, pendingBackgroundTasks: [] },
3783 + sessionScoped: true,
3784 + },
3785 + ];
3786 + const afterSequence = yield* eventSink.latestSequence({ threadId });
3787 + const persistedFiber = yield* eventSink.stream({ threadId, afterSequence }).pipe(
3788 + Stream.filter(
3789 + (stored) =>
3790 + stored.event.type === "runtime-request.updated" ||
3791 + stored.event.type === "node.updated" ||
3792 + (stored.event.type === "turn-item.updated" &&
3793 + stored.event.payload.type === "approval_request"),
3794 + ),
3795 + Stream.take(3),
3796 + Stream.runCollect,
3797 + Effect.forkScoped,
3798 + );
3799 + const adapterEvents = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId));
3800 + assert.isDefined(adapterEvents);
3801 + yield* Queue.offerAll(adapterEvents!, [
3802 + ...commandEvents,
3803 + {
3804 + type: "turn_item.updated",
3805 + driver: CODEX_DRIVER,
3806 + sessionScoped: true,
3807 + turnItem: { ...command, threadId: otherThreadId },
3808 + },
3809 + {
3810 + type: "provider_thread.updated",
3811 + driver: CODEX_DRIVER,
3812 + providerThread: { ...providerThread, appThreadId: otherThreadId },
3813 + sessionScoped: true,
3814 + },
3815 + ...pendingRequest.providerEvents,
3816 + ]);
3817 + const persisted = Array.from(yield* Fiber.join(persistedFiber));
3818
3723 - assert.sameMembers(
3724 - persisted.map((stored) => stored.event.type),
3725 - ["runtime-request.updated", "node.updated", "turn-item.updated"],
3726 - );
3727 - const projection = yield* projectionStore.getThreadProjection(threadId);
3728 - const request = projection.runtimeRequests.find(
3729 - (candidate) => candidate.id === pendingRequest.requestId,
3730 - );
3731 - const node = projection.nodes.find((candidate) => candidate.id === pendingRequest.nodeId);
3732 - const turnItem = projection.turnItems.find(
3733 - (candidate) =>
3734 - candidate.type === "approval_request" && candidate.requestId === pendingRequest.requestId,
3735 - );
3736 - assert.equal(request?.status, "pending");
3737 - assert.equal(request?.providerTurnId, null);
3738 - assert.equal(node?.runId, null);
3739 - assert.equal(node?.status, "waiting");
3740 - assert.equal(turnItem?.runId, null);
3741 - assert.equal(turnItem?.status, "waiting");
3742 - });
3819 + assert.sameMembers(
3820 + persisted.map((stored) => stored.event.type),
3821 + ["runtime-request.updated", "node.updated", "turn-item.updated"],
3822 + );
3823 + const projection = yield* projectionStore.getThreadProjection(threadId);
3824 + const request = projection.runtimeRequests.find(
3825 + (candidate) => candidate.id === pendingRequest.requestId,
3826 + );
3827 + const node = projection.nodes.find((candidate) => candidate.id === pendingRequest.nodeId);
3828 + const turnItem = projection.turnItems.find(
3829 + (candidate) =>
3830 + candidate.type === "approval_request" &&
3831 + candidate.requestId === pendingRequest.requestId,
3832 + );
3833 + const recovered = projection.turnItems.find((item) => item.id === command.id);
3834 + assert.deepInclude(recovered, {
3835 + runId: null,
3836 + status: "completed",
3837 + output: "retained\nfinished",
3838 + });
3839 + assert.deepEqual(
3840 + projection.providerThreads.find((item) => item.id === providerThread.id)
3841 + ?.pendingBackgroundTasks,
3842 + [],
3843 + );
3844 + assert.deepInclude(
3845 + projection.turnItems.find((item) => item.id === anchored.id),
3846 + { runId: anchored.runId, output: "retained" },
3847 + );
3848 + assert.isEmpty(projection.runs);
3849 + const unrelated = yield* projectionStore.getThreadProjection(otherThreadId);
3850 + assert.isEmpty(unrelated.turnItems);
3851 + assert.isEmpty(unrelated.providerThreads);
3852 + assert.equal(request?.status, "pending");
3853 + assert.equal(request?.providerTurnId, null);
3854 + assert.equal(node?.runId, null);
3855 + assert.equal(node?.status, "waiting");
3856 + assert.equal(turnItem?.runId, null);
3857 + assert.equal(turnItem?.status, "waiting");
3858 + });
3859
3744 - yield* effect.pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1000 })));
3745 - }),
3860 + yield* effect.pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1000 })));
3861 + }),
3862 );
3863
3864 it.effect(
apps/server/src/orchestration-v2/ProviderSessionManager.ts
+18 -7
@@ -281,10 +281,14 @@ function sessionKey(providerSessionId: ProviderSessionId): string {
281 return String(providerSessionId);
282 }
283
284 -function sessionScopedRuntimeRequestThreadId(
284 +function sessionScopedArtifactThreadId(
285 event: ProviderAdapter.ProviderAdapterV2Event,
286 ): ThreadId | undefined {
287 switch (event.type) {
288 + case "provider_thread.updated":
289 + return event.sessionScoped === true
290 + ? (event.providerThread.appThreadId ?? undefined)
291 + : undefined;
292 case "runtime_request.updated":
293 return event.runtimeRequest.providerTurnId === null ? event.threadId : undefined;
294 case "node.updated":
@@ -292,6 +296,8 @@ function sessionScopedRuntimeRequestThreadId(
296 ? event.node.threadId
297 : undefined;
298 case "turn_item.updated":
299 + if (event.turnItem.type === "command_execution")
300 + return event.sessionScoped === true ? event.turnItem.threadId : undefined;
301 return event.turnItem.runId === null &&
302 (event.turnItem.type === "approval_request" || event.turnItem.type === "user_input_request")
303 ? event.turnItem.threadId
@@ -2274,17 +2280,21 @@ export const layerWithOptions = (
2280 });
2281 });
2282 }
2277 - // Some providers can block before a run subscriber exists
2278 - // (project trust, login, or session-switch hooks). Persist
2279 - // their runless request artifacts directly so the normal T3
2280 - // request UI can answer them and unblock session setup.
2281 - const threadId = sessionScopedRuntimeRequestThreadId(event);
2283 + // Requests and recovered background commands can arrive before a run subscribes.
2284 + const threadId = sessionScopedArtifactThreadId(event);
2285 if (threadId !== undefined) {
2286 yield* Effect.gen(function* () {
2287 const current = (yield* Ref.get(sessions)).get(
2288 sessionKey(entry.runtime.providerSessionId),
2289 );
2287 - if (current?.runtime !== entry.runtime) return;
2290 + if (
2291 + current?.runtime !== entry.runtime ||
2292 + ((event.type === "provider_thread.updated" ||
2293 + (event.type === "turn_item.updated" &&
2294 + event.turnItem.type === "command_execution")) &&
2295 + !current.attachedThreadIds.has(threadId))
2296 + )
2297 + return;
2298 yield* providerEventIngestor
2299 .ingestNormalized({
2300 providerSessionId: entry.runtime.providerSessionId,
@@ -2303,6 +2313,7 @@ export const layerWithOptions = (
2313 ),
2314 );
2315 }).pipe(entry.requestEventPermit.withPermits(1));
2316 + yield* releaseLiveOutput;
2317 return;
2318 }
2319 yield* publishToSubscribers(entry.eventSubscribers, { type: "event", event });
packages/provider-core/src/server/ProviderAdapter.ts
+4
@@ -98,6 +98,8 @@ export const ProviderAdapterV2Event = Schema.Union([
98 providerThread: OrchestrationV2ProviderThread,
99 /** Work remaining at this point in the event stream, including native continuations. */
100 pendingBackgroundWork: Schema.optional(Schema.Boolean),
101 + /** Persist idle background snapshots before a run subscriber exists. */
102 + sessionScoped: Schema.optional(Schema.Boolean),
103 retainedNativeTurnIds: Schema.optional(Schema.Array(Schema.String)),
104 }),
105 Schema.Struct({
@@ -125,6 +127,8 @@ export const ProviderAdapterV2Event = Schema.Union([
127 type: Schema.Literal("turn_item.updated"),
128 driver: ProviderDriverKind,
129 turnItem: OrchestrationV2TurnItem,
130 + /** Persist recovered activity independently of a run subscription. */
131 + sessionScoped: Schema.optional(Schema.Boolean),
132 }),
133 /** A steer the provider queued stays `pending` until the agent reads it; `cancelled` if dropped unread. */
134 Schema.Struct({
packages/provider-opencode/src/server/v2/OpenCode2Client.ts
+24
@@ -52,6 +52,17 @@ export type OpenCode2StreamEvent =
52 | OpenCode2UnreadableTerminal
53 | OpenCode2UnreadableStart;
54
55 +const ShellJobs = Schema.Struct({
56 + data: Schema.Array(
57 + Schema.Struct({
58 + kind: Schema.Literal("shell"),
59 + shellID: Schema.String,
60 + sessionID: Schema.String,
61 + command: Schema.String,
62 + status: Schema.Literals(["running", "completed", "error", "cancelled"]),
63 + }),
64 + ),
65 +});
66 export class OpenCode2ImageError extends Schema.TaggedError<OpenCode2ImageError>()(
67 "OpenCode2ImageError",
68 { cause: Schema.Defect() },
@@ -82,6 +93,9 @@ const decodeImageJob = Schema.decodeUnknownOption(NativeImageJob);
93 /** events resolves on subscription acceptance; subscribe before work because the stream is volatile. */
94 export interface OpenCode2Api {
95 readonly client: OpenCodeClient;
96 + readonly shellJobs?: (
97 + sessionID: string,
98 + ) => Effect.Effect<typeof ShellJobs.Type, HttpClientError.HttpClientError | Schema.SchemaError>;
99 readonly imageJobs: (
100 sessionID: string,
101 ) => Effect.Effect<ReadonlyArray<typeof NativeImageJob.Type>, OpenCode2ImageError>;
@@ -249,6 +263,16 @@ export const make = Effect.gen(function* () {
263 Effect.provideService(HttpClient.HttpClient, fillCompactionRecents(authenticated)),
264 Effect.map((client) => ({
265 client,
266 + shellJobs: Effect.fn("OpenCode2Client.shellJobs")(function (sessionID: string) {
267 + return authenticated
268 + .get(`${baseUrl}/api/experimental/job`, {
269 + urlParams: { sessionID, kind: "shell", descendants: "true" },
270 + })
271 + .pipe(
272 + Effect.flatMap(HttpClientResponse.filterStatusOk),
273 + Effect.flatMap(HttpClientResponse.schemaBodyJson(ShellJobs)),
274 + );
275 + }),
276 imageJobs: (sessionID: string) =>
277 authenticated
278 .get(`${baseUrl}/api/experimental/job`, {
packages/provider-opencode/src/server/v2/adapter.ts
+473 -13
@@ -15,6 +15,7 @@ import {
15 Skill,
16 type OpenCodeEvent,
17 } from "@opencode/client/effect";
18 +import * as Shell from "@opencode/schema/shell";
19 import { Mcp } from "@opencode/schema/mcp";
20 import {
21 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
@@ -307,6 +308,7 @@ interface ThreadState {
308 readonly sessionId: string;
309 providerThread: OrchestrationV2ProviderThread;
310 publishedBackgroundWork?: boolean;
311 + sessionScopedBackground?: boolean;
312 readonly imageJobs: Map<
313 string,
314 {
@@ -889,7 +891,27 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
891 return state.active === undefined ? undefined : { state, turn: state.active };
892 };
893
894 + const shellInfo = new Map<string, Shell.Info>();
895 + const shells = new Map<
896 + string,
897 + {
898 + state: ThreadState;
899 + turn?: ActiveTurn;
900 + toolId?: string;
901 + tool?: { name: string; input: Record<string, unknown> };
902 + command: string;
903 + running: boolean;
904 + stopping?: boolean;
905 + output: string;
906 + cursor: number;
907 + startedAt?: DateTime.Utc;
908 + recoveredRunId?: RunId | null;
909 + published?: boolean;
910 + }
911 + >();
912 +
913 const owesWork = (state: ThreadState) =>
914 + [...shells.values()].some((shell) => shell.state === state && shell.running) ||
915 [...state.imageJobs.values()].some((job) => job.status === "running") ||
916 state.wakes.length > 0 ||
917 state.reports.size > 0 ||
@@ -906,6 +928,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
928 driver,
929 providerThread: state.providerThread,
930 pendingBackgroundWork,
931 + ...(state.sessionScopedBackground === true ? { sessionScoped: true } : {}),
932 });
933 });
934
@@ -1161,6 +1184,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1184 status: "running" | "completed" | "failed" | "interrupted",
1185 result?: {
1186 readonly output: string | undefined;
1187 + readonly nativeTaskId?: string;
1188 readonly metadata: unknown;
1189 readonly files?: ReadonlyArray<{ readonly uri: string; readonly mime: string }>;
1190 },
@@ -1220,13 +1244,21 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1244 type: "turn_item.updated",
1245 driver,
1246 turnItem: openCodeToolTurnItem(
1223 - itemBase(state, turn, nativeId, settled, startedAt, completedAt, updatedAt),
1247 + {
1248 + ...itemBase(state, turn, nativeId, settled, startedAt, completedAt, updatedAt),
1249 + ...(result?.nativeTaskId === undefined
1250 + ? {}
1251 + : { nativeItemRef: ref(result.nativeTaskId) }),
1252 + },
1253 {
1254 name: tool.name,
1255 input: tool.input,
1256 output: result?.output,
1257 files: result?.files,
1229 - completedMetadata: status === "completed" ? result?.metadata : undefined,
1258 + completedMetadata:
1259 + status === "completed" || result?.nativeTaskId !== undefined
1260 + ? result?.metadata
1261 + : undefined,
1262 },
1263 ),
1264 });
@@ -1461,16 +1493,29 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1493 });
1494
1495 const syncRoster = Effect.fnUntraced(function* (state: ThreadState) {
1464 - const roster = runningCalls(state)
1465 - .filter((call) => call.background)
1466 - .map((call) => ({
1467 - taskId: call.nativeId,
1468 - kind: "subagent" as const,
1469 - ...(call.title?.trim() ? { description: call.title.trim() } : {}),
1470 - ...(call.child?.subagent === undefined
1471 - ? {}
1472 - : { childThreadId: call.child.subagent.appThread.id }),
1473 - }));
1496 + const roster: Array<import("@t3tools/contracts").OrchestrationV2PendingBackgroundTask> =
1497 + runningCalls(state)
1498 + .filter((call) => call.background)
1499 + .map((call) => ({
1500 + taskId: call.nativeId,
1501 + kind: "subagent" as const,
1502 + ...(call.title?.trim() ? { description: call.title.trim() } : {}),
1503 + ...(call.child?.subagent === undefined
1504 + ? {}
1505 + : { childThreadId: call.child.subagent.appThread.id }),
1506 + }));
1507 + for (const [taskId, shell] of shells) {
1508 + if (shell.running && sessionsOf(state).includes(shell.state)) {
1509 + roster.push({
1510 + taskId,
1511 + kind: "command",
1512 + description: shell.command,
1513 + ...(shell.state.subagent === undefined
1514 + ? {}
1515 + : { parentTaskId: shell.state.subagent.call.nativeId }),
1516 + });
1517 + }
1518 + }
1519 const imageTasks = sessionsOf(state).flatMap((session) =>
1520 [...session.imageJobs.entries()].flatMap(([taskId, job]) =>
1521 job.status === "running"
@@ -1494,7 +1539,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1539 task.taskId === allTasks[index]?.taskId &&
1540 task.description === allTasks[index]?.description &&
1541 (task.kind === "subagent" ? task.childThreadId : undefined) ===
1497 - roster[index]?.childThreadId,
1542 + (allTasks[index]?.kind === "subagent" ? allTasks[index]?.childThreadId : undefined),
1543 )
1544 ) {
1545 return;
@@ -1515,6 +1560,242 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1560 }
1561 });
1562
1563 + const fetchShellOutput = Effect.fn("OpenCode2Adapter.fetchShellOutput")(function* (
1564 + id: string,
1565 + snapshot: { directory: string; cursor: number; output: string },
1566 + settled = false,
1567 + ) {
1568 + let { cursor, output } = snapshot;
1569 + // Bound each read and retained UI text; the native byte cursor must never use JS string lengths.
1570 + for (let page = 0; page < (settled ? 5 : 4); page++) {
1571 + const { data } = yield* client.shell.output({
1572 + id: Shell.ID.make(id),
1573 + location: { directory: snapshot.directory },
1574 + cursor,
1575 + limit: 65536,
1576 + });
1577 + output = (output + data.output).slice(-262144);
1578 + const previous = cursor;
1579 + cursor = data.cursor;
1580 + if (data.cursor >= data.size || data.cursor <= previous) break;
1581 + if (settled && data.size - data.cursor > 262144) {
1582 + cursor = data.size - 262144;
1583 + output = "";
1584 + }
1585 + }
1586 + return { cursor, output };
1587 + }, Effect.timeout(INVENTORY_TIMEOUT));
1588 +
1589 + const readShellOutput = Effect.fn("OpenCode2Adapter.readShellOutput")(function* (
1590 + id: string,
1591 + settled = false,
1592 + ) {
1593 + const shell = shells.get(id);
1594 + if (shell === undefined) return;
1595 + const output = yield* fetchShellOutput(
1596 + id,
1597 + {
1598 + directory: shell.state.directory,
1599 + cursor: shell.cursor,
1600 + output: shell.output,
1601 + },
1602 + settled,
1603 + );
1604 + Object.assign(shell, output);
1605 + });
1606 +
1607 + const emitShell = Effect.fnUntraced(function* (
1608 + id: string,
1609 + status: "running" | "completed" | "failed" | "interrupted",
1610 + exit?: number,
1611 + ) {
1612 + const shell = shells.get(id);
1613 + if (shell === undefined) return;
1614 + if (shell.turn === undefined || shell.toolId === undefined || shell.tool === undefined) {
1615 + const updatedAt = yield* DateTime.now;
1616 + yield* emit({
1617 + type: "turn_item.updated",
1618 + driver,
1619 + sessionScoped: true,
1620 + turnItem: {
1621 + id: idAllocator.derive.turnItemFromProviderItem({ driver, nativeItemId: id }),
1622 + threadId: shell.state.providerThread.appThreadId ?? input.threadId,
1623 + runId: shell.recoveredRunId ?? null,
1624 + nodeId: null,
1625 + providerThreadId: shell.state.providerThread.id,
1626 + providerTurnId: null,
1627 + nativeItemRef: ref(id),
1628 + parentItemId: null,
1629 + ordinal: 0,
1630 + status,
1631 + title: null,
1632 + startedAt: shell.startedAt ?? updatedAt,
1633 + completedAt: status === "running" ? null : updatedAt,
1634 + updatedAt,
1635 + type: "command_execution",
1636 + input: shell.command,
1637 + output: shell.output,
1638 + ...(exit === undefined ? {} : { exitCode: exit }),
1639 + },
1640 + });
1641 + shell.published = true;
1642 + return;
1643 + }
1644 + shell.turn.tools.set(shell.toolId, shell.tool);
1645 + yield* emitTool(shell.state, shell.turn, shell.toolId, status, {
1646 + output: shell.output,
1647 + nativeTaskId: id,
1648 + metadata: { shellID: id, exit },
1649 + });
1650 + shell.turn.tools.delete(shell.toolId);
1651 + shell.published = true;
1652 + });
1653 +
1654 + const stopShell = Effect.fn("OpenCode2Adapter.stopShell")(function* (id: string) {
1655 + const shell = shells.get(id);
1656 + if (shell === undefined || !shell.running) return;
1657 + yield* readShellOutput(id, true).pipe(Effect.ignore({ log: true }));
1658 + shell.stopping = true;
1659 + yield* client.shell
1660 + .remove({
1661 + id: Shell.ID.make(id),
1662 + location: { directory: shell.state.directory },
1663 + })
1664 + .pipe(
1665 + Effect.timeout(INVENTORY_TIMEOUT),
1666 + Effect.onError(() =>
1667 + Effect.sync(() => {
1668 + shell.stopping = false;
1669 + }),
1670 + ),
1671 + );
1672 + shell.stopping = false;
1673 + shell.running = false;
1674 + shell.state.stoppedChildren.add(id);
1675 + yield* emitShell(id, "interrupted");
1676 + shells.delete(id);
1677 + shellInfo.delete(id);
1678 + yield* syncRosterAncestors(shell.state);
1679 + });
1680 +
1681 + const recoverShells = Effect.fn("OpenCode2Adapter.recoverShells")(
1682 + function* (state: ThreadState) {
1683 + if (compareSemverVersions(connection.version, "2.2.1") < 0) return;
1684 + const jobs =
1685 + compareSemverVersions(connection.version, "2.2.6") >= 0 &&
1686 + connection.shellJobs !== undefined
1687 + ? yield* connection.shellJobs(state.sessionId).pipe(Effect.option)
1688 + : undefined;
1689 + const data =
1690 + jobs?._tag === "Some"
1691 + ? jobs.value.data.map((job) => ({
1692 + id: Shell.ID.make(job.shellID),
1693 + command: job.command,
1694 + metadata: { sessionID: job.sessionID },
1695 + }))
1696 + : (yield* client.shell.list({ location: { directory: state.directory } })).data;
1697 + for (const info of data) {
1698 + const sessionId = stringField(info.metadata, "sessionID");
1699 + const owner =
1700 + sessionId === undefined
1701 + ? undefined
1702 + : (threads.get(sessionId) ??
1703 + ownerOf(sessionId) ??
1704 + (jobs?._tag === "Some" ? state : undefined));
1705 + if (owner === undefined || !sessionsOf(state).includes(owner)) continue;
1706 + if (!shells.has(info.id)) {
1707 + if (state.active === undefined && !hasBackground(state)) {
1708 + state.sessionScopedBackground = true;
1709 + delete state.publishedBackgroundWork;
1710 + }
1711 + const target = requestTurn(owner.sessionId);
1712 + shells.set(info.id, {
1713 + state: owner,
1714 + ...(target === undefined
1715 + ? {
1716 + recoveredRunId:
1717 + owner.providerThread.lastRunOrdinal === null
1718 + ? null
1719 + : idAllocator.derive.run({
1720 + threadId: owner.providerThread.appThreadId ?? input.threadId,
1721 + ordinal: owner.providerThread.lastRunOrdinal,
1722 + }),
1723 + }
1724 + : {
1725 + turn: target.turn,
1726 + toolId: info.id,
1727 + tool: { name: "shell", input: { command: info.command } },
1728 + }),
1729 + command: info.command,
1730 + running: true,
1731 + output: "",
1732 + cursor: 0,
1733 + });
1734 + }
1735 + }
1736 + for (const [id, shell] of shells) {
1737 + if (!shell.running || !sessionsOf(state).includes(shell.state)) continue;
1738 + yield* Effect.gen(function* () {
1739 + const found = yield* client.shell
1740 + .get({ id: Shell.ID.make(id), location: { directory: shell.state.directory } })
1741 + .pipe(
1742 + Effect.timeout(INVENTORY_TIMEOUT),
1743 + Effect.catchTags({ ShellNotFoundError: () => Effect.undefined }),
1744 + );
1745 + if (found === undefined) {
1746 + shell.running = false;
1747 + yield* emitShell(id, "interrupted");
1748 + shells.delete(id);
1749 + return;
1750 + }
1751 + const info = found.data;
1752 + shell.startedAt = DateTime.makeUnsafe(info.time.started);
1753 + yield* readShellOutput(id, info.status !== "running").pipe(
1754 + Effect.ignore({ log: true }),
1755 + );
1756 + shell.running = info.status === "running";
1757 + yield* emitShell(
1758 + id,
1759 + shell.running
1760 + ? "running"
1761 + : info.status === "killed"
1762 + ? "interrupted"
1763 + : info.exit === 0
1764 + ? "completed"
1765 + : "failed",
1766 + info.exit,
1767 + );
1768 + if (!shell.running) shells.delete(id);
1769 + }).pipe(
1770 + Effect.catch((cause) =>
1771 + Effect.logWarning("Could not recover an OpenCode shell.", cause).pipe(
1772 + Effect.andThen(emitShell(id, "running")),
1773 + ),
1774 + ),
1775 + );
1776 + }
1777 + },
1778 + (effect, state) =>
1779 + lock.withPermit(
1780 + effect.pipe(
1781 + Effect.timeout(INVENTORY_TIMEOUT),
1782 + Effect.ensuring(
1783 + Effect.gen(function* () {
1784 + for (const [id, shell] of shells) {
1785 + if (
1786 + shell.running &&
1787 + shell.published !== true &&
1788 + sessionsOf(state).includes(shell.state)
1789 + )
1790 + yield* emitShell(id, "running");
1791 + }
1792 + yield* syncRosterAncestors(state);
1793 + }),
1794 + ),
1795 + ),
1796 + ),
1797 + );
1798 +
1799 const withReportedModel = (
1800 providerThread: OrchestrationV2ProviderThread,
1801 model: ModelRef | undefined,
@@ -1613,6 +1894,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1894 const child =
1895 previous ?? newThreadState(childId, providerThread, call.state.directory, subagent);
1896 child.subagent = subagent;
1897 + child.sessionScopedBackground = false;
1898 child.model = info?.model ?? child.model;
1899 child.providerThread = withReportedModel(providerThread, child.model);
1900 child.directory = call.state.directory;
@@ -1652,6 +1934,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1934 if (child.active !== undefined && status !== "completed") {
1935 yield* finishTurn(child, { status: "interrupted" });
1936 }
1937 + child.sessionScopedBackground = false;
1938 child.providerThread = {
1939 ...child.providerThread,
1940 status: "idle",
@@ -1699,6 +1982,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1982 turn.before = subagent.queued;
1983 subagent.queued = undefined;
1984 child.active = turn;
1985 + child.sessionScopedBackground = false;
1986 yield* emit({
1987 type: "node.updated",
1988 driver,
@@ -2322,6 +2606,44 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2606 }
2607 return yield* settleCall(call, "completed", subagentOutput(textOf(event.data.content)));
2608 }
2609 + const shellId = stringField(event.data.metadata, "shellID");
2610 + const tool = turn.tools.get(event.data.id);
2611 + if (
2612 + shellId !== undefined &&
2613 + tool?.name === "shell" &&
2614 + event.data.metadata?.["exit"] === undefined &&
2615 + event.data.metadata?.["signal"] === undefined &&
2616 + event.data.metadata?.["timeout"] !== true
2617 + ) {
2618 + shells.set(shellId, {
2619 + state,
2620 + turn,
2621 + toolId: event.data.id,
2622 + tool,
2623 + command: stringField(tool.input, "command") ?? "Shell command",
2624 + running: true,
2625 + output: "",
2626 + cursor: 0,
2627 + });
2628 + yield* readShellOutput(shellId).pipe(Effect.ignore({ log: true }));
2629 + const known = shellInfo.get(shellId);
2630 + const tracked = shells.get(shellId)!;
2631 + tracked.running = known === undefined || known.status === "running";
2632 + yield* emitShell(
2633 + shellId,
2634 + tracked.running
2635 + ? "running"
2636 + : known?.status === "killed"
2637 + ? "interrupted"
2638 + : known?.exit === 0
2639 + ? "completed"
2640 + : "failed",
2641 + known?.exit,
2642 + );
2643 + yield* syncRosterAncestors(state);
2644 + return;
2645 + }
2646 + if (shellId !== undefined) shellInfo.delete(shellId);
2647 const output = textOf(event.data.content);
2648 yield* emitTool(state, turn, event.data.id, "completed", {
2649 output,
@@ -2540,9 +2862,43 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2862 inboxId: string,
2863 payload: {
2864 readonly text: string;
2865 + readonly description?: string | undefined;
2866 readonly metadata?: Readonly<Record<string, unknown>> | undefined;
2867 },
2868 ) {
2869 + if (stringField(payload.metadata, "source") === "shell") {
2870 + const id = stringField(payload.metadata, "shellID");
2871 + const shell = id === undefined ? undefined : shells.get(id);
2872 + if (shell !== undefined && shell.state !== state) return;
2873 + state.reports.set(inboxId, {
2874 + inboxId,
2875 + childId: id ?? inboxId,
2876 + text: payload.text,
2877 + report: {
2878 + kind: "command",
2879 + label: shell?.command ?? payload.description,
2880 + outcome: reportOutcome(stringField(payload.metadata, "state")),
2881 + },
2882 + });
2883 + if (id !== undefined && shell?.stopping !== true) {
2884 + if (shell?.running === true && shell.state === state) {
2885 + yield* readShellOutput(id, true).pipe(Effect.ignore({ log: true }));
2886 + shell.running = false;
2887 + const outcome = reportOutcome(stringField(payload.metadata, "state"));
2888 + yield* emitShell(
2889 + id,
2890 + outcome === "failed"
2891 + ? "failed"
2892 + : outcome === "cancelled"
2893 + ? "interrupted"
2894 + : "completed",
2895 + );
2896 + }
2897 + shells.delete(id);
2898 + shellInfo.delete(id);
2899 + }
2900 + return;
2901 + }
2902 if (stringField(payload.metadata, "source") === "experimental_image_generate") {
2903 return yield* imageReport(state, payload);
2904 }
@@ -2606,6 +2962,41 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2962 : Effect.void;
2963
2964 const handleEvent = Effect.fnUntraced(function* (event: OpenCode2Client.OpenCode2StreamEvent) {
2965 + if (event.type === "shell.created") {
2966 + const sessionId = stringField(event.data.info.metadata, "sessionID");
2967 + if (sessionId !== undefined && ownerOf(sessionId) !== undefined) {
2968 + shellInfo.set(event.data.info.id, event.data.info);
2969 + if (shellInfo.size > 128) shellInfo.delete(shellInfo.keys().next().value!);
2970 + }
2971 + return;
2972 + }
2973 + if (event.type === "shell.exited" || event.type === "shell.deleted") {
2974 + const known = shellInfo.get(event.data.id);
2975 + if (known !== undefined)
2976 + shellInfo.set(event.data.id, {
2977 + ...known,
2978 + status: event.type === "shell.deleted" ? "killed" : event.data.status,
2979 + exit: "exit" in event.data ? event.data.exit : undefined,
2980 + });
2981 + const shell = shells.get(event.data.id);
2982 + if (shell === undefined || !shell.running || shell.stopping === true) return;
2983 + if (event.type === "shell.exited")
2984 + yield* readShellOutput(event.data.id, true).pipe(Effect.ignore({ log: true }));
2985 + shell.running = false;
2986 + yield* emitShell(
2987 + event.data.id,
2988 + event.type === "shell.deleted" || event.data.status === "killed"
2989 + ? "interrupted"
2990 + : event.data.exit === 0
2991 + ? "completed"
2992 + : "failed",
2993 + "exit" in event.data ? event.data.exit : undefined,
2994 + );
2995 + shells.delete(event.data.id);
2996 + shellInfo.delete(event.data.id);
2997 + yield* syncRosterAncestors(shell.state);
2998 + return;
2999 + }
3000 const sessionId = sessionOfEvent(event);
3001 const cleared = sessionId === undefined ? undefined : clearing.get(sessionId);
3002 if (cleared !== undefined) {
@@ -3104,6 +3495,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3495 { concurrency: 4, discard: true },
3496 ).pipe(Effect.timeout(INVENTORY_TIMEOUT), Effect.ignore({ log: true }));
3497 }
3498 + for (const state of threads.values()) {
3499 + yield* recoverShells(state).pipe(Effect.ignore({ log: true }));
3500 + }
3501 yield* lock.withPermit(reconcile()).pipe(Effect.timeout(RECONCILE_TIMEOUT));
3502 return stream;
3503 }).pipe(
@@ -3165,6 +3559,47 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3559 // Subscribed before any session or prompt call, so no event of theirs is missed.
3560 yield* follow(yield* connection.events).pipe(Effect.forkScoped);
3561
3562 + yield* Effect.gen(function* () {
3563 + const snapshots = yield* lock.withPermit(
3564 + Effect.sync(() =>
3565 + [...shells]
3566 + .filter(([, shell]) => shell.running)
3567 + .map(([id, shell]) => ({
3568 + id,
3569 + shell,
3570 + cursor: shell.cursor,
3571 + output: shell.output,
3572 + directory: shell.state.directory,
3573 + })),
3574 + ),
3575 + );
3576 + yield* Effect.forEach(
3577 + snapshots,
3578 + (snapshot) =>
3579 + fetchShellOutput(snapshot.id, snapshot).pipe(
3580 + Effect.flatMap((next) =>
3581 + lock.withPermit(
3582 + Effect.gen(function* () {
3583 + const shell = shells.get(snapshot.id);
3584 + // An exit, Stop, or recovery may have consumed this cursor while the request was in flight.
3585 + if (
3586 + shell !== snapshot.shell ||
3587 + !shell.running ||
3588 + shell.cursor !== snapshot.cursor
3589 + )
3590 + return;
3591 + if (next.cursor <= shell.cursor) return;
3592 + Object.assign(shell, next);
3593 + yield* emitShell(snapshot.id, "running");
3594 + }),
3595 + ),
3596 + ),
3597 + Effect.ignore({ log: true }),
3598 + ),
3599 + { concurrency: 4, discard: true },
3600 + );
3601 + }).pipe(Effect.repeat(Schedule.spaced("2 seconds")), Effect.forkScoped);
3602 +
3603 // External servers outlive T3; stop their turns before losing observation.
3604 if (connection.external) {
3605 yield* Effect.addFinalizer(() =>
@@ -3605,6 +4040,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
4040 });
4041 }
4042 state.active = turn;
4043 + state.sessionScopedBackground = false;
4044 yield* emitProviderTurn(state, turn, providerTurn);
4045 state.providerThread = {
4046 ...state.providerThread,
@@ -3703,6 +4139,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
4139 });
4140
4141 const stopBackground = Effect.fnUntraced(function* (state: ThreadState) {
4142 + for (const [id, shell] of shells) {
4143 + if (shell.running && sessionsOf(state).includes(shell.state))
4144 + yield* lock.withPermit(stopShell(id)).pipe(Effect.ignore({ log: true }));
4145 + }
4146 const calls = runningCalls(state).filter((call) => call.background);
4147 const callers = sessionsOf(state);
4148 // Ended subagent calls can run again to answer their own background reports.
@@ -3984,6 +4424,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
4424 Effect.ignore({ log: true }),
4425 );
4426 }
4427 + if (!loaded) yield* recoverShells(state).pipe(Effect.ignore({ log: true }));
4428 yield* writeRules(state, threadInput.runtimePolicy ?? state.policy);
4429 if (cwd != null && native.location.directory !== cwd) {
4430 yield* client.session.move({
@@ -4312,6 +4753,25 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
4753 ),
4754 ),
4755 ),
4756 + stopTask: Effect.fn("OpenCode2Adapter.stopTask")(function* ({ providerThread, taskId }) {
4757 + const shell = shells.get(taskId);
4758 + const state =
4759 + providerThread.nativeThreadRef == null
4760 + ? undefined
4761 + : threads.get(providerThread.nativeThreadRef.nativeId ?? "");
4762 + if (state === undefined || shell === undefined || !sessionsOf(state).includes(shell.state))
4763 + return;
4764 + yield* lock.withPermit(stopShell(taskId)).pipe(
4765 + Effect.mapError(
4766 + (cause) =>
4767 + new ProviderAdapter.ProviderAdapterProtocolError({
4768 + driver,
4769 + detail: "Could not stop the OpenCode shell.",
4770 + cause,
4771 + }),
4772 + ),
4773 + );
4774 + }),
4775 unloadThread: Effect.fn("OpenCode2Adapter.unloadThread")(function* ({ providerThread }) {
4776 const nativeId = providerThread.nativeThreadRef?.nativeId;
4777 const state = nativeId == null ? undefined : threads.get(nativeId);