process-gpt-agent-sdk 0.2.8__py3-none-any.whl → 0.2.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of process-gpt-agent-sdk might be problematic. Click here for more details.

@@ -1,292 +1,313 @@
1
- import asyncio
2
- from typing import Any, Dict
3
-
4
- from a2a.server.agent_execution import AgentExecutor, RequestContext
5
- from a2a.server.events import EventQueue, Event
6
-
7
- from .core.database import (
8
- fetch_human_users_by_proc_inst_id,
9
- initialize_db,
10
- get_consumer_id,
11
- polling_pending_todos,
12
- fetch_done_data,
13
- fetch_agent_data,
14
- fetch_form_types,
15
- fetch_task_status,
16
- fetch_tenant_mcp_config,
17
- update_task_error,
18
- )
19
-
20
- from .utils.logger import handle_application_error, write_log_message
21
- from .utils.summarizer import summarize_async
22
- from .utils.event_handler import process_event_message
23
- from .utils.context_manager import set_context, reset_context
24
-
25
-
26
- # =============================================================================
27
- # 서버: ProcessGPTAgentServer
28
- # 설명: 작업 폴링→실행 준비→실행/이벤트 저장→취소 감시까지 담당하는 핵심 서버
29
- # =============================================================================
30
- class ProcessGPTAgentServer:
31
- """ProcessGPT 핵심 서버
32
-
33
- - 단일 실행기 모델: 실행기는 하나이며, 작업별 분기는 실행기 내부 로직에 위임합니다.
34
- - 폴링은 타입 필터 없이(빈 값) 가져온 뒤, 작업 레코드의 정보로 처리합니다.
35
- """
36
-
37
- def __init__(self, executor: AgentExecutor, polling_interval: int = 5, agent_orch: str = ""):
38
- """서버 실행기/폴링 주기/오케스트레이션 값을 초기화한다."""
39
- self.polling_interval = polling_interval
40
- self.is_running = False
41
- self._executor: AgentExecutor = executor
42
- self.cancel_check_interval: float = 0.5
43
- self.agent_orch: str = agent_orch or ""
44
- initialize_db()
45
-
46
- async def run(self) -> None:
47
- """메인 폴링 루프를 실행한다. 작업을 가져와 준비/실행/감시를 순차 수행."""
48
- self.is_running = True
49
- write_log_message("ProcessGPT 서버 시작")
50
-
51
- while self.is_running:
52
- try:
53
- task_record = await polling_pending_todos(self.agent_orch, get_consumer_id())
54
- if not task_record:
55
- await asyncio.sleep(self.polling_interval)
56
- continue
57
-
58
- task_id = task_record["id"]
59
- write_log_message(f"[JOB START] task_id={task_id}")
60
-
61
- try:
62
- prepared_data = await self._prepare_service_data(task_record)
63
- write_log_message(f"[RUN] 서비스 데이터 준비 완료 [task_id={task_id} agent={prepared_data.get('agent_orch','')}]")
64
-
65
- await self._execute_with_cancel_watch(task_record, prepared_data)
66
- write_log_message(f"[RUN] 서비스 실행 완료 [task_id={task_id} agent={prepared_data.get('agent_orch','')}]")
67
- except Exception as job_err:
68
- handle_application_error("작업 처리 오류", job_err, raise_error=False)
69
- try:
70
- await update_task_error(str(task_id))
71
- except Exception as upd_err:
72
- handle_application_error("FAILED 상태 업데이트 실패", upd_err, raise_error=False)
73
- continue
74
-
75
- except Exception as e:
76
- handle_application_error("폴링 루프 오류", e, raise_error=False)
77
- await asyncio.sleep(self.polling_interval)
78
-
79
- def stop(self) -> None:
80
- """폴링 루프를 중지 플래그로 멈춘다."""
81
- self.is_running = False
82
- write_log_message("ProcessGPT 서버 중지")
83
-
84
- async def _prepare_service_data(self, task_record: Dict[str, Any]) -> Dict[str, Any]:
85
- """실행에 필요한 데이터(에이전트/폼/요약/사용자)를 준비해 dict로 반환."""
86
- done_outputs = await fetch_done_data(task_record.get("proc_inst_id"))
87
- write_log_message(f"[PREP] done_outputs → {done_outputs}")
88
- feedbacks = task_record.get("feedback")
89
-
90
- agent_list = await fetch_agent_data(str(task_record.get("user_id", "")))
91
- write_log_message(f"[PREP] agent_list → {agent_list}")
92
-
93
- mcp_config = await fetch_tenant_mcp_config(str(task_record.get("tenant_id", "")))
94
- write_log_message(f"[PREP] mcp_config() {mcp_config}")
95
-
96
- form_id, form_types, form_html = await fetch_form_types(
97
- str(task_record.get("tool", "")),
98
- str(task_record.get("tenant_id", ""))
99
- )
100
- write_log_message(f"[PREP] formid={form_id} types={form_types}")
101
-
102
- output_summary, feedback_summary = await summarize_async(
103
- done_outputs or [], feedbacks or "", task_record.get("description", "")
104
- )
105
- write_log_message(f"[PREP] summary output={output_summary} feedback={feedback_summary}")
106
-
107
-
108
- all_users = await fetch_human_users_by_proc_inst_id(task_record.get("proc_inst_id"))
109
- write_log_message(f"[PREP] all_users → {all_users}")
110
-
111
- prepared: Dict[str, Any] = {
112
- "task_id": str(task_record.get("id")),
113
- "proc_inst_id": task_record.get("proc_inst_id"),
114
- "agent_list": agent_list or [],
115
- "mcp_config": mcp_config,
116
- "form_id": form_id,
117
- "todo_id": str(task_record.get("id")),
118
- "form_types": form_types or [],
119
- "form_html": form_html or "",
120
- "activity_name": str(task_record.get("activity_name", "")),
121
- "description": str(task_record.get("description", "")),
122
- "agent_orch": str(task_record.get("agent_orch", "")),
123
- "done_outputs": done_outputs or [],
124
- "output_summary": output_summary or "",
125
- "feedback_summary": feedback_summary or "",
126
- "all_users": all_users or "",
127
- }
128
-
129
- return prepared
130
-
131
- async def _execute_with_cancel_watch(self, task_record: Dict[str, Any], prepared_data: Dict[str, Any]) -> None:
132
- """실행 태스크와 취소 감시 태스크를 동시에 운영한다."""
133
- executor = self._executor
134
-
135
- context = ProcessGPTRequestContext(prepared_data)
136
- loop = asyncio.get_running_loop()
137
- event_queue = ProcessGPTEventQueue(task_record, loop=loop)
138
-
139
- try:
140
- set_context(
141
- todo_id=str(task_record.get("id")),
142
- proc_inst_id=str(task_record.get("proc_inst_id") or ""),
143
- crew_type=str(prepared_data.get("agent_orch") or ""),
144
- form_id=str(prepared_data.get("form_id") or ""),
145
- all_users=str(prepared_data.get("all_users") or ""),
146
- )
147
- except Exception as e:
148
- handle_application_error("컨텍스트 설정 실패", e, raise_error=False)
149
-
150
- write_log_message(f"[EXEC START] task_id={task_record.get('id')} agent={prepared_data.get('agent_orch','')}")
151
- execute_task = asyncio.create_task(executor.execute(context, event_queue))
152
- cancel_watch_task = asyncio.create_task(self._watch_cancellation(task_record, executor, context, event_queue, execute_task))
153
-
154
- try:
155
- done, pending = await asyncio.wait(
156
- [cancel_watch_task, execute_task],
157
- return_when=asyncio.FIRST_COMPLETED
158
- )
159
- for task in pending:
160
- task.cancel()
161
-
162
- except Exception as e:
163
- handle_application_error("서비스 실행 오류", e, raise_error=False)
164
- cancel_watch_task.cancel()
165
- execute_task.cancel()
166
- finally:
167
- # 컨텍스트 정리
168
- try:
169
- reset_context()
170
- except Exception as e:
171
- handle_application_error("컨텍스트 리셋 실패", e, raise_error=False)
172
- try:
173
- await event_queue.close()
174
- except Exception as e:
175
- handle_application_error("이벤트 큐 종료 실패", e, raise_error=False)
176
- write_log_message(f"[EXEC END] task_id={task_record.get('id')} agent={prepared_data.get('agent_orch','')}")
177
-
178
- async def _watch_cancellation(self, task_record: Dict[str, Any], executor: AgentExecutor, context: RequestContext, event_queue: EventQueue, execute_task: asyncio.Task) -> None:
179
- """작업 상태를 주기적으로 확인해 취소 신호 시 안전 종료를 수행."""
180
- todo_id = str(task_record.get("id"))
181
-
182
- while True:
183
- await asyncio.sleep(self.cancel_check_interval)
184
-
185
- status = await fetch_task_status(todo_id)
186
- normalized = (status or "").strip().lower()
187
- if normalized in ("cancelled", "fb_requested"):
188
- write_log_message(f"작업 취소 감지: {todo_id}, 상태: {status}")
189
-
190
- try:
191
- await executor.cancel(context, event_queue)
192
- except Exception as e:
193
- handle_application_error("취소 처리 실패", e, raise_error=False)
194
- finally:
195
- try:
196
- execute_task.cancel()
197
- except Exception as e:
198
- handle_application_error("실행 태스크 즉시 취소 실패", e, raise_error=False)
199
- try:
200
- await event_queue.close()
201
- except Exception as e:
202
- handle_application_error("취소 이벤트 큐 종료 실패", e, raise_error=False)
203
- break
204
-
205
- # =============================================================================
206
- # 요청 컨텍스트: ProcessGPTRequestContext
207
- # 설명: 실행기에게 전달되는 요청 데이터/상태를 캡슐화
208
- # =============================================================================
209
- class ProcessGPTRequestContext(RequestContext):
210
- def __init__(self, prepared_data: Dict[str, Any]):
211
- """실행에 필요한 데이터 묶음을 보관한다."""
212
- self._prepared_data = prepared_data
213
- self._message = prepared_data.get("message", "")
214
- self._current_task = None
215
-
216
- def get_user_input(self) -> str:
217
- """사용자 입력 메시지를 반환한다."""
218
- return self._message
219
-
220
- @property
221
- def message(self) -> str:
222
- """현재 메시지(사용자 입력)를 반환한다."""
223
- return self._message
224
-
225
- @property
226
- def current_task(self):
227
- """현재 실행 태스크(있다면)를 반환한다."""
228
- return getattr(self, "_current_task", None)
229
-
230
- def get_context_data(self) -> Dict[str, Any]:
231
- """실행 컨텍스트 전체 데이터를 dict로 반환한다."""
232
- return self._prepared_data
233
-
234
- # =============================================================================
235
- # 이벤트 큐: ProcessGPTEventQueue
236
- # 설명: 실행기 이벤트를 내부 큐에 넣고, 비동기 처리 태스크를 생성해 저장 로직 호출
237
- # =============================================================================
238
- class ProcessGPTEventQueue(EventQueue):
239
- def __init__(self, task_record: Dict[str, Any], loop: asyncio.AbstractEventLoop | None = None):
240
- """현재 처리 중인 작업 레코드를 보관한다."""
241
- self.todo = task_record
242
- self._loop = loop
243
- super().__init__()
244
-
245
- def enqueue_event(self, event: Event):
246
- """이벤트를 큐에 넣고, 백그라운드로 DB 저장 코루틴을 실행한다."""
247
- try:
248
- try:
249
- super().enqueue_event(event)
250
- except Exception as e:
251
- handle_application_error("이벤트 삽입 실패", e, raise_error=False)
252
-
253
- self._create_bg_task(process_event_message(self.todo, event), "process_event_message")
254
- except Exception as e:
255
- handle_application_error("이벤트 저장 실패", e, raise_error=False)
256
-
257
- def task_done(self) -> None:
258
- """태스크 완료 로그를 남긴다."""
259
- try:
260
- write_log_message(f"태스크 완료: {self.todo['id']}")
261
- except Exception as e:
262
- handle_application_error("태스크 완료 처리 실패", e, raise_error=False)
263
-
264
- async def close(self) -> None:
265
- """큐 종료 훅(필요 시 리소스 정리)."""
266
- pass
267
-
268
- def _create_bg_task(self, coro: Any, label: str) -> None:
269
- """백그라운드 태스크 생성 완료 콜백으로 예외 로깅.
270
-
271
- - 실행 중인 이벤트 루프가 없을 때도 전달된 루프에 안전하게 예약한다.
272
- """
273
- try:
274
- loop = self._loop
275
- if loop is None:
276
- try:
277
- loop = asyncio.get_running_loop()
278
- except RuntimeError:
279
- raise
280
-
281
- def _cb(t: asyncio.Task):
282
- exc = t.exception()
283
- if exc:
284
- handle_application_error(f"백그라운드 태스크 오류({label})", exc, raise_error=False)
285
-
286
- def _schedule():
287
- task = loop.create_task(coro)
288
- task.add_done_callback(_cb)
289
-
290
- loop.call_soon_threadsafe(_schedule)
291
- except Exception as e:
292
- handle_application_error(f"백그라운드 태스크 생성 실패({label})", e, raise_error=False)
1
+ import asyncio
2
+ from typing import Any, Dict
3
+
4
+ from a2a.server.agent_execution import AgentExecutor, RequestContext
5
+ from a2a.server.events import EventQueue, Event
6
+
7
+ from .core.database import (
8
+ fetch_human_users_by_proc_inst_id,
9
+ initialize_db,
10
+ get_consumer_id,
11
+ polling_pending_todos,
12
+ fetch_done_data,
13
+ fetch_agent_data,
14
+ fetch_form_types,
15
+ fetch_task_status,
16
+ fetch_tenant_mcp_config,
17
+ update_task_error,
18
+ )
19
+
20
+ from .utils.logger import handle_application_error, write_log_message, write_debug_message, write_info_message, DEBUG_LEVEL_BASIC, DEBUG_LEVEL_DETAILED, DEBUG_LEVEL_VERBOSE
21
+ from .utils.summarizer import summarize_async
22
+ from .utils.event_handler import process_event_message
23
+ from .utils.context_manager import set_context, reset_context
24
+
25
+
26
+ # =============================================================================
27
+ # 서버: ProcessGPTAgentServer
28
+ # 설명: 작업 폴링→실행 준비→실행/이벤트 저장→취소 감시까지 담당하는 핵심 서버
29
+ # =============================================================================
30
+ class ProcessGPTAgentServer:
31
+ """ProcessGPT 핵심 서버
32
+
33
+ - 단일 실행기 모델: 실행기는 하나이며, 작업별 분기는 실행기 내부 로직에 위임합니다.
34
+ - 폴링은 타입 필터 없이(빈 값) 가져온 뒤, 작업 레코드의 정보로 처리합니다.
35
+ """
36
+
37
+ def __init__(self, executor: AgentExecutor, polling_interval: int = 5, agent_orch: str = ""):
38
+ """서버 실행기/폴링 주기/오케스트레이션 값을 초기화한다."""
39
+ self.polling_interval = polling_interval
40
+ self.is_running = False
41
+ self._executor: AgentExecutor = executor
42
+ self.cancel_check_interval: float = 0.5
43
+ self.agent_orch: str = agent_orch or ""
44
+ initialize_db()
45
+
46
+ async def run(self) -> None:
47
+ """메인 폴링 루프를 실행한다. 작업을 가져와 준비/실행/감시를 순차 수행."""
48
+ self.is_running = True
49
+ write_log_message("ProcessGPT 서버 시작")
50
+ write_debug_message(f"[DEBUG-001] 서버 초기화 완료 - polling_interval={self.polling_interval}s, agent_orch='{self.agent_orch}', cancel_check_interval={self.cancel_check_interval}s", DEBUG_LEVEL_BASIC)
51
+
52
+ while self.is_running:
53
+ try:
54
+ write_debug_message(f"[DEBUG-002] 폴링 시작 - agent_orch='{self.agent_orch}', consumer_id={get_consumer_id()}", DEBUG_LEVEL_VERBOSE)
55
+ task_record = await polling_pending_todos(self.agent_orch, get_consumer_id())
56
+ if not task_record:
57
+ write_debug_message(f"[DEBUG-003] 대기 중인 작업 없음 - {self.polling_interval}초 후 재시도", DEBUG_LEVEL_VERBOSE)
58
+ await asyncio.sleep(self.polling_interval)
59
+ continue
60
+
61
+ task_id = task_record["id"]
62
+ write_log_message(f"[JOB START] task_id={task_id}")
63
+ write_debug_message(f"[DEBUG-004] 작업 레코드 수신 - task_id={task_id}, proc_inst_id={task_record.get('proc_inst_id')}, user_id={task_record.get('user_id')}, tenant_id={task_record.get('tenant_id')}, activity_name={task_record.get('activity_name')}", DEBUG_LEVEL_BASIC)
64
+
65
+ try:
66
+ write_debug_message(f"[DEBUG-005] 서비스 데이터 준비 시작 - task_id={task_id}", DEBUG_LEVEL_DETAILED)
67
+ prepared_data = await self._prepare_service_data(task_record)
68
+ write_log_message(f"[RUN] 서비스 데이터 준비 완료 [task_id={task_id} agent={prepared_data.get('agent_orch','')}]")
69
+ write_debug_message(f"[DEBUG-006] 준비된 데이터 요약 - agent_list_count={len(prepared_data.get('agent_list', []))}, form_types_count={len(prepared_data.get('form_types', []))}, done_outputs_count={len(prepared_data.get('done_outputs', []))}, all_users_count={len(prepared_data.get('all_users', []))}", DEBUG_LEVEL_DETAILED)
70
+
71
+ write_debug_message(f"[DEBUG-007] 실행 취소 감시 시작 - task_id={task_id}", DEBUG_LEVEL_BASIC)
72
+ await self._execute_with_cancel_watch(task_record, prepared_data)
73
+ write_log_message(f"[RUN] 서비스 실행 완료 [task_id={task_id} agent={prepared_data.get('agent_orch','')}]")
74
+ write_debug_message(f"[DEBUG-008] 작업 완료 처리 - task_id={task_id}", DEBUG_LEVEL_BASIC)
75
+ except Exception as job_err:
76
+ write_debug_message(f"[DEBUG-009] 작업 처리 중 예외 발생 - task_id={task_id}, error_type={type(job_err).__name__}, error_message={str(job_err)}", DEBUG_LEVEL_BASIC)
77
+ handle_application_error("작업 처리 오류", job_err, raise_error=False)
78
+ try:
79
+ await update_task_error(str(task_id))
80
+ except Exception as upd_err:
81
+ handle_application_error("FAILED 상태 업데이트 실패", upd_err, raise_error=False)
82
+ continue
83
+
84
+ except Exception as e:
85
+ handle_application_error("폴링 루프 오류", e, raise_error=False)
86
+ await asyncio.sleep(self.polling_interval)
87
+
88
+ def stop(self) -> None:
89
+ """폴링 루프를 중지 플래그로 멈춘다."""
90
+ self.is_running = False
91
+ write_log_message("ProcessGPT 서버 중지")
92
+
93
+ async def _prepare_service_data(self, task_record: Dict[str, Any]) -> Dict[str, Any]:
94
+ """실행에 필요한 데이터(에이전트/폼/요약/사용자) 준비해 dict로 반환."""
95
+ done_outputs = await fetch_done_data(task_record.get("proc_inst_id"))
96
+ write_log_message(f"[PREP] done_outputs {done_outputs}")
97
+ feedbacks = task_record.get("feedback")
98
+
99
+ agent_list = await fetch_agent_data(str(task_record.get("user_id", "")))
100
+ write_log_message(f"[PREP] agent_list → {agent_list}")
101
+
102
+ mcp_config = await fetch_tenant_mcp_config(str(task_record.get("tenant_id", "")))
103
+ write_log_message(f"[PREP] mcp_config(툴) {mcp_config}")
104
+
105
+ form_id, form_types, form_html = await fetch_form_types(
106
+ str(task_record.get("tool", "")),
107
+ str(task_record.get("tenant_id", ""))
108
+ )
109
+ write_log_message(f"[PREP] formid={form_id} types={form_types}")
110
+
111
+ output_summary, feedback_summary = await summarize_async(
112
+ done_outputs or [], feedbacks or "", task_record.get("description", "")
113
+ )
114
+ write_log_message(f"[PREP] summary output={output_summary} feedback={feedback_summary}")
115
+
116
+
117
+ all_users = await fetch_human_users_by_proc_inst_id(task_record.get("proc_inst_id"))
118
+ write_log_message(f"[PREP] all_users {all_users}")
119
+
120
+ prepared: Dict[str, Any] = {
121
+ "task_id": str(task_record.get("id")),
122
+ "proc_inst_id": task_record.get("proc_inst_id"),
123
+ "agent_list": agent_list or [],
124
+ "mcp_config": mcp_config,
125
+ "form_id": form_id,
126
+ "todo_id": str(task_record.get("id")),
127
+ "form_types": form_types or [],
128
+ "form_html": form_html or "",
129
+ "activity_name": str(task_record.get("activity_name", "")),
130
+ "description": str(task_record.get("description", "")),
131
+ "agent_orch": str(task_record.get("agent_orch", "")),
132
+ "done_outputs": done_outputs or [],
133
+ "output_summary": output_summary or "",
134
+ "feedback_summary": feedback_summary or "",
135
+ "all_users": all_users or "",
136
+ }
137
+
138
+ return prepared
139
+
140
+ async def _execute_with_cancel_watch(self, task_record: Dict[str, Any], prepared_data: Dict[str, Any]) -> None:
141
+ """실행 태스크와 취소 감시 태스크를 동시에 운영한다."""
142
+ executor = self._executor
143
+
144
+ context = ProcessGPTRequestContext(prepared_data)
145
+ loop = asyncio.get_running_loop()
146
+ event_queue = ProcessGPTEventQueue(task_record, loop=loop)
147
+
148
+ try:
149
+ set_context(
150
+ todo_id=str(task_record.get("id")),
151
+ proc_inst_id=str(task_record.get("proc_inst_id") or ""),
152
+ crew_type=str(prepared_data.get("agent_orch") or ""),
153
+ form_id=str(prepared_data.get("form_id") or ""),
154
+ all_users=str(prepared_data.get("all_users") or ""),
155
+ )
156
+ except Exception as e:
157
+ handle_application_error("컨텍스트 설정 실패", e, raise_error=False)
158
+
159
+ write_log_message(f"[EXEC START] task_id={task_record.get('id')} agent={prepared_data.get('agent_orch','')}")
160
+ write_debug_message(f"[DEBUG-010] 실행기 및 이벤트 큐 초기화 완료 - task_id={task_record.get('id')}, context_data_keys={list(context.get_context_data().keys())}, event_queue_type={type(event_queue).__name__}", DEBUG_LEVEL_DETAILED)
161
+ execute_task = asyncio.create_task(executor.execute(context, event_queue))
162
+ cancel_watch_task = asyncio.create_task(self._watch_cancellation(task_record, executor, context, event_queue, execute_task))
163
+ write_debug_message(f"[DEBUG-011] 비동기 태스크 생성 완료 - execute_task={execute_task.get_name()}, cancel_watch_task={cancel_watch_task.get_name()}", DEBUG_LEVEL_DETAILED)
164
+
165
+ try:
166
+ write_debug_message(f"[DEBUG-012] 태스크 대기 시작 - task_id={task_record.get('id')}", DEBUG_LEVEL_VERBOSE)
167
+ done, pending = await asyncio.wait(
168
+ [cancel_watch_task, execute_task],
169
+ return_when=asyncio.FIRST_COMPLETED
170
+ )
171
+ write_debug_message(f"[DEBUG-013] 태스크 완료 감지 - done_count={len(done)}, pending_count={len(pending)}", DEBUG_LEVEL_VERBOSE)
172
+ for task in pending:
173
+ write_debug_message(f"[DEBUG-014] 대기 중인 태스크 취소 - task_name={task.get_name()}", DEBUG_LEVEL_VERBOSE)
174
+ task.cancel()
175
+
176
+ except Exception as e:
177
+ handle_application_error("서비스 실행 오류", e, raise_error=False)
178
+ cancel_watch_task.cancel()
179
+ execute_task.cancel()
180
+ finally:
181
+ # 컨텍스트 정리
182
+ try:
183
+ reset_context()
184
+ except Exception as e:
185
+ handle_application_error("컨텍스트 리셋 실패", e, raise_error=False)
186
+ try:
187
+ await event_queue.close()
188
+ except Exception as e:
189
+ handle_application_error("이벤트 큐 종료 실패", e, raise_error=False)
190
+ write_log_message(f"[EXEC END] task_id={task_record.get('id')} agent={prepared_data.get('agent_orch','')}")
191
+
192
+ async def _watch_cancellation(self, task_record: Dict[str, Any], executor: AgentExecutor, context: RequestContext, event_queue: EventQueue, execute_task: asyncio.Task) -> None:
193
+ """작업 상태를 주기적으로 확인해 취소 신호 안전 종료를 수행."""
194
+ todo_id = str(task_record.get("id"))
195
+
196
+ while True:
197
+ await asyncio.sleep(self.cancel_check_interval)
198
+
199
+ status = await fetch_task_status(todo_id)
200
+ normalized = (status or "").strip().lower()
201
+ write_debug_message(f"[DEBUG-015] 취소 상태 확인 - todo_id={todo_id}, status='{status}', normalized='{normalized}', check_interval={self.cancel_check_interval}s", DEBUG_LEVEL_VERBOSE)
202
+ if normalized in ("cancelled", "fb_requested"):
203
+ write_log_message(f"작업 취소 감지: {todo_id}, 상태: {status}")
204
+ write_debug_message(f"[DEBUG-016] 취소 처리 시작 - todo_id={todo_id}, status='{status}', normalized='{normalized}'", DEBUG_LEVEL_BASIC)
205
+
206
+ try:
207
+ await executor.cancel(context, event_queue)
208
+ except Exception as e:
209
+ handle_application_error("취소 처리 실패", e, raise_error=False)
210
+ finally:
211
+ try:
212
+ execute_task.cancel()
213
+ except Exception as e:
214
+ handle_application_error("실행 태스크 즉시 취소 실패", e, raise_error=False)
215
+ try:
216
+ await event_queue.close()
217
+ except Exception as e:
218
+ handle_application_error("취소 후 이벤트 큐 종료 실패", e, raise_error=False)
219
+ break
220
+
221
+ # =============================================================================
222
+ # 요청 컨텍스트: ProcessGPTRequestContext
223
+ # 설명: 실행기에게 전달되는 요청 데이터/상태를 캡슐화
224
+ # =============================================================================
225
+ class ProcessGPTRequestContext(RequestContext):
226
+ def __init__(self, prepared_data: Dict[str, Any]):
227
+ """실행에 필요한 데이터 묶음을 보관한다."""
228
+ self._prepared_data = prepared_data
229
+ self._message = prepared_data.get("message", "")
230
+ self._current_task = None
231
+
232
+ def get_user_input(self) -> str:
233
+ """사용자 입력 메시지를 반환한다."""
234
+ return self._message
235
+
236
+ @property
237
+ def message(self) -> str:
238
+ """현재 메시지(사용자 입력)를 반환한다."""
239
+ return self._message
240
+
241
+ @property
242
+ def current_task(self):
243
+ """현재 실행 중 태스크(있다면)를 반환한다."""
244
+ return getattr(self, "_current_task", None)
245
+
246
+ def get_context_data(self) -> Dict[str, Any]:
247
+ """실행 컨텍스트 전체 데이터를 dict로 반환한다."""
248
+ return self._prepared_data
249
+
250
+ # =============================================================================
251
+ # 이벤트 큐: ProcessGPTEventQueue
252
+ # 설명: 실행기 이벤트를 내부 큐에 넣고, 비동기 처리 태스크를 생성해 저장 로직 호출
253
+ # =============================================================================
254
+ class ProcessGPTEventQueue(EventQueue):
255
+ def __init__(self, task_record: Dict[str, Any], loop: asyncio.AbstractEventLoop | None = None):
256
+ """현재 처리 중인 작업 레코드를 보관한다."""
257
+ self.todo = task_record
258
+ self._loop = loop
259
+ super().__init__()
260
+
261
+ def enqueue_event(self, event: Event):
262
+ """이벤트를 큐에 넣고, 백그라운드로 DB 저장 코루틴을 실행한다."""
263
+ try:
264
+ write_debug_message(f"[DEBUG-017] 이벤트 큐 삽입 시작 - todo_id={self.todo.get('id')}, event_type={type(event).__name__}", DEBUG_LEVEL_VERBOSE)
265
+ try:
266
+ super().enqueue_event(event)
267
+ write_debug_message(f"[DEBUG-018] 이벤트 큐 삽입 성공 - todo_id={self.todo.get('id')}, event_type={type(event).__name__}", DEBUG_LEVEL_VERBOSE)
268
+ except Exception as e:
269
+ write_debug_message(f"[DEBUG-019] 이벤트 삽입 실패 - todo_id={self.todo.get('id')}, error={str(e)}", DEBUG_LEVEL_BASIC)
270
+ handle_application_error("이벤트 큐 삽입 실패", e, raise_error=False)
271
+
272
+ write_debug_message(f"[DEBUG-020] 백그라운드 이벤트 처리 태스크 생성 - todo_id={self.todo.get('id')}", DEBUG_LEVEL_VERBOSE)
273
+ self._create_bg_task(process_event_message(self.todo, event), "process_event_message")
274
+ except Exception as e:
275
+ write_debug_message(f"[DEBUG-021] 이벤트 저장 전체 실패 - todo_id={self.todo.get('id')}, error={str(e)}", DEBUG_LEVEL_BASIC)
276
+ handle_application_error("이벤트 저장 실패", e, raise_error=False)
277
+
278
+ def task_done(self) -> None:
279
+ """태스크 완료 로그를 남긴다."""
280
+ try:
281
+ write_log_message(f"태스크 완료: {self.todo['id']}")
282
+ except Exception as e:
283
+ handle_application_error("태스크 완료 처리 실패", e, raise_error=False)
284
+
285
+ async def close(self) -> None:
286
+ """큐 종료 훅(필요 시 리소스 정리)."""
287
+ pass
288
+
289
+ def _create_bg_task(self, coro: Any, label: str) -> None:
290
+ """백그라운드 태스크 생성 및 완료 콜백으로 예외 로깅.
291
+
292
+ - 실행 중인 이벤트 루프가 없을 때도 전달된 루프에 안전하게 예약한다.
293
+ """
294
+ try:
295
+ loop = self._loop
296
+ if loop is None:
297
+ try:
298
+ loop = asyncio.get_running_loop()
299
+ except RuntimeError:
300
+ raise
301
+
302
+ def _cb(t: asyncio.Task):
303
+ exc = t.exception()
304
+ if exc:
305
+ handle_application_error(f"백그라운드 태스크 오류({label})", exc, raise_error=False)
306
+
307
+ def _schedule():
308
+ task = loop.create_task(coro)
309
+ task.add_done_callback(_cb)
310
+
311
+ loop.call_soon_threadsafe(_schedule)
312
+ except Exception as e:
313
+ handle_application_error(f"백그라운드 태스크 생성 실패({label})", e, raise_error=False)