33import { ensurePluginRuntime } from "@opencode/plugin/runtime"
44import { NodeRuntime , NodeServices } from "@effect/platform-node"
55import { Cause , Effect } from "effect"
6- import { getErrorReported } from "effect/Runtime"
6+ import { defaultTeardown , getErrorReported } from "effect/Runtime"
77import { Commands } from "./commands/commands"
88import { Runtime } from "./framework/runtime"
99import { Observability } from "@opencode/util/observability"
@@ -39,6 +39,8 @@ if (process.env.OPENCODE_SSH_ASKPASS_PORT) {
3939 process . exit ( await Effect . runPromise ( askpass . pipe ( Effect . provide ( NodeServices . layer ) ) ) )
4040}
4141
42+ let terminated = false
43+
4244const Handlers = Runtime . handlers ( Commands , {
4345 $ : ( ) => import ( "./commands/handlers/default" ) ,
4446 upgrade : ( ) => import ( "./commands/handlers/upgrade" ) ,
@@ -100,6 +102,10 @@ Effect.gen(function* () {
100102 yield * Heap . listen
101103 yield * CpuProfile . listen
102104 yield * ShutdownDeadline . install ( )
105+ // runMain reports every signal interruption as 130; remember a SIGTERM so the exit code is 143.
106+ process . once ( "SIGTERM" , ( ) => {
107+ terminated = true
108+ } )
103109 const runFork = Effect . runForkWith ( yield * Effect . context < never > ( ) )
104110 const uncaughtException = ( cause : Error , origin : "uncaughtException" | "unhandledRejection" ) => {
105111 runFork ( Effect . logError ( "uncaught exception" , { cause, origin } ) )
@@ -152,7 +158,6 @@ Effect.gen(function* () {
152158 ) ,
153159 Effect . provide ( NodeServices . layer ) ,
154160 Effect . scoped ,
155- Effect . tap ( ( ) => Effect . sync ( ( ) => process . exit ( process . exitCode ?? 0 ) ) ) ,
156161 // runMain's default reporter logs the fatal cause to stdout. Write it to stderr instead: the
157162 // desktop and `Service.ensure` only capture stderr from `serve --service`, so this is the only
158163 // channel through which a startup failure's reason reaches the user.
@@ -163,5 +168,16 @@ Effect.gen(function* () {
163168 process . stderr . write ( Cause . pretty ( cause ) + "\n" )
164169 } ) ,
165170 ) ,
166- NodeRuntime . runMain ( { disableErrorReporting : true } ) ,
171+ NodeRuntime . runMain ( {
172+ disableErrorReporting : true ,
173+ teardown : ( exit ) =>
174+ defaultTeardown ( exit , ( code ) => {
175+ // Commands report failures through process.exitCode.
176+ const status = code === 0 ? ( process . exitCode ?? 0 ) : code === 130 && terminated ? 143 : code
177+ // process.exit drops output still queued for a pipe; ending the streams waits for it.
178+ void Promise . all (
179+ [ process . stdout , process . stderr ] . map ( ( stream ) => new Promise < void > ( ( resolve ) => stream . end ( ( ) => resolve ( ) ) ) ) ,
180+ ) . then ( ( ) => process . exit ( status ) )
181+ } ) ,
182+ } ) ,
167183)
0 commit comments