11import CoreFoundation
22import Darwin
33import Foundation
4+ import notify
5+ import os
46import Security
57
68/// One native signed helper per MCP session. This executable owns both local
@@ -74,6 +76,105 @@ import Security
7476 static let registeredHost = AgentPeerSigning . registeredHost ( pid : getpid ( ) )
7577 static var slot : Int ?
7678
79+ // MARK: Reconnecting without a tool call
80+ //
81+ // The MCP loop and background attempts share `slot`, `clientKey` and the socket
82+ // exchange; `stateLock` serializes them. The reconnect bookkeeping below is
83+ // touched only on `pairingQueue`. Background attempts never write to stdout.
84+ static let stateLock = NSLock ( )
85+ static let pairingQueue = DispatchQueue ( label : " codebasic-tts.agent-helper.pairing " )
86+ static let log = Logger ( subsystem : TTSRuntime . appID , category : " agent " )
87+ static var readyToken : Int32 = 0
88+ static var listening = false
89+ static var attempt = 0
90+ static var retryGeneration = 0
91+ static var stopped = false
92+ static var nextSignalAttempt = DispatchTime ( uptimeNanoseconds : 0 )
93+ static var signalPending = false
94+ static var signalAgain = false
95+ /// Bumped by every attempt the helper starts on its own.
96+ static var backgroundRuns = 0
97+
98+ /// Called before the session's first pairing, so a ready signal sent while
99+ /// that pairing runs is not lost (its attempt simply waits for the lock).
100+ static func listenForReady ( ) {
101+ guard ! listening else { return }
102+ let name = AgentPairing . readyNotification ( appID : AgentPeerSigning . appID )
103+ let registered = notify_register_dispatch ( name , & readyToken , pairingQueue ) { _ in onReadySignal ( ) }
104+ if registered == 0 { listening = true }
105+ else { log . error ( " [AGENT-CONN] helper listen result= \( registered , privacy : . public ) " ) }
106+ }
107+
108+ /// After the session's first pairing: retry while the app is unreachable.
109+ static func startReconnecting ( after status : String ) {
110+ pairingQueue . async {
111+ // A signal-driven attempt that already ran has the newer answer.
112+ guard backgroundRuns == 0 else { return }
113+ schedule ( after : status )
114+ }
115+ }
116+
117+ /// At most one signal-driven attempt per `AgentReconnect.signalInterval`,
118+ /// each delayed by up to a quarter second so the helpers of several sessions
119+ /// do not reach the app at the same instant. A burst of signals (or someone
120+ /// posting the name in a loop) collapses into one pending attempt.
121+ static func onReadySignal ( ) {
122+ guard ! stopped else { return }
123+ // A signal during a pending or running attempt gets one more attempt after it.
124+ guard ! signalPending else { signalAgain = true ; return }
125+ signalPending = true
126+ let now = DispatchTime . now ( )
127+ let start = max ( now , nextSignalAttempt ) + Double . random ( in : 0 ... 0.25 )
128+ pairingQueue . asyncAfter ( deadline : start ) {
129+ // A real ready signal means the app can be reached now.
130+ attempt = 0
131+ backgroundAttempt ( " ready " )
132+ // Measured from the end of this attempt, so attempts never overlap
133+ // and start at least the interval apart.
134+ nextSignalAttempt = . now ( ) + AgentReconnect . signalInterval
135+ signalPending = false
136+ if signalAgain {
137+ signalAgain = false
138+ onReadySignal ( )
139+ }
140+ }
141+ }
142+
143+ static func backgroundAttempt ( _ trigger : String ) {
144+ guard ! stopped else { return }
145+ backgroundRuns += 1
146+ stateLock . lock ( )
147+ let status = pairingStatus ( )
148+ let key = clientKey . map { String ( AgentBytes . hash ( $0 . publicKey ) . prefix ( 12 ) ) } ?? " none "
149+ stateLock . unlock ( )
150+ log . info ( " [AGENT-CONN] helper attempt trigger= \( trigger , privacy : . public ) key= \( key , privacy : . public ) result= \( status , privacy : . public ) " )
151+ schedule ( after : status )
152+ }
153+
154+ static func schedule ( after status : String ) {
155+ retryGeneration += 1
156+ switch AgentReconnect . next ( after : status , attempt : attempt ) {
157+ case . done :
158+ attempt = 0
159+ case . waitForSignal :
160+ attempt = 0
161+ log . info ( " [AGENT-CONN] helper wait reason= \( status , privacy : . public ) " )
162+ case . stop :
163+ stopped = true
164+ if listening { notify_cancel ( readyToken ) ; listening = false }
165+ log . info ( " [AGENT-CONN] helper wait reason=terminal: \( status , privacy : . public ) " )
166+ case . retry ( let base ) :
167+ let delay = AgentReconnect . jittered ( base , unit : Double . random ( in : 0 ... 1 ) )
168+ attempt += 1
169+ let generation = retryGeneration
170+ log . info ( " [AGENT-CONN] helper retry attempt= \( attempt , privacy : . public ) delay_ms= \( Int ( delay * 1000 ) , privacy : . public ) reason= \( status , privacy : . public ) " )
171+ pairingQueue . asyncAfter ( deadline : . now ( ) + delay ) {
172+ guard generation == retryGeneration else { return }
173+ backgroundAttempt ( " retry " )
174+ }
175+ }
176+ }
177+
77178 static func main ( ) {
78179 // A keychain dialog raised by a background helper would block the agent's
79180 // tool call. An inaccessible registered credential stays unavailable.
@@ -91,6 +192,8 @@ import Security
91192 var initialized = false , ready = false
92193 var proofs : [ Proof ] = [ ]
93194 while let input = readFrame ( ) {
195+ stateLock . lock ( )
196+ defer { stateLock . unlock ( ) }
94197 if input . isEmpty { emit ( error ( nil , - 32700 , " Malformed or oversized frame " ) ) ; continue }
95198 guard let frame = decode ( input ) , frame [ " jsonrpc " ] as? String == " 2.0 " ,
96199 let method = frame [ " method " ] as? String else {
@@ -99,7 +202,11 @@ import Security
99202 guard let id = frame [ " id " ] else {
100203 if method == " notifications/initialized " , initialized , ! ready {
101204 ready = true
102- _ = pairingStatus ( )
205+ listenForReady ( )
206+ let status = pairingStatus ( )
207+ let key = clientKey . map { String ( AgentBytes . hash ( $0 . publicKey ) . prefix ( 12 ) ) } ?? " none "
208+ log . info ( " [AGENT-CONN] helper attempt trigger=initialized key= \( key , privacy : . public ) result= \( status , privacy : . public ) " )
209+ startReconnecting ( after : status )
103210 }
104211 continue
105212 }
0 commit comments