@@ -10,12 +10,17 @@ func connectionError(_ message: String) -> NSError {
1010/// A dedicated home avoids importing the user's project tools, MCP servers or API configuration.
1111@ MainActor
1212final class CodexPlanRPC {
13+ private let diagnosticID = MemoryDiagnostics . begin ( " codexRPC.instance " )
14+ deinit { MemoryDiagnostics . end ( diagnosticID ) }
15+ private func updateMemoryMetrics ( ) {
16+ MemoryDiagnostics . update ( diagnosticID , values : [ " rpcBufferBytes " : buffer . count , " rpcPending " : pending . count ] )
17+ }
1318 private let process = Process ( )
1419 private let input = Pipe ( )
1520 private let output = Pipe ( )
16- private var buffer = Data ( )
21+ private var buffer = Data ( ) { didSet { updateMemoryMetrics ( ) } }
1722 private var nextID = 0
18- private var pending : [ Int : CheckedContinuation < [ String : Any ] , Error > ] = [ : ]
23+ private var pending : [ Int : CheckedContinuation < [ String : Any ] , Error > ] = [ : ] { didSet { updateMemoryMetrics ( ) } }
1924 var notification : ( ( String , [ String : Any ] ) -> Void ) ?
2025 var disconnected : ( ( ) -> Void ) ?
2126 private var closed = false
@@ -45,18 +50,21 @@ final class CodexPlanRPC {
4550 output . fileHandleForReading . readabilityHandler = { [ weak self ] handle in
4651 let data = handle . availableData
4752 Task { @MainActor in
53+ let activityID = MemoryDiagnostics . begin ( " CodexPlan.rpcRead " )
54+ defer { MemoryDiagnostics . end ( activityID ) }
4855 guard let self else { return }
4956 if data . isEmpty { self . stop ( ) ; return }
5057 self . receive ( data )
5158 }
5259 }
5360 process . terminationHandler = { [ weak self ] _ in Task { @MainActor in self ? . stop ( ) } }
5461 try process . run ( )
62+ MemoryDiagnostics . sample ( " codex.process.started " , details : " childPID= \( process . processIdentifier ) " )
5563 }
5664
57- func initialize ( ) async throws {
65+ func initialize ( experimental : Bool = false ) async throws {
5866 _ = try await request ( " initialize " , [ " clientInfo " : [ " name " : " codebasic_tts " , " version " : " 1.0 " ] ,
59- " capabilities " : [ " experimentalApi " : false ] ] )
67+ " capabilities " : [ " experimentalApi " : experimental ] ] )
6068 try send ( [ " method " : " initialized " , " params " : [ : ] ] )
6169 }
6270
@@ -69,6 +77,8 @@ final class CodexPlanRPC {
6977 do { try send ( [ " id " : id , " method " : method , " params " : params ] ) }
7078 catch { pending . removeValue ( forKey : id ) ? . resume ( throwing : error ) }
7179 Task { [ weak self ] in
80+ let activityID = MemoryDiagnostics . begin ( " CodexPlan.rpcDeadline " )
81+ defer { MemoryDiagnostics . end ( activityID ) }
7282 try? await Task . sleep ( for : . seconds ( 30 ) )
7383 self ? . pending . removeValue ( forKey : id ) ? . resume ( throwing : connectionError ( " 연결 응답 시간이 초과되었습니다. " ) )
7484 }
@@ -111,6 +121,7 @@ final class CodexPlanRPC {
111121 func stop ( ) {
112122 guard ! closed else { return }
113123 closed = true
124+ MemoryDiagnostics . sample ( " codex.stop.requested " , details : " childPID= \( process . processIdentifier ) running= \( process . isRunning ) " )
114125 notification = nil
115126 output . fileHandleForReading . readabilityHandler = nil
116127 try? input . fileHandleForWriting . close ( )
@@ -136,6 +147,8 @@ final class CodexPlanLogin: ObservableObject {
136147 busy = true
137148 status = " 로그인 준비 중… "
138149 loginTask = Task {
150+ let activityID = MemoryDiagnostics . begin ( " CodexPlan.login " )
151+ defer { MemoryDiagnostics . end ( activityID ) }
139152 do {
140153 try Task . checkCancellation ( )
141154 let client = try CodexPlanRPC ( )
@@ -159,6 +172,8 @@ final class CodexPlanLogin: ObservableObject {
159172 guard NSWorkspace . shared . open ( url ) else { throw connectionError ( " 로그인 브라우저를 열 수 없습니다. " ) }
160173 status = " 브라우저에서 ChatGPT 로그인을 완료하세요. "
161174 timeout = Task { [ weak self ] in
175+ let activityID = MemoryDiagnostics . begin ( " CodexPlan.loginDeadline " )
176+ defer { MemoryDiagnostics . end ( activityID ) }
162177 do { try await Task . sleep ( for : . seconds ( 180 ) ) } catch { return }
163178 self ? . cancel ( )
164179 self ? . status = " 로그인 시간이 초과되었습니다. 다시 시도하세요. "
@@ -191,35 +206,45 @@ enum CodexPlan {
191206 return models
192207 }
193208
194- static func stream ( prompt : String , model : String , images : [ Data ] , reasoning : ReasoningLevel ) -> AsyncThrowingStream < String , Error > {
209+ static func stream ( prompt : String , model : String , images : [ Data ] , reasoning : ReasoningLevel ,
210+ conversation : ExplanationConversation ? = nil , executable : URL ? = nil , home : URL ? = nil ) -> AsyncThrowingStream < String , Error > {
195211 AsyncThrowingStream { continuation in
196212 let task = Task { @MainActor in
213+ let activityID = MemoryDiagnostics . begin ( " CodexPlan.generation " )
214+ defer { MemoryDiagnostics . end ( activityID ) }
197215 var rpc : CodexPlanRPC ?
198216 do {
199217 try Task . checkCancellation ( )
200- let client = try CodexPlanRPC ( )
218+ let client = try CodexPlanRPC ( executable : executable , home : home )
201219 rpc = client
202220 defer { client . stop ( ) }
203- try await client . initialize ( )
221+ try await client . initialize ( experimental : conversation != nil )
204222 _ = try await client . requirePlan ( )
205223 try Task . checkCancellation ( )
206224 let thread = try await client . request ( " thread/start " , [ " ephemeral " : true , " model " : model ,
207225 " modelProvider " : " openai " , " sandbox " : " read-only " , " approvalPolicy " : " never " ,
208- " baseInstructions " : " Return only the requested text. Do not use tools, access files, or perform actions. " ,
226+ " baseInstructions " : " Return only the requested text. Do not use tools, access files, or perform actions. "
227+ + ( conversation . map { " \n \n " + $0 . system } ?? " " ) ,
209228 " config " : [ " features.shell_tool " : false , " features.apply_patch_freeform " : false ,
210229 " features.code_mode " : false , " web_search " : " disabled " ] ] )
211230 guard let info = thread [ " thread " ] as? [ String : Any ] , let id = info [ " id " ] as? String else {
212231 throw connectionError ( " 생성 세션을 시작하지 못했습니다. " )
213232 }
233+ if let conversation , ! conversation . codexHistoryItems . isEmpty {
234+ _ = try await client . request ( " thread/injectItems " , [ " threadId " : id , " items " : conversation . codexHistoryItems ] )
235+ }
214236 let ( events , eventContinuation ) = AsyncStream < ( String , [ String : Any ] ) > . makeStream ( )
215237 client . notification = { eventContinuation . yield ( ( $0 , $1 ) ) }
216238 client . disconnected = { eventContinuation . finish ( ) }
217- var input : [ [ String : Any ] ] = [ [ " type " : " text " , " text " : prompt , " text_elements " : [ ] ] ]
218- input += images . map { [ " type " : " image " , " url " : " data:image/png;base64, \( $0 . base64EncodedString ( ) ) " ] }
239+ let current = conversation ? . messages . last
240+ var input : [ [ String : Any ] ] = [ [ " type " : " text " , " text " : current ? . text ?? prompt , " text_elements " : [ ] ] ]
241+ input += ( current ? . images ?? images ) . map { [ " type " : " image " , " url " : " data:image/png;base64, \( $0 . base64EncodedString ( ) ) " ] }
219242 var params : [ String : Any ] = [ " threadId " : id , " input " : input ]
220243 if ! reasoning . isProviderDefault { params [ " effort " ] = reasoning . rawValue }
221244 _ = try await client . request ( " turn/start " , params )
222245 let deadline = Task { @MainActor in
246+ let activityID = MemoryDiagnostics . begin ( " CodexPlan.generationDeadline " )
247+ defer { MemoryDiagnostics . end ( activityID ) }
223248 do { try await Task . sleep ( for : . seconds ( 180 ) ) } catch { return }
224249 eventContinuation . finish ( )
225250 }
0 commit comments