@@ -10,6 +10,7 @@ import { randomUUID } from 'node:crypto';
1010import type { DiagnosticsRecordRef , NormalizedError } from '@agent-device/kernel/errors' ;
1111import { normalizeError } from '@agent-device/kernel/errors' ;
1212import { LEASE_BACKENDS } from '@agent-device/kernel/contracts' ;
13+ import { isRecord } from '@agent-device/kernel/record' ;
1314import type { DaemonInvokeFn , DaemonRequest , DaemonResponse } from '../daemon-request.ts' ;
1415import { emitDiagnostic } from '@agent-device/host-kit/diagnostics' ;
1516import {
@@ -178,6 +179,10 @@ export async function createDaemonHttpServer(options: {
178179 }
179180
180181 readRpcRequestBody ( req , res , ( body ) => {
182+ // The flow owns this request's lifetime, so this call site must neither hold lifetime state
183+ // nor re-run it; the `catch` only answers. That answer is load-bearing: the daemon exits on
184+ // an `unhandledRejection`, so a rejection dropped here would let any process that reaches
185+ // the port stop the daemon with one request body.
181186 void handleRpcRequest ( {
182187 req,
183188 res,
@@ -186,6 +191,8 @@ export async function createDaemonHttpServer(options: {
186191 expectedToken : token ,
187192 instanceId,
188193 handleRequest,
194+ } ) . catch ( ( error : unknown ) => {
195+ sendUnownedRpcRequestFailure ( res , error ) ;
189196 } ) ;
190197 } ) ;
191198 } ) ;
@@ -242,7 +249,8 @@ async function handleRpcRequest(params: {
242249 const lifetime = beginRpcRequestLifetime ( { req, res, rpcId : validated . rpcRequest . id } ) ;
243250 // The `finally` below is the flow's only cleanup for a call that never reached an
244251 // invocation: unsound method params or a duplicate tracking id. An invoked request
245- // releases its own lifetime as the last step of answering.
252+ // releases its own lifetime as the last step of answering, before anything observing the
253+ // socket gets a turn.
246254 try {
247255 const admission = await admitRpcRequest ( {
248256 req,
@@ -275,7 +283,7 @@ async function handleRpcRequest(params: {
275283 // or a duplicate tracking id. The failure answer is on its way, so a socket closing
276284 // after it is not a client walking out on work still in flight.
277285 lifetime . markHandlerCompleted ( ) ;
278- sendRpcRequestFailure ( res , validated . rpcRequest , error ) ;
286+ sendRpcRequestFailure ( res , validated . rpcRequest . id , normalizeError ( error ) ) ;
279287 } finally {
280288 lifetime . release ( ) ;
281289 }
@@ -310,15 +318,25 @@ type RpcEnvelopeVerdict =
310318
311319/**
312320 * Parses and validates one `/rpc` body. A body that is not JSON gets the same -32700 answer
313- * the socket's `error` listener gives a stream that breaks before it ends.
321+ * the socket's `error` listener gives a stream that breaks before it ends. A body that parses as
322+ * anything but one object — `null`, a number, a string, an array — is refused as -32600 before
323+ * anything reads a property off it: reading through `null` throws, and that throw has no call to
324+ * answer for.
314325 */
315326function validateRpcRequestEnvelope ( body : string ) : RpcEnvelopeVerdict {
316- let rpcRequest : JsonRpcRequest ;
327+ let parsed : unknown ;
317328 try {
318- rpcRequest = JSON . parse ( body ) as JsonRpcRequest ;
329+ parsed = JSON . parse ( body ) ;
319330 } catch {
320331 return { ok : false , refusal : rpcParseErrorRefusal ( ) } ;
321332 }
333+ if ( ! isRecord ( parsed ) ) {
334+ return {
335+ ok : false ,
336+ refusal : rpcRefusal ( null , INVALID_REQUEST , 'Invalid Request' , 400 ) ,
337+ } ;
338+ }
339+ const rpcRequest = parsed as JsonRpcRequest ;
322340
323341 const refused = ( code : number , message : string , statusCode : number ) : RpcEnvelopeVerdict => ( {
324342 ok : false ,
@@ -493,7 +511,7 @@ async function admitRpcRequest(params: {
493511 outcome : 'rejected' ,
494512 refusal : rpcRefusal (
495513 rpcRequest . id ?? null ,
496- - 32602 ,
514+ INVALID_PARAMS ,
497515 'Invalid params: command is required' ,
498516 400 ,
499517 ) ,
@@ -636,34 +654,51 @@ async function invokeAdmittedRpcRequest(params: {
636654 writeRpcResponseEnvelope ( res , rpcAnswerFor ( rpcRequest , daemonResponse ) ) ;
637655 } catch ( error ) {
638656 lifetime . markHandlerCompleted ( ) ;
639- sendRpcRequestFailure ( res , rpcRequest , error ) ;
657+ sendRpcRequestFailure ( res , rpcRequest . id , normalizeError ( error ) ) ;
640658 } finally {
641659 lifetime . release ( ) ;
642660 }
643661}
644662
645663/**
646- * Answers a call that failed before an answer could be written — malformed wire input the
647- * method vocabulary refused, or a handler that threw. A status code goes only to a call
648- * that has not started answering; a stream already opened answers with its envelope.
664+ * Last-resort answer for a `/rpc` flow rejection: no call id is known, so the refusal carries none.
665+ * The reason goes to the daemon's error stream, the sink `unhandledRejection` used, because the
666+ * request's diagnostics scope may not exist yet; writing after `end` throws, so an already-ended
667+ * response gets nothing.
668+ */
669+ function sendUnownedRpcRequestFailure ( res : http . ServerResponse , error : unknown ) : void {
670+ const failure = normalizeError ( error ) ;
671+ emitDiagnostic ( {
672+ level : 'error' ,
673+ phase : 'rpc_request_flow_failed' ,
674+ data : { code : failure . code , message : failure . message } ,
675+ } ) ;
676+ process . stderr . write ( `Daemon error: ${ failure . message } \n` ) ;
677+ if ( res . writableEnded ) return ;
678+ sendRpcRequestFailure ( res , null , failure ) ;
679+ }
680+
681+ /**
682+ * Answers a call that failed before an answer could be written — malformed wire input the method
683+ * vocabulary refused, a handler that threw, or a flow that rejected outright. A status code goes
684+ * only to a call that has not started answering; a stream already opened answers with its envelope.
649685 */
650686function sendRpcRequestFailure (
651687 res : http . ServerResponse ,
652- rpcRequest : JsonRpcRequest ,
653- error : unknown ,
688+ requestId : JsonRpcRequest [ 'id' ] ,
689+ failure : NormalizedError ,
654690) : void {
655- const normalized = normalizeError ( error ) ;
656691 const response = createRpcError (
657- rpcRequest . id ?? null ,
658- jsonRpcCodeForNormalizedError ( normalized . code ) ,
659- normalized . message ,
660- normalized ,
692+ requestId ?? null ,
693+ jsonRpcCodeForNormalizedError ( failure . code ) ,
694+ failure . message ,
695+ failure ,
661696 ) ;
662697 if ( res . headersSent ) {
663698 writeRpcResponseEnvelope ( res , response ) ;
664699 return ;
665700 }
666- sendJson ( res , response , statusCodeForNormalizedError ( normalized . code ) ) ;
701+ sendJson ( res , response , statusCodeForNormalizedError ( failure . code ) ) ;
667702}
668703
669704function rpcAnswerFor ( rpcRequest : JsonRpcRequest , daemonResponse : DaemonResponse ) : JsonRpcResponse {
0 commit comments